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

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

Nhà phát triển ở Khu vực kinh tế Châu Âu (EEA)

Bạn có thể sử dụng Places API và Geocoding API trong Maps JavaScript API để tìm kiếm khu vực và xem thêm thông tin về địa điểm. Geocoding API và Places API là những giải pháp 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 tính năng định kiểu dựa trên dữ liệu cho ranh giới.

Thêm Địa điểm và Mã hoá địa lý vào ứng dụng Maps JavaScript API theo những cách sau:

Sử dụng Places API

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 bao gồm 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 mất phí khi 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 này minh hoạ cách tạo 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 = {
        textQuery: 'Trinidad, CA',
        fields: ['id', 'location'],
        includedType: 'locality',
        locationBias: center,
    };

    const { Place } = await google.maps.importLibrary('places');
    const { places } = await Place.searchByText(request);

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

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

    // Define the feature style function.
    featureLayer.style = (params: google.maps.FeatureStyleFunctionOptions) => {
        const placeFeature = params.feature as google.maps.PlaceFeature;
        if (placeFeature.placeId === placeid) {
            return styleFill;
        }
        return null;
    };
}

JavaScript

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

    const { Place } = await google.maps.importLibrary('places');
    const { places } = await Place.searchByText(request);

    if (places.length) {
        const place = places[0];
        styleBoundary(place.id);
        innerMap.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) => {
        const placeFeature = params.feature;
        if (placeFeature.placeId === placeid) {
            return styleFill;
        }
        return null;
    };
}

Xem mã nguồn ví dụ hoàn chỉnh

TypeScript

let innerMap: google.maps.Map;
let featureLayer: google.maps.FeatureLayer;
let center: google.maps.LatLngLiteral;

async function init() {
    // Load the needed libraries.
    await google.maps.importLibrary('maps');

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

    // Get the gmp-map element.
    const mapElement = document.querySelector('gmp-map')!;

    // Get the inner map.
    innerMap = mapElement.innerMap;

    // Get the LOCALITY feature layer.
    featureLayer = innerMap.getFeatureLayer('LOCALITY');

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

    const { Place } = await google.maps.importLibrary('places');
    const { places } = await Place.searchByText(request);

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

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

    // Define the feature style function.
    featureLayer.style = (params: google.maps.FeatureStyleFunctionOptions) => {
        const placeFeature = params.feature as google.maps.PlaceFeature;
        if (placeFeature.placeId === placeid) {
            return styleFill;
        }
        return null;
    };
}
void init();

JavaScript

let innerMap;
let featureLayer;
let center;

async function init() {
    // Load the needed libraries.
    await google.maps.importLibrary('maps');

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

    // Get the gmp-map element.
    const mapElement = document.querySelector('gmp-map');

    // Get the inner map.
    innerMap = mapElement.innerMap;

    // Get the LOCALITY feature layer.
    featureLayer = innerMap.getFeatureLayer('LOCALITY');

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

    const { Place } = await google.maps.importLibrary('places');
    const { places } = await Place.searchByText(request);

    if (places.length) {
        const place = places[0];
        styleBoundary(place.id);
        innerMap.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) => {
        const placeFeature = params.feature;
        if (placeFeature.placeId === placeid) {
            return styleFill;
        }
        return null;
    };
}
void init();

Sử dụng tính năng Place Autocomplete để tìm khu vực

Tiện ích Place Autocomplete cung cấp một cách thuận tiện để cho phép người dùng tìm kiếm khu vực. Để định cấu hình tiện ích Place Autocomplete chỉ trả về các vùng, hãy đặt includedPrimaryTypes thành (regions), như trong đoạn mã sau:

// Set up the Autocomplete widget to return only region results.
placeAutocomplete = document.querySelector(
    'gmp-place-autocomplete'
) as google.maps.places.PlaceAutocompleteElement;
placeAutocomplete.includedPrimaryTypes = ['(regions)'];

Xem thông tin chi tiết về địa điểm của một khu vực

Dữ liệu Place Details của 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.
  • Lấy khung nhìn để thu phóng đến một 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, chẳng hạn như bài đánh giá và ảnh của người dùng.

Hàm ví dụ sau đây tìm ranh giới cho Trinidad, CA và căn giữa bản đồ theo kết quả:

Ví dụ sau đây gọi hàm fetchFields() để lấy Place Details, bao gồm cả place.viewport, sau đó gọi hàm 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 data fields you want.
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'viewport', 'types'] });

        // Zoom to the boundary polygon.
        let viewport = place.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 Geocoding API

Geocoding API cho phép bạn chuyển đổi địa chỉ thành toạ độ địa lý và ngược lại. Các trường hợp sử dụng sau đây kết hợp hiệu quả với tính năng định kiểu dựa trên dữ liệu cho ranh giới:

  • Sử dụng tính năng Mã hoá địa lý để lấy 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ã hoá địa lý để lấy mã địa điểm cho khu vực hành chính 1-4, địa phương hoặc mã bưu chính.
  • Sử dụng tính nă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ả thành phần ở một vị trí cụ thể.

Lấy khung nhìn cho một khu vực

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

Bạn có thể sử dụng tính năng mã hoá địa lý ngược để tìm mã địa điểm. Hàm dịch vụ Mã hoá địa lý trong ví dụ sau đây trả về mã địa điểm cho tất 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)
        });
}

Dưới đây là lệnh gọi dịch vụ web mã hoá địa lý ngược tương đương:

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

Cách sử dụng tính năng mã hoá địa lý ngược có 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 cách sử dụng dịch vụ Mã hoá địa lý, thêm các quy định hạn chế về thành phần bằng tính năng mã hoá địa lý ngược để lấy tất 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ý ngược tương đương:

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