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

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

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

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

שימוש ב-Places API

שימוש ב'חיפוש טקסט' (חדש) לחיפוש אזור

ניתן לך להשתמש בחיפוש טקסט (חדש) על מנת לקבל מזהה מקום שכולל נתוני אזור, על ידי שימוש ב-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();

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

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