Skip to content

Commit 1fac491

Browse files
authored
fix(google-maps): instantiate geocoder lazily (#22159)
Currently we instantiate the `Geocoder` when the `MapGeocoder` provider is instantiated which may be too early if the Google Maps API is loaded lazily. These changes switch to creating it only when `geocode` is called. Fixes #22148.
1 parent 4b11445 commit 1fac491

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

src/google-maps/map-geocoder/map-geocoder.spec.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,12 @@ describe('MapGeocoder', () => {
2222
(window.google as any) = undefined;
2323
});
2424

25-
it('initializes the Google Maps Geocoder', () => {
25+
it('does not initialize the Google Maps Geocoder immediately', () => {
26+
expect(geocoderConstructorSpy).not.toHaveBeenCalled();
27+
});
28+
29+
it('initializes the Google Maps Geocoder after `geocode` is called', () => {
30+
geocoder.geocode({}).subscribe();
2631
expect(geocoderConstructorSpy).toHaveBeenCalled();
2732
});
2833

src/google-maps/map-geocoder/map-geocoder.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,21 @@ export interface MapGeocoderResponse {
2323
*/
2424
@Injectable({providedIn: 'root'})
2525
export class MapGeocoder {
26-
private readonly _geocoder: google.maps.Geocoder;
26+
private _geocoder: google.maps.Geocoder|undefined;
2727

28-
constructor(private readonly _ngZone: NgZone) {
29-
this._geocoder = new google.maps.Geocoder();
30-
}
28+
constructor(private readonly _ngZone: NgZone) {}
3129

3230
/**
3331
* See developers.google.com/maps/documentation/javascript/reference/geocoder#Geocoder.geocode
3432
*/
3533
geocode(request: google.maps.GeocoderRequest): Observable<MapGeocoderResponse> {
3634
return new Observable(observer => {
35+
// Initialize the `Geocoder` lazily since the Google Maps API may
36+
// not have been loaded when the provider is instantiated.
37+
if (!this._geocoder) {
38+
this._geocoder = new google.maps.Geocoder();
39+
}
40+
3741
this._geocoder.geocode(request, (results, status) => {
3842
this._ngZone.run(() => {
3943
observer.next({results, status});

0 commit comments

Comments
 (0)