@@ -44,6 +44,8 @@ const CIRCLE_CENTER: google.maps.LatLngLiteral = {
4444} ;
4545const CIRCLE_RADIUS = 500000 ;
4646
47+ let apiLoadingPromise : Promise < unknown > | null = null ;
48+
4749/** Demo Component for @angular/google-maps/map */
4850@Component ( {
4951 selector : 'google-map-demo' ,
@@ -96,6 +98,7 @@ export class GoogleMapDemo {
9698 } ;
9799
98100 isGroundOverlayDisplayed = false ;
101+ hasLoaded : boolean ;
99102 groundOverlayImages = [
100103 {
101104 title : 'Red logo' ,
@@ -116,19 +119,16 @@ export class GoogleMapDemo {
116119 isBicyclingLayerDisplayed = false ;
117120
118121 mapTypeId : google . maps . MapTypeId ;
119- mapTypeIds = [
120- google . maps . MapTypeId . HYBRID ,
121- google . maps . MapTypeId . ROADMAP ,
122- google . maps . MapTypeId . SATELLITE ,
123- google . maps . MapTypeId . TERRAIN ,
124- ] ;
122+ mapTypeIds = [ 'hybrid' , 'roadmap' , 'sattelite' , 'terrain' ] as google . maps . MapTypeId [ ] ;
125123
126124 markerClustererImagePath =
127125 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' ;
128126
129127 directionsResult ?: google . maps . DirectionsResult ;
130128
131- constructor ( private readonly _mapDirectionsService : MapDirectionsService ) { }
129+ constructor ( private readonly _mapDirectionsService : MapDirectionsService ) {
130+ this . _loadApi ( ) ;
131+ }
132132
133133 authFailure ( ) {
134134 console . log ( 'Auth failure event emitted' ) ;
@@ -257,4 +257,41 @@ export class GoogleMapDemo {
257257
258258 return result ;
259259 }
260+
261+ private _loadApi ( ) {
262+ this . hasLoaded = ! ! window . google ?. maps ;
263+
264+ if ( this . hasLoaded ) {
265+ return ;
266+ }
267+
268+ if ( ! apiLoadingPromise ) {
269+ // Key can be set through the `GOOGLE_MAPS_KEY` environment variable.
270+ const apiKey : string | undefined = ( window as any ) . GOOGLE_MAPS_KEY ;
271+
272+ apiLoadingPromise = Promise . all ( [
273+ this . _loadScript (
274+ `https://maps.googleapis.com/maps/api/js?libraries=visualization${
275+ apiKey ? `&key=${ apiKey } ` : ''
276+ } `,
277+ ) ,
278+ this . _loadScript ( 'https://unpkg.com/@googlemaps/markerclustererplus/dist/index.min.js' ) ,
279+ ] ) ;
280+ }
281+
282+ apiLoadingPromise . then (
283+ ( ) => ( this . hasLoaded = true ) ,
284+ error => console . error ( 'Failed to load Google Maps API' , error ) ,
285+ ) ;
286+ }
287+
288+ private _loadScript ( url : string ) : Promise < unknown > {
289+ return new Promise ( ( resolve , reject ) => {
290+ const script = document . createElement ( 'script' ) ;
291+ script . src = url ;
292+ script . addEventListener ( 'load' , resolve ) ;
293+ script . addEventListener ( 'error' , reject ) ;
294+ document . body . appendChild ( script ) ;
295+ } ) ;
296+ }
260297}
0 commit comments