Guest User

Untitled

a guest
Jun 23rd, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. /**
  2. * Use this class to ensure Google Maps API javascript is loaded before running any google map specific code.
  3. */
  4. export class GoogleMapsApi {
  5. /**
  6. * Constructor set up config.
  7. */
  8. constructor() {
  9. // api key for google maps
  10. this.apiKey = 'APIKEY';
  11.  
  12. // set a globally scoped callback if it doesn't already exist
  13. if (!window._GoogleMapsApi) {
  14. this.callbackName = '_GoogleMapsApi.mapLoaded';
  15. window._GoogleMapsApi = this;
  16. window._GoogleMapsApi.mapLoaded = this.mapLoaded.bind(this);
  17. }
  18. }
  19.  
  20. /**
  21. * Load the Google Maps API javascript
  22. */
  23. load() {
  24. if (!this.promise) {
  25. this.promise = new Promise(resolve => {
  26. this.resolve = resolve;
  27. if (typeof window.google === 'undefined') {
  28. const script = document.createElement('script');
  29. script.src = `//maps.googleapis.com/maps/api/js?key=${this.apiKey}&callback=${this.callbackName}`;
  30. script.async = true;
  31. document.body.append(script);
  32. } else {
  33. this.resolve();
  34. }
  35. });
  36. }
  37.  
  38. return this.promise;
  39. }
  40.  
  41. /**
  42. * Globally scoped callback for the map loaded
  43. */
  44. mapLoaded() {
  45. if (this.resolve) {
  46. this.resolve();
  47. }
  48. }
  49. }
Add Comment
Please, Sign In to add comment