Promesse

Restituzione di metodi asincroni attraverso l'API JavaScript di Google Maps Promesse.

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

Visualizza 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

La 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

La Oggetto Promesso include metodi then, catch e finally che assumono 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

La pattern di callback sia 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()