שימוש ב-Places APIs וב-Geocoding עם עיצוב מבוסס-נתונים לגבולות

בחירת פלטפורמה: Android iOS JavaScript

מפתחים באזור הכלכלי האירופי (EEA)

אפשר להשתמש ב-Places API וב-Geocoding API ב-Maps JavaScript API כדי לחפש אזורים ולקבל מידע נוסף על מקומות. ‫Geocoding API ו-Places API הם חלופות יציבות ושימושיות לקבלת מזהי מקומות. אם אתם כבר משתמשים במזהי מקומות, אתם יכולים בקלות להשתמש שוב במזהים האלה כדי להגדיר סגנון מבוסס-נתונים לגבולות.

כדי להוסיף את Places API ואת Geocoding API לאפליקציות שלכם ב-Maps JavaScript API, אפשר להשתמש באחת מהשיטות הבאות:

שימוש ב-Places API

אתם יכולים להשתמש ב-Text Search (New) כדי לקבל מזהה של מקום שכולל נתונים של אזור. לשם כך, צריך להשתמש בפרמטר includedType כדי לציין את סוג האזור שרוצים לקבל. לא יחול חיוב על שימוש ב-Text Search (New) API כדי לבקש רק מזהי מקומות. מידע נוסף

במפה לדוגמה הזו מוצגת בקשת searchByText לקבלת מזהה המקום של טרינידד, קליפורניה, ולאחר מכן החלת סגנון על הגבול:

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

שימוש בהשלמה אוטומטית של מקומות כדי למצוא אזורים

בווידג'ט Places Autocomplete יש דרך נוחה לאפשר למשתמשים לחפש אזורים. כדי להגדיר את הווידג'ט של השלמה אוטומטית של מקומות כך שיחזיר רק אזורים, מגדירים את types ל-(regions), כמו שמוצג בקטע הקוד הבא:

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

קבלת פרטים על מקום באזור מסוים

הנתונים של פרטי המקום באזור מסוים יכולים להיות מאוד שימושיים. לדוגמה, אפשר:

  • חיפוש מזהי מקומות של גבולות על סמך שמות מקומות.
  • קבלת אזור התצוגה כדי לשנות את המרחק לגבול.
  • מקבלים את סוג התכונה של הגבול (לדוגמה 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 data fields you want.
        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 מאפשר להמיר כתובות לקואורדינטות גאוגרפיות, ולהיפך. השימושים הבאים משתלבים היטב עם סגנון מבוסס-נתונים לגבולות:

  • אפשר להשתמש בגיאו-קידוד כדי לקבל את אזור התצוגה של אזור מסוים.
  • אפשר להחיל סינון רכיבים על קריאת ה-Geocoding כדי לקבל את מזהי המקומות של אזורים אדמיניסטרטיביים 1-4, של יישובים או של מיקודים.
  • אפשר להשתמש בגיאו-קידוד הפוך כדי למצוא מזהי מקומות לפי קואורדינטות של קו רוחב וקו אורך, או אפילו להחזיר מזהי מקומות לכל הרכיבים במיקום מסוים.

קבלת אזור התצוגה של אזור מסוים

שירות הגיאו-קידוד יכול לקבל מזהה של מקום ולהחזיר אזור תצוגה, שאפשר להעביר לפונקציה 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)

אפשר להשתמש בהמרת קואורדינטות לכתובות כדי למצוא מזהי מקומות. בדוגמה הבאה, פונקציית שירות הגיאוקודינג מחזירה את מזהי המקומות של כל רכיבי הכתובת בקואורדינטות של קו הרוחב וקו האורך שצוינו:

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

זוהי קריאה שקולה לשירות אינטרנט של המרת קואורדינטות לכתובות:

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

זוהי קריאה שקולה לשירות האינטרנט של המרת קואורדינטות לכתובות:

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