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 thêm thông tin về các địa điểm. API mã hóa đị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 đã 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 API Maps JavaScript 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ể sử dụng tính năng Tìm kiếm văn bản (Mới) để lấy mã địa điểm 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ề. Bạn sẽ không phải trả phí nếu sử dụng API Tìm kiếm văn bản (Mới) để chỉ yêu cầu mã địa điểm. Tìm hiểu thêm.

Bản đồ mẫu sau minh hoạ việc gửi một 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 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 mang đến 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 của đị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 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" 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 ví dụ sau đây tìm ranh giới của Trinidad, CA và căn giữa bản đồ vào kết quả đó:

Hàm mẫu sau đây 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 các địa chỉ thành toạ độ địa lý và ngược lại. Các cách sử dụng sau đây 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 tính năng lọc thành phần cho cuộc gọi Mã hoá địa lý của bạn để 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 toạ độ vĩ độ/kinh độ, hoặc thậm chí trả về mã địa điểm cho tất cả cá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ể chuyển đến hàm map.fitBounds() để thu phóng đ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ý để có 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ã hoá địa lý ngược

Mã hóa địa lý ngược có thể được sử dụng để tìm ID địa điểm. Ví dụ sau đây về hàm dịch vụ Mã hoá địa lý trả về mã địa điểm cho tất cả các thành phần địa chỉ tại các 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ý ngược với tính năng lọc thành phần nhằm 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 bằng cách sử dụng dịch vụ Mã hoá địa lý, thêm các hạn chế thành phần bằng mã hoá địa lý ngược để nhận tất cả các thành phần địa chỉ tại vị trí được 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