Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple class for loading the Google Maps Javascript API in browser async using ES6 and Promise
/**
* Use this class to ensure Google Maps API javascript is loaded before running any google map specific code.
*/
export class GoogleMapsApi {
/**
* Constructor set up config.
*/
constructor() {
// api key for google maps
this.apiKey = 'your api key here';
// set a globally scoped callback if it doesn't already exist
if (!window._GoogleMapsApi) {
this.callbackName = '_GoogleMapsApi.mapLoaded';
window._GoogleMapsApi = this;
window._GoogleMapsApi.mapLoaded = this.mapLoaded.bind(this);
}
}
/**
* Load the Google Maps API javascript
*/
load() {
if (!this.promise) {
this.promise = new Promise(resolve => {
this.resolve = resolve;
if (typeof window.google === 'undefined') {
const script = document.createElement('script');
script.src = `//maps.googleapis.com/maps/api/js?key=${this.apiKey}&callback=${this.callbackName}`;
script.async = true;
document.body.append(script);
} else {
this.resolve();
}
});
}
return this.promise;
}
/**
* Globally scoped callback for the map loaded
*/
mapLoaded() {
if (this.resolve) {
this.resolve();
}
}
}
// example of using that class
import GoogleMapsApi from './GoogleMapsApi';
const gmapApi = new GoogleMapsApi();
gmapApi.load().then(() => {
// safe to start using the API now
new google.maps.Map(document.querySelector('.map-container'));
// etc.
});
@mavame

This comment has been minimized.

Copy link
Owner Author

mavame commented Sep 12, 2017

To use this make sure ES6 promises are supported or polyfilled.

@JonSilver

This comment has been minimized.

Copy link

JonSilver commented Mar 17, 2018

Thank you so much for showing the way with this... perfect for when you just need Google Maps Javascript API services without all any visuals.

@OksanaRomaniv

This comment has been minimized.

Copy link

OksanaRomaniv commented Apr 22, 2018

Thank you for sharing! Great way to use Google Maps with npm project.

@aaryan79831014

This comment has been minimized.

Copy link

aaryan79831014 commented Oct 9, 2018

Thanks for sharing and very good approach for the Google Maps, was very helpful to use via dynamic loading of maps. Especially, when google maps are costing a lot now.Very much appreciated

@markusmo

This comment has been minimized.

Copy link

markusmo commented Apr 15, 2019

Thanks mate :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.