您可以在 Maps JavaScript API 中使用 Places API 和 Geocoding API 來搜尋區域,並取得地點的詳細資訊。Geocoding API 和 Places API 是功能強大且穩定的替代方案,可用於取得地點 ID。如果您已在使用地點 ID,就能透過界線資料導向樣式輕鬆重複使用這些 ID。
在 Maps JavaScript API 應用程式中加入 Places API 和 Geocoding API 的方法如下:
- Maps JavaScript API Places Library 可讓您的應用程式搜尋地點,且包含自動完成小工具。
- Places API 會使用 HTTP 要求傳回地點資訊。
- 地理編碼服務和地理編碼器類別可以根據使用者輸入內容,動態進行地理編碼及反向地理編碼。
- Geocoding API 可讓您針對已知靜態地址進行地理編碼。
使用 Places API
使用 Text Search (預先發布版) 尋找區域
您可以使用 Text Search (預先發布版) 取得包含區域資料的地點 ID,方法是使用 includedType
指定要傳回的區域類型。如果僅使用 Text Search (預先發布版) 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();
使用 Places Autocomplete 尋找區域
Places Autocomplete 小工具方便您的使用者搜尋區域。如要將 Places Autocomplete 小工具設為只傳回區域,請將 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)
});
}
這相當於反向地理編碼網路服務呼叫:
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