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 Places API và API Mã hoá địa lý trong API JavaScript của Maps để tìm kiếm các khu vực và nhận thêm thông tin về các địa điểm. API mã hoá địa lý và Places API là các lựa chọn thay thế mạnh mẽ và ổn định để lấy mã địa điểm. Nếu đang 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 theo hướng dữ liệu cho các ranh giới.

Thêm Địa điểm và Mã hoá địa lý vào ứng dụng API JavaScript Maps của bạn theo 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ể dùng công cụ Tìm kiếm bằng văn bản (Mới) để lấy 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 cần trả về. Việc sử dụng API Tìm kiếm văn bản (Mới) để chỉ yêu cầu mã địa điểm sẽ không bị tính phí. Tìm hiểu thêm.

Bản đồ mẫu này minh hoạ việc đưa ra yêu cầu searchByText để lấy mã địa điểm cho 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 ví dụ 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();

Dùng tính năng Tự động hoàn thành địa điểm để tìm các khu vực

Tiện ích Tự động hoàn thành địa điểm cung cấp một cách thuận tiện để cho phép người dùng 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 nhằm chỉ trả về các khu vực, hãy đặt types thành (regions), như 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 thông tin chi tiết về địa điểm cho một khu vực

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

  • Tìm kiếm mã địa điểm ranh giới dựa trên tên địa điểm.
  • Lấy khung nhìn để thu phóng đến 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 mà sẽ phân giải thành "Tên địa điểm, Tiểu bang, Quốc gia" tại 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 mẫu sau đây tìm ranh giới của Trinidad, CA và căn giữa bản đồ trên kết quả:

Hàm ví dụ sau gọi fetchFields() để lấy thông tin chi tiết về địa điểm, bao gồm cả place.geometry.viewport, sau đó gọi map.fitBounds() để căn giữa bản đồ trên đa giác ranh giới đã 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. Các công cụ sau đây kết hợp hiệu quả với định kiểu dựa trên dữ liệu cho các ranh giới:

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

Xem khung nhìn của 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, bạn có thể truyền khung nhìn này cho hàm map.fitBounds() để thu phóng một đa giác ranh giới trên bản đồ. Ví dụ sau cho thấy việc sử dụng dịch vụ Mã hoá địa lý để tải khung nhìn, 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ã hóa địa lý ngược

Có thể sử dụng mã hóa địa lý ngược để tìm ID địa điểm. Hàm dịch vụ Mã hoá địa lý mẫu sau đây trả về mã địa điểm cho tất cả các thành phần địa chỉ tại toạ độ 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à lệnh gọi dịch vụ web mã hoá địa lý đảo ngược tương đương:

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

Để sử dụng mã hoá địa lý đảo ngược bằng 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 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ã hoá địa lý, thêm các hạn chế về thành phần bằng mã hoá địa lý ngược để nhận được tất cả các thành phần địa chỉ tại vị trí đã chỉ định chỉ 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à lệnh gọi dịch vụ web mã hoá địa lý đảo ngược tương đương:

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