JavaScript: how to use the Google Maps API with Promises and async/await

JavaScript: how to use the Google Maps API with Promises and async/await

In JavaScript we can use the Google Maps API with Promises and async/await.

In JavaScript we can use the Google Maps API with Promises and async/await.

The example below shows how to create a Google Maps with a geocoder. Our Promise will return the address coordinates if the request was successful or an error message if something went wrong with our request.

Within the async/await block we're going to display the dynamic map if the geolocation routine returned the correct coordinates or a static map in case of an error. Note how the way we're using the Google Maps API basically remains the same. What it's different here is only how our code is designed and organised.


'use strict';

const getAddress = address => {
    return new Promise((resolve, reject) => {
        const geocoder = new google.maps.Geocoder();
        geocoder.geocode({address: address}, (results, status) => {
            if (status === 'OK') {
                resolve(results[0].geometry.location);
            } else {
                reject(status);
            }    
        });    
    });
};

const createMap = async () => {
    let element = document.querySelector('#map');
    try {
        
        let map = new google.maps.Map(element, { zoom: 16 });
        let location = await getAddress('Via San Michele 162, Vasto');

         map.setCenter(location);

         let marker = new google.maps.Marker({
                    map: element,
                    position: location
          });
    } catch(err) {
        console.warn(err);

        element.innerHTML = '<img src="/images/static-map.jpg" alt="">';
    }
};

Example usage:


'use strict';

document.addEventListener('DOMContentLoaded', () => {
    createMap();
});