@@ -44,6 +44,8 @@ const CIRCLE_CENTER: google.maps.LatLngLiteral = {
44
44
} ;
45
45
const CIRCLE_RADIUS = 500000 ;
46
46
47
+ let apiLoadingPromise : Promise < unknown > | null = null ;
48
+
47
49
/** Demo Component for @angular/google-maps/map */
48
50
@Component ( {
49
51
selector : 'google-map-demo' ,
@@ -96,6 +98,7 @@ export class GoogleMapDemo {
96
98
} ;
97
99
98
100
isGroundOverlayDisplayed = false ;
101
+ hasLoaded : boolean ;
99
102
groundOverlayImages = [
100
103
{
101
104
title : 'Red logo' ,
@@ -116,19 +119,16 @@ export class GoogleMapDemo {
116
119
isBicyclingLayerDisplayed = false ;
117
120
118
121
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 [ ] ;
125
123
126
124
markerClustererImagePath =
127
125
'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' ;
128
126
129
127
directionsResult ?: google . maps . DirectionsResult ;
130
128
131
- constructor ( private readonly _mapDirectionsService : MapDirectionsService ) { }
129
+ constructor ( private readonly _mapDirectionsService : MapDirectionsService ) {
130
+ this . _loadApi ( ) ;
131
+ }
132
132
133
133
authFailure ( ) {
134
134
console . log ( 'Auth failure event emitted' ) ;
@@ -257,4 +257,41 @@ export class GoogleMapDemo {
257
257
258
258
return result ;
259
259
}
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
+ }
260
297
}
0 commit comments