使用 Places API 和地理编码服务来设置边界的数据驱动型样式

您可以使用 Maps JavaScript API 中的 Places API 和 Geocoding API 搜索区域并获取有关地点的更多信息。Geocoding API 和 Places API 是强大且稳定的替代方案,可以用来获取地点 ID。如果您已经在使用地点 ID,也可以轻松地重复使用这些 ID 来设置边界的数据驱动型样式。

您可以通过以下方式将地点服务和地理编码服务添加到您的 Maps JavaScript API 应用:

使用 Places API

使用文本搜索(预览版)查找区域

您可以使用文本搜索(预览版)获取包含区域数据的地点 ID,只需使用 includedType 指定要返回的区域类型。仅使用文本搜索(预览版)API 请求地点 ID 不会产生任何费用。了解详情

以下示例函数会发出 searchByText 请求以获取加利福尼亚州特立尼达市的地点 ID,然后对边界应用样式:

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

    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 = /** @type {!google.maps.FeatureStyleOptions} */({
        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();

使用地点自动补全功能查找区域

地点自动补全 widget 可让您的用户便捷地搜索区域。要将地点自动补全 widget 配置为仅返回区域,请将 types 设置为 (regions),如以下代码段所示:

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

获取某个区域的地点详情

区域的地点详情数据非常有用。例如,您可以:

  • 根据地点名称搜索边界地点 ID。
  • 获取视口以缩放至边界。
  • 获取边界的地图项类型(例如 locality)。
  • 获取格式化地址,在美国,该地址会解析为“地点名称,州,国家”(例如“奥塔姆瓦,爱荷华州,美国”)。
  • 获取其他实用数据,例如照片。

以下示例函数会调用 fetchFields() 来获取地点详情(包括 place.geometry.viewport),然后调用 map.fitBounds(),以便将地图中心设为所选边界多边形。

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);
}

使用 Geocoding API

您可以通过 Geocoding API 将地址转换为地理坐标,反之亦然。以下用法非常适合设置边界的数据驱动型样式:

  • 使用地理编码服务获取某个区域的视口。
  • 向地理编码调用应用组成部分过滤,以获取行政区域 1-4、市行政区或邮政编码的地点 ID。
  • 使用反向地理编码按纬度/经度坐标查找地点 ID,甚至返回特定位置的所有组成部分的地点 ID。

获取某个区域的视口

地理编码服务可以接受地点 ID 并返回视口,您可以将其传递给 map.fitBounds() 函数以缩放到地图上的边界多边形。以下示例说明了如何使用地理编码服务获取视口,然后调用 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)
        });
}

使用反向地理编码

反向地理编码可用于查找地点 ID。以下示例地理编码服务函数会返回指定纬度/经度坐标处所有地址组成部分的地点 ID:

// 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)
        });
}

以下是等效的反向地理编码网络服务调用:

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

将反向地理编码与组成部分过滤结合使用,以获取指定位置处以下一种或多种类型的地址组成部分:

  • administrativeArea
  • country
  • locality
  • postalCode

下一个示例函数说明了如何使用地理编码服务,并为反向地理编码添加组成部分限制,以获取指定位置处仅限 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)
        });
}

以下是等效的反向地理编码网络服务调用:

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