אתם יכולים להשתמש ב-Places API וב-Geocoding API ב-Maps JavaScript API כדי לחפש אזורים ולקבל מידע נוסף על מקומות. Geocoding API ו-Places API הם חלופות יציבות ושימושיות לקבלת מזהי מקומות. אם אתם כבר משתמשים במזהי מקומות, אתם יכולים להשתמש בהם בקלות עם סגנון מבוסס-נתונים לגבולות.
אפשר להוסיף את Places API ואת Geocoding API לאפליקציות של Maps JavaScript API בדרכים הבאות:
- Places Library, Maps JavaScript API מאפשרת לאפליקציה לחפש מקומות, וכוללת ווידג'ט של השלמה אוטומטית.
- Places API מחזיר מידע על מקומות באמצעות בקשות HTTP.
- שירות המרת הכתובות לקואורדינטות והכיתה Geocoder יכולים להמיר כתובות לקואורדינטות וקואורדינטות לכתובות באופן דינמי על סמך קלט מהמשתמש.
- Geocoding API מאפשר לכם להמיר לקואורדינטות כתובות סטטיות ידועות.
שימוש ב-Places API
שימוש בחיפוש טקסט (חדש) כדי למצוא אזור
אתם יכולים להשתמש ב-חיפוש טקסט (חדש) כדי לקבל מזהה מקום שכולל נתונים של אזור. לשם כך, צריך להשתמש בפרמטר includedType כדי לציין את סוג האזור שרוצים לקבל. לא יחול חיוב על שימוש ב-Text Search (New) API כדי לבקש רק מזהי מקומות. מידע נוסף
במפה לדוגמה הזו מוצגת בקשת searchByText לקבלת מזהה המקום של טרינידד, קליפורניה, ואז החלת סגנון על הגבול:
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; }; }
קוד מקור מלא לדוגמה
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();
שימוש בהשלמה אוטומטית למקומות כדי למצוא אזורים
הווידג'ט "השלמה אוטומטית למקומות" מאפשר למשתמשים לחפש אזורים בקלות. כדי להגדיר את הווידג'ט השלמה אוטומטית למקומות כך שיחזיר רק אזורים, מגדירים את includedPrimaryTypes ל-(regions), כמו שמוצג בקטע הקוד הבא:
// Set up the Autocomplete widget to return only region results.
placeAutocomplete = document.querySelector(
'gmp-place-autocomplete'
) as google.maps.places.PlaceAutocompleteElement;
placeAutocomplete.includedPrimaryTypes = ['(regions)'];
קבלת פרטי מקום לאזור מסוים
הנתונים של Place Details באזור מסוים יכולים להיות שימושיים מאוד. לדוגמה, אתם יכולים:
- חיפוש מזהי מקומות של גבולות לפי שמות המקומות.
- קבלת אזור התצוגה לשינוי מרחק התצוגה לגבול.
- מאתרים את סוג המאפיין של הגבול (לדוגמה,
locality). - מקבלים את הכתובת בפורמט המתאים, שמופיעה כ'שם המקום, המדינה, המדינה' באזור ארצות הברית (לדוגמה, 'Ottumwa, IA, USA').
- לקבל נתונים שימושיים אחרים, כמו ביקורות ותמונות של משתמשים.
הפונקציה לדוגמה הבאה מוצאת את הגבול של טרינידד, קליפורניה, וממרכזת את המפה בתוצאה:
בדוגמה הבאה, הפונקציה קוראת ל-fetchFields() כדי לקבל את פרטי המקום, כולל place.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 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);
}
שימוש ב-Geocoding API
באמצעות Geocoding API אפשר להמיר כתובות לקואורדינטות גיאוגרפיות, ולהפך. השימושים הבאים מתאימים לשילוב עם סגנון מבוסס-נתונים לגבולות:
- משתמשים בהמרת כתובות לקואורדינטות (geocoding) כדי לקבל את אזור התצוגה של אזור מסוים.
- כדי לקבל את מזהי המקומות של אזורים מנהליים 1-4, יישובים או מספרי מיקוד, צריך להפעיל סינון רכיבים בקריאה להמרת כתובות לקואורדינטות.
- אפשר להשתמש בהמרת קואורדינטות לכתובות (reverse geocoding) כדי למצוא מזהי מקומות לפי קואורדינטות של קווי רוחב ואורך, או אפילו להחזיר מזהי מקומות לכל הרכיבים במיקום מסוים.
קבלת אזור התצוגה של אזור מסוים
שירות Geocoding יכול לקבל מזהה מקום ולהחזיר אזור תצוגה, שאפשר להעביר לפונקציה map.fitBounds() כדי לשנות את מרחק התצוגה לפוליגון גבול במפה. בדוגמה הבאה מוצג שימוש בשירות Geocoding כדי לקבל אזור תצוגה, ואז קריאה ל-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)
});
}
שימוש בהמרת קואורדינטות לכתובות (reverse geocoding)
אפשר להשתמש בהמרת קואורדינטות לכתובות (reverse geocoding) כדי למצוא מזהי מקומות. בדוגמה הבאה, פונקציית שירות הגיאוקודינג מחזירה את מזהי המקומות של כל רכיבי הכתובת בקואורדינטות של קו הרוחב וקו האורך שצוינו:
// 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)
});
}
זוהי קריאת שירות האינטרנט המקבילה של המרת קואורדינטות לכתובות (reverse geocoding):
```html
https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930
```
כדי להשתמש בהמרת קואורדינטות לכתובות עם סינון רכיבים כדי לקבל את רכיב הכתובת של אחד או יותר מהסוגים הבאים במיקום שצוין:
administrativeAreacountrylocalitypostalCode
הפונקציה הבאה לדוגמה מראה איך להשתמש בשירות Geocoding, להוסיף הגבלות על רכיבים עם המרת קואורדינטות לכתובות כדי לקבל את כל רכיבי הכתובת במיקום שצוין רק לסוג 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)
});
}
זוהי קריאה שקולה לשירות אינטרנט של המרת קואורדינטות לכתובות (reverse geocoding):
```html
https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930&result_type=locality
```