Sử dụng API Địa điểm và Mã hoá địa lý bằng tính năng định kiểu theo hướng dữ liệu cho các ranh giới

Chọn nền tảng: iOS JavaScript

Bạn có thể sử dụng API địa điểm và API mã hoá địa lý trong API JavaScript của Maps để tìm kiếm các khu vực và nhận được nhiều hơn thông tin về địa điểm. API mã hoá địa lý và API địa điểm là các lựa chọn thay thế mạnh mẽ và ổn định để lấy mã địa điểm. Nếu bạn đã bằng cách sử dụng mã địa điểm, bạn có thể dễ dàng sử dụng lại các mã đó bằng cách định kiểu dựa trên dữ liệu cho các ranh giới.

Thêm Địa điểm và Mã hoá địa lý vào ứng dụng Maps JavaScript API của bạn trong các cách sau:

Sử dụng Places API

Sử dụng tính năng Tìm kiếm văn bản (Mới) để tìm khu vực

Bạn có thể sử dụng tính năng Tìm kiếm văn bản (Mới) để nhận mã địa điểm có chứa dữ liệu khu vực bằng cách sử dụng includedType để chỉ định loại khu vực quay lại. Sử dụng API Tìm kiếm văn bản (Mới) để chỉ bị tính mã địa điểm yêu cầu. Tìm hiểu thêm.

Bản đồ mẫu này minh hoạ việc yêu cầu searchByText để lấy địa điểm Mã của Trinidad, CA, sau đó áp dụng kiểu cho ranh giới:

TypeScript

async function findBoundary() {
    const request = {
        query: 'Trinidad, CA',
        fields: ['id', 'location'],
        includedType: 'locality',
        locationBias: center,
    };

    const { Place } = await google.maps.importLibrary("places") as google.maps.PlacesLibrary;
    //@ts-ignore
    const { places } = await Place.searchByText(request);

    if (places.length) {
        const place = places[0];
        styleBoundary(place.id);
        map.setCenter(place.location);
    } else {
        console.log('No results');
    }
}

function styleBoundary(placeid) {
    // Define a style of transparent purple with opaque stroke.
    const styleFill = {
        strokeColor: '#810FCB',
        strokeOpacity: 1.0,
        strokeWeight: 3.0,
        fillColor: '#810FCB',
        fillOpacity: 0.5
    };

    // Define the feature style function.
    featureLayer.style = (params) => {
        if (params.feature.placeId == placeid) {
            return styleFill;
        }
    };
}

JavaScript

async function findBoundary() {
  const request = {
    query: "Trinidad, CA",
    fields: ["id", "location"],
    includedType: "locality",
    locationBias: center,
  };
  const { Place } = await google.maps.importLibrary("places");
  //@ts-ignore
  const { places } = await Place.searchByText(request);

  if (places.length) {
    const place = places[0];

    styleBoundary(place.id);
    map.setCenter(place.location);
  } else {
    console.log("No results");
  }
}

function styleBoundary(placeid) {
  // Define a style of transparent purple with opaque stroke.
  const styleFill = {
    strokeColor: "#810FCB",
    strokeOpacity: 1.0,
    strokeWeight: 3.0,
    fillColor: "#810FCB",
    fillOpacity: 0.5,
  };

  // Define the feature style function.
  featureLayer.style = (params) => {
    if (params.feature.placeId == placeid) {
      return styleFill;
    }
  };
}

Xem mã nguồn mẫu hoàn chỉnh

TypeScript

let map;
let featureLayer;
let center;

async function initMap() {
    const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;

    center = {lat: 41.059, lng: -124.151}; // Trinidad, CA

    map = new Map(document.getElementById('map') as HTMLElement, {
        center: center,
        zoom: 15,
        // In the cloud console, configure this Map ID with a style that enables the
        // "Locality" Data Driven Styling type.
        mapId: 'a3efe1c035bad51b', // <YOUR_MAP_ID_HERE>,
    });

    featureLayer = map.getFeatureLayer('LOCALITY');

    findBoundary();
}
async function findBoundary() {
    const request = {
        query: 'Trinidad, CA',
        fields: ['id', 'location'],
        includedType: 'locality',
        locationBias: center,
    };

    const { Place } = await google.maps.importLibrary("places") as google.maps.PlacesLibrary;
    //@ts-ignore
    const { places } = await Place.searchByText(request);

    if (places.length) {
        const place = places[0];
        styleBoundary(place.id);
        map.setCenter(place.location);
    } else {
        console.log('No results');
    }
}

