Promesse

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

Assistenza

API I metodi restituiscono promesse
Indicazioni Sì
Distance Matrix Sì
Elevazione Sì
Geocoder Sì
Immagini con zoom massimo Sì
Luoghi No
Places AutocompleteService Parziale1
Streetview Sì

Utilizzo

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

Async e await

L'operatore await 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 i metodi then, catch e finally che accettano 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');
    });

Pattern di callback asincrono

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(). ↩