Usa le API Places e la geocodifica con stili basati sui dati per i confini

Seleziona la piattaforma: iOS JavaScript

Puoi utilizzare l'API Places e l'API Geocoding nell'API Maps JavaScript per cercare regioni e ottenere ulteriori informazioni sui luoghi. L'API Geocoding e l'API Places sono alternative potenti e stabili per l'ottenimento degli ID luogo. Se già utilizzi gli ID luogo, puoi facilmente riutilizzarli con uno stile basato sui dati per i confini.

Aggiungi Places e Geocoding alle tue app dell'API Maps JavaScript nei seguenti modi:

Utilizzare l'API Places

Utilizza la ricerca testuale (nuova) per trovare una regione

Puoi utilizzare Ricerca testuale (nuova) per ottenere un ID luogo che includa i dati sulla regione utilizzando includedType per specificare il tipo di regione da restituire. L'utilizzo dell'API Text Search (nuovo) per richiedere solo ID luogo non comporta alcun addebito. Scopri di più.

Questa mappa di esempio mostra come effettuare una richiesta searchByText per ottenere l'ID luogo per Trinidad, California, e applicare lo stile al confine:

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

Guarda l'esempio di codice sorgente completo

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

Utilizzare il completamento automatico di Places per trovare le regioni

Il widget Places Autocomplete consente agli utenti di cercare facilmente le regioni. Per configurare il widget di completamento automatico di Places in modo che restituisca solo le regioni, imposta types su (regions), come mostrato nel seguente snippet:

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

Ottenere i dettagli su un luogo per una regione

I dati sui dettagli del luogo per una regione possono essere molto utili. Ad esempio, puoi:

  • Cerca gli ID dei luoghi dei confini in base ai nomi dei luoghi.
  • Ottieni l'area visibile per eseguire lo zoom su un confine.
  • Ottieni il tipo di caratteristica per il confine (ad esempio locality).
  • Ottieni l'indirizzo formattato, che si risolve in "Nome posizione, stato, paese" nell'area geografica degli Stati Uniti (ad esempio "Ottumwa, IA, USA").
  • Ricevi altri dati utili come le foto.

La seguente funzione di esempio trova il confine di Trinidad, in California, e centra la mappa sul risultato:

La funzione di esempio seguente chiama fetchFields() per ottenere i dettagli sul luogo, tra cui place.geometry.viewport, poi chiama map.fitBounds() per centrare la mappa sul poligono del confine selezionato.

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

Utilizzare l'API Geocoding

L'API Geocoding consente di convertire gli indirizzi in coordinate geografiche e viceversa. I seguenti utilizzi si combinano bene con lo stile basato sui dati per i confini:

  • Utilizza la geocodifica per ottenere l'area visibile per una regione.
  • Applica i filtri dei componenti alla chiamata Geocoding per ottenere gli ID luogo per aree amministrative 1-4, località o codice postale.
  • Utilizza la geocodifica inversa per trovare gli ID luogo in base alle coordinate di latitudine/longitudine o anche restituire gli ID luogo per tutti i componenti di una determinata località.

Ottenere l'area visibile per una regione

Il servizio di geocodifica può acquisire un ID luogo e restituire un'area visibile, che puoi passare alla funzione map.fitBounds() per eseguire lo zoom su un poligono di confine sulla mappa. Nell'esempio seguente viene mostrato l'utilizzo del servizio Geocoding per ottenere un'area visibile, dopodiché viene chiamato 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)
        });
}

Usa geocodifica inversa

Per trovare gli ID luogo è possibile utilizzare la geocodifica inversa. La funzione del servizio di geocodifica dell'esempio seguente restituisce gli ID luogo per tutti i componenti dell'indirizzo alle coordinate di latitudine/longitudine specificate:

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

Questa è la chiamata di servizio web equivalente a geocodifica inversa:

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

Per utilizzare la geocodifica inversa con filtro dei componenti in modo da ottenere il componente indirizzo per uno o più dei seguenti tipi nella posizione specificata:

  • administrativeArea
  • country
  • locality
  • postalCode

La funzione di esempio successiva mostra l'uso del servizio Geocoding, aggiungendo limitazioni dei componenti con geocodifica inversa per ottenere tutti i componenti dell'indirizzo nella posizione specificata solo per il tipo 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)
        });
}

Questa è la chiamata di servizio web equivalente a geocodifica inversa:

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