Promises

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

  1. Currently Promises are only supported in getPlacePredictions()

Design a Mobile Site
View Site in Mobile | Classic
Share by: