Promesse

I metodi asincroni nell'API JavaScript di Google Maps restituiscono Promises.

Assistenza

API I metodi restituiscono promesse
trasporto pubblico
Matrice delle distanze
Elevazione
Geocodificatore
Massimo zoom delle immagini
Luoghi No
Places AutocompleteService Parziale1
Street View

Utilizzo

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

Asinc e attendi

L'operatore in attesa viene utilizzato per attendere una promessa. Può essere utilizzato 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();

Poi prendi e infine

L'oggetto Promise ha metodi then, catch e finally che accettano le 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 promesse sono supportate solo in getPlacePredictions()