function styleBoundary(placeid) {
    // Define a style of transparent purple with opaque stroke.
    const styleFill = {
        strokeColor: '#810FCB',
        strokeOpacity: 1.0,
        strokeWeight: 3.0,
        fillColor: '#810FCB',
        fillOpacity: 0.5
    };

    // Define the feature style function.
    featureLayer.style = (params) => {
        if (params.feature.placeId == placeid) {
            return styleFill;
        }
    };
}
initMap();

JavaScript

let map;
let featureLayer;
let center;

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  center = { lat: 41.059, lng: -124.151 }; // Trinidad, CA
  map = new Map(document.getElementById("map"), {
    center: center,
    zoom: 15,
    // In the cloud console, configure this Map ID with a style that enables the
    // "Locality" Data Driven Styling type.
    mapId: "a3efe1c035bad51b", // <YOUR_MAP_ID_HERE>,
  });
  featureLayer = map.getFeatureLayer("LOCALITY");
  findBoundary();
}

async function findBoundary() {
  const request = {
    query: "Trinidad, CA",
    fields: ["id", "location"],
    includedType: "locality",
    locationBias: center,
  };
  const { Place } = await google.maps.importLibrary("places");
  //@ts-ignore
  const { places } = await Place.searchByText(request);

  if (places.length) {
    const place = places[0];

    styleBoundary(place.id);
    map.setCenter(place.location);
  } else {
    console.log("No results");
  }
}

function styleBoundary(placeid) {
  // Define a style of transparent purple with opaque stroke.
  const styleFill = {
    strokeColor: "#810FCB",
    strokeOpacity: 1.0,
    strokeWeight: 3.0,
    fillColor: "#810FCB",
    fillOpacity: 0.5,
  };

  // Define the feature style function.
  featureLayer.style = (params) => {
    if (params.feature.placeId == placeid) {
      return styleFill;
    }
  };
}

initMap();

Sử dụng tính năng Tự động hoàn thành của địa điểm để tìm khu vực

Tiện ích Tự động hoàn thành dành cho địa điểm cung cấp một cách thuận tiện để người dùng của bạn tìm kiếm các khu vực. Để định cấu hình tiện ích Tự động hoàn thành địa điểm để chỉ trả về khu vực, đặt types thành (regions), như được minh hoạ trong đoạn mã sau:

// Set up the Autocomplete widget to return only region results.
const autocompleteOptions = {
  fields: ["place_id", "type"],
  strictBounds: false,
  types: ["(regions)"],
};

Xem chi tiết địa điểm cho một khu vực

Dữ liệu chi tiết địa điểm cho một khu vực có thể khá hữu ích. Ví dụ như bạn có thể:

  • Tìm mã địa điểm ở ranh giới dựa trên tên địa điểm.
  • Tải khung nhìn để thu phóng ranh giới.
  • Lấy loại đối tượng cho ranh giới (ví dụ: locality).
  • Lấy địa chỉ được định dạng, phân giải thành "Tên địa điểm, Tiểu bang, Quốc gia" ở khu vực Hoa Kỳ (ví dụ: "Ottumwa, IA, Hoa Kỳ").
  • Nhận dữ liệu hữu ích khác như ảnh.

Hàm ví dụ sau đây tìm ranh giới của Trinidad, CA và trung tâm bản đồ trên kết quả:

Hàm ví dụ sau đây gọi fetchFields() để lấy thông tin chi tiết về địa điểm bao gồm place.geometry.viewport, sau đó gọi map.fitBounds() để căn giữa trên đa giác ranh giới được chọn.

    async function getPlaceDetails(placeId) {
        // Use place ID to create a new Place instance.
        const place = new google.maps.places.Place({
            id: placeId,
        });

        // Call fetchFields, passing the desired data fields.
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'geometry', 'type'] });

        // Zoom to the boundary polygon.
        let viewport = place.geometry.viewport;
        map.fitBounds(viewport, 155);

        // Print some place details to the console.
        const types = place.types;
        console.log("Feature type: " + types[0]);
        console.log("Formatted address: " + place.formattedAddress);
    }

