Created
March 3, 2020 13:11
-
-
Save crazyyy/5ffb832c7fdc8ce8872aae47816f7612 to your computer and use it in GitHub Desktop.
#js || A simple class for loading the Google Maps Javascript API in browser async using ES6 and Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment