diff --git a/src/google-maps/map-directions-renderer/map-directions-service.spec.ts b/src/google-maps/map-directions-renderer/map-directions-service.spec.ts index 6927c7e1e55d..68099a130cb0 100644 --- a/src/google-maps/map-directions-renderer/map-directions-service.spec.ts +++ b/src/google-maps/map-directions-renderer/map-directions-service.spec.ts @@ -26,7 +26,12 @@ describe('MapDirectionsService', () => { (window.google as any) = undefined; }); - it('initializes the Google Maps Directions Service', () => { + it('does not initialize the Google Maps Directions Service immediately', () => { + expect(directionsServiceConstructorSpy).not.toHaveBeenCalled(); + }); + + it('initializes the Google Maps Directions Service when `route` is called', () => { + mapDirectionsService.route({}).subscribe(); expect(directionsServiceConstructorSpy).toHaveBeenCalled(); }); diff --git a/src/google-maps/map-directions-renderer/map-directions-service.ts b/src/google-maps/map-directions-renderer/map-directions-service.ts index ec9849aa049b..7fd588a4657b 100644 --- a/src/google-maps/map-directions-renderer/map-directions-service.ts +++ b/src/google-maps/map-directions-renderer/map-directions-service.ts @@ -25,11 +25,9 @@ export interface MapDirectionsResponse { */ @Injectable({providedIn: 'root'}) export class MapDirectionsService { - private readonly _directionsService: google.maps.DirectionsService; + private _directionsService: google.maps.DirectionsService|undefined; - constructor(private readonly _ngZone: NgZone) { - this._directionsService = new google.maps.DirectionsService(); - } + constructor(private readonly _ngZone: NgZone) {} /** * See @@ -38,6 +36,12 @@ export class MapDirectionsService { */ route(request: google.maps.DirectionsRequest): Observable { return new Observable(observer => { + // Initialize the `DirectionsService` lazily since the Google Maps API may + // not have been loaded when the provider is instantiated. + if (!this._directionsService) { + this._directionsService = new google.maps.DirectionsService(); + } + const callback = ( result: google.maps.DirectionsResult|undefined,