AI-generated Key Takeaways
-
Asynchronous methods within the Google Maps JavaScript API predominantly return Promises for efficient handling of operations.
-
Numerous Google Maps services, including Directions, Distance Matrix, Elevation, Geocoder, and Streetview, utilize Promises in their methods.
-
Developers can employ async/await, then/catch/finally, or traditional callbacks to manage asynchronous operations and responses effectively.
-
While Places generally do not utilize Promises, the
getPlacePredictions()
method within the Places AutocompleteService does offer partial Promise support. -
Beginning in 2020, all newly introduced APIs within the Google Maps JavaScript API exclusively support Promises for asynchronous operations.
Asynchronous methods throughout Google Maps JavaScript API return Promises.
Support
API | Methods return Promises |
---|---|
Directions | Yes |
Distance Matrix | Yes |
Elevation | Yes |
Geocoder | Yes |
Maximum Zoom Imagery | Yes |
Places | No |
Places AutocompleteService | Partial1 |
Streetview | Yes |
Usage
See this guide on using Promises or the examples below for making asynchronous method calls with Google Maps JavaScript API.
Async and await
The await operator is used to wait for a Promise. It can only be used inside an async function.
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, and finally
The
Promise object
has then
, catch
, and finally
methods that take callback functions.
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');
});
Async callback pattern
The callback pattern is still valid and supported.
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);
-
Currently Promises are only supported in
getPlacePredictions()
. ↩