שימוש בממשקי API של מקומות ובקידוד גיאוגרפי עם סגנון מבוסס-נתונים להגדרת גבולות

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

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

אפשר להוסיף מקומות וקידוד גיאוגרפי לאפליקציות של Maps JavaScript API בדרכים הבאות:

שימוש ב-Places API

איך משתמשים בחיפוש טקסט (חדש) כדי למצוא אזור

תוכלו להשתמש ב-Text Search (New) כדי לקבל מזהה מקום שכולל נתוני אזור, על ידי שימוש ב-includedType כדי לציין את סוג האזור שרוצים להחזיר. לא יתבצע חיוב על שימוש ב-Text Search API (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();

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

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

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

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

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

  • חיפוש מזהים של מקומות גבולות לפי שמות של מקומות.
  • קבלת אזור התצוגה לשינוי מרחק התצוגה עד לגבול.
  • מקבלים את סוג התכונה עבור הגבול (לדוגמה locality).
  • מוצאים את הכתובת בפורמט המתאים, שמתחילה ב-'Place Name, State, Country' באזור ישראל (לדוגמה, '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, יישוב או מיקוד.
  • אפשר להשתמש בקידוד גיאוגרפי הפוך כדי למצוא מזהי מקומות לפי קואורדינטות של קו רוחב או קו אורך, או אפילו להחזיר מזהי מקומות לכל הרכיבים במיקום מסוים.

חיפוש אזור התצוגה של אזור מסוים

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

שימוש בקידוד גיאוגרפי הפוך

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

// 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