Sử dụng API mã hóa địa lý

API mã hoá địa lý cho phép bạn chuyển đổi địa chỉ thành toạ độ địa lý và ngược lại. Nội dung sau đây sử dụng kết hợp tốt với định kiểu theo hướng dữ liệu cho các ranh giới:

  • Sử dụng Mã hóa địa lý để nhận chế độ xem cho một khu vực.
  • Áp dụng lọc thành phần cho cuộc gọi Mã hóa địa lý của bạn để lấy ID địa điểm cho khu vực hành chính 1-4, địa phương hoặc mã bưu điện.
  • Sử dụng mã hóa địa lý ngược để tìm mã địa điểm theo vĩ độ/kinh độ, hoặc thậm chí còn trả về mã địa điểm cho tất cả thành phần ở một vị trí cụ thể.

Tải khung nhìn cho một khu vực

Dịch vụ Mã hoá địa lý có thể lấy một mã địa điểm và trả về một khung nhìn mà bạn có thể truyền đến map.fitBounds() để phóng to đa giác ranh giới trên bản đồ. Ví dụ sau cho thấy sử dụng dịch vụ Mã hóa địa lý để có chế độ xem, sau đó gọi map.fitBounds():

// Set up the geocoder.
geocoder = new google.maps.Geocoder();

...

// Call Geocoding API and zoom to the resulting bounds.
function zoomToPolygon(placeid) {
    geocoder
        .geocode({ placeId: placeid })
        .then(({ results }) => {
            map.fitBounds(results[0].geometry.viewport, 155);
        })
        .catch((e) => {
            console.log('Geocoder failed due to: ' + e)
        });
}

Sử dụng mã hoá địa lý ngược

Mã hóa địa lý ngược có thể được sử dụng để tìm ID địa điểm. Mã hoá địa lý ví dụ sau hàm service trả về ID địa điểm cho tất cả thành phần địa chỉ tại vĩ độ/kinh độ được chỉ định:

// Set up the geocoder.
geocoder = new google.maps.Geocoder();

...

// Call Geocoding API.
function getPlaceIds(latLng) {
    geocoder
        .geocode({ latLng })
        .then(({ results }) => {
            console.log('Geocoding result:');
            console.log(results[0]);
            console.log(results[0].place_id);
            console.log(results[0].address_components);
        })
        .catch((e) => {
            console.log('Geocoder failed due to: ' + e)
        });
}

Đây là kỹ thuật mã hoá địa lý ngược tương đương Cuộc gọi dịch vụ web:

https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930

Để sử dụng mã hóa địa lý ngược với tính năng lọc thành phần để lấy thành phần địa chỉ cho một hoặc nhiều loại sau đây tại vị trí được chỉ định:

  • administrativeArea
  • country
  • locality
  • postalCode

Hàm ví dụ tiếp theo cho thấy việc sử dụng dịch vụ Mã hóa địa lý, thêm thành phần với mã hoá địa lý ngược để có được tất cả các thành phần địa chỉ tại vị trí được chỉ định riêng cho loại locality:

// Set up the geocoder.
geocoder = new google.maps.Geocoder();

...

function getPlaceIdWithRestrictions(latLng) {
    geocoder
        .geocode({ latLng,
            componentRestrictions: {
              country: "US",
              locality: "chicago",
            },
        })
        .then(({ results }) => {
            console.log('Geocoding result with restriction:');
            console.log(results[0]);
            console.log(results[0].place_id);
            console.log(results[0].address_components);
            console.log(results[0].address_components[1].types[0]);
            console.log(results[0].address_components[1].long_name);
        })
        .catch((e) => {
            console.log('getPlaceId Geocoder failed due to: ' + e)
        });
}

Đây là kỹ thuật mã hoá địa lý ngược tương đương Cuộc gọi dịch vụ web:

https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930&result_type=locality