I metodi asincroni dell'API Maps JavaScript di Google restituiscono Promises.
Assistenza
| API | I metodi restituiscono Promises |
|---|---|
| Indicazioni | Sì |
| Distance Matrix | Sì |
| Elevation | Sì |
| Geocoder | Sì |
| Maximum Zoom Imagery | Sì |
| Luoghi | No |
| Places AutocompleteService | Parziale1 |
| Streetview | Sì |
Utilizzo
Consulta questa guida sull'utilizzo di Promises 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 Promise. 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();
Then, catch e finally
L'
oggetto Promise
ha 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);
-
Al momento, Promises è supportato solo in
getPlacePredictions(). ↩