Promesse

I metodi asincroni in tutta l'API JavaScript di Google Maps restituiscono Promises.

Assistenza

API I metodi restituiscono promise
trasporto pubblico
Matrice delle distanze
Elevazione
Geocodificatore
Immagini con zoom massimo
Luoghi No
AutocompleteService di Places Parziale1
Street View

Utilizzo

Consulta questa guida sull'utilizzo di Promises o gli esempi riportati di seguito per effettuare chiamate di metodo asincrone con l'API JavaScript di Google Maps.

asincroni e in attesa

L'operatore attesa viene utilizzato per attendere un comando Promise. Può essere utilizzata solo all'interno di una funzione asincrona.

const app = async () => {
  const elevationService = google.maps.ElevationService();
  const locations = [{lat: 27.986065, lng:86.922623}];

  const response = await elevationService.getElevationForLocation({locations});
  console.log(response.results);
};

app();

Quindi, cattura e infine

L'oggetto Promise dispone di metodi then, catch e finally che acquisiscono funzioni di callback.

const elevationService = google.maps.ElevationService();
const locations = [{lat: 27.986065, lng:86.922623}];

const promise = elevationService.getElevationForLocation({locations});

promise
    .then((response) => {
      console.log(response.results);
    })
    .catch((error) => {
      console.log(error);
    });
    .finally(() => {
      console.log('done');
    });

Sequenza di callback asincrona

Il pattern di callback è ancora valido e supportato.

const elevationService = google.maps.ElevationService();
const locations = [{lat: 27.986065, lng:86.922623}];

const callback = (results, status) => {
  if (status === 'OK') {
    console.log(results);
  } else {
    // handle this case
  }
};

elevationService.getElevationForLocation({locations}, callback);

  1. Al momento le Promise sono supportate solo in getPlacePredictions()