Skip to content

Instantly share code, notes, and snippets.

@mavame
Last active December 6, 2023 21:53
Show Gist options
  • Star 39 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mavame/b833b50085dc856acbccbb34ab1dbe92 to your computer and use it in GitHub Desktop.
Save mavame/b833b50085dc856acbccbb34ab1dbe92 to your computer and use it in GitHub Desktop.
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
Copy link
Author

mavame commented Sep 12, 2017

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

@JonSilver
Copy link

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
Copy link

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

@aaryan79831014
Copy link

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
Copy link

Thanks mate :-)

@KarinePistili
Copy link

Thanks a lot, it really helped in my case. Awesome approach!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment