Promises

Asynchronous methods throughout Google Maps JavaScript API will soon be returning Promises. Currently, these methods take a request object and a callback. In the future, this callback will become optional and a Promise will always be returned.

Support

Promise support requires the use of the beta version of Maps JS. Use v=beta to load the beta features.

<script defer
    src="https://maps.googleapis.com/maps/api/js?v=beta&key=YOUR_API_KEY&callback=initMap">
</script>
API Methods return Promises
Directions Yes
Distance Matrix Yes
Elevation Yes
Geocoder Yes
Maximum Zoom Imagery No
Places No
Streetview No

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);