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

请选择平台: iOS JavaScript

您可以使用 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,然后对相应边界应用样式:

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

查看完整的示例源代码

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

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

地点自动补全 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)。
  • 获取采用特定格式的地址。美国区域的地址会解析为“地点名称,州,国家”(例如“Ottumwa, IA, USA”)。
  • 获取照片等其他实用数据。

下例中的函数会找出加利福尼亚州特立尼达市的边界,并将该市设为地图中心:

下例中的函数会调用 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)
        });
}

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

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

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

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