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

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

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

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

שימוש ב-Places API

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

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