Skip to content

Commit

Permalink
fix(google-maps): instantiate geocoder lazily (#22159)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
crisbeto committed Mar 19, 2021
1 parent 4b11445 commit 1fac491
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
7 changes: 6 additions & 1 deletion src/google-maps/map-geocoder/map-geocoder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ describe('MapGeocoder', () => {
(window.google as any) = undefined;
});

it('initializes the Google Maps Geocoder', () => {
it('does not initialize the Google Maps Geocoder immediately', () => {
expect(geocoderConstructorSpy).not.toHaveBeenCalled();
});

it('initializes the Google Maps Geocoder after `geocode` is called', () => {
geocoder.geocode({}).subscribe();
expect(geocoderConstructorSpy).toHaveBeenCalled();
});

Expand Down
12 changes: 8 additions & 4 deletions src/google-maps/map-geocoder/map-geocoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,21 @@ export interface MapGeocoderResponse {
*/
@Injectable({providedIn: 'root'})
export class MapGeocoder {
private readonly _geocoder: google.maps.Geocoder;
private _geocoder: google.maps.Geocoder|undefined;

constructor(private readonly _ngZone: NgZone) {
this._geocoder = new google.maps.Geocoder();
}
constructor(private readonly _ngZone: NgZone) {}

/**
* See developers.google.com/maps/documentation/javascript/reference/geocoder#Geocoder.geocode
*/
geocode(request: google.maps.GeocoderRequest): Observable<MapGeocoderResponse> {
return new Observable(observer => {
// Initialize the `Geocoder` lazily since the Google Maps API may
// not have been loaded when the provider is instantiated.
if (!this._geocoder) {
this._geocoder = new google.maps.Geocoder();
}

this._geocoder.geocode(request, (results, status) => {
this._ngZone.run(() => {
observer.next({results, status});
Expand Down

0 comments on commit 1fac491

Please sign in to comment.