File

packages/core/src/lib/services/geocoder-service.ts

Index

Properties
Methods

Constructor

constructor(loader: MapsAPILoader)
Parameters :
Name Type Optional
loader MapsAPILoader No

Methods

Private _createGeocoder
_createGeocoder()
Returns : any
Private _getGoogleResults
_getGoogleResults(geocoder: google.maps.Geocoder, request: google.maps.GeocoderRequest)
Parameters :
Name Type Optional
geocoder google.maps.Geocoder No
request google.maps.GeocoderRequest No
Returns : Observable<google.maps.GeocoderResult[]>
geocode
geocode(request: google.maps.GeocoderRequest)
Parameters :
Name Type Optional
request google.maps.GeocoderRequest No
Returns : Observable<google.maps.GeocoderResult[]>

Properties

Protected Readonly geocoder$
Type : Observable<google.maps.Geocoder>
import { Injectable } from '@angular/core';
import { bindCallback, ConnectableObservable, Observable, of, ReplaySubject, throwError } from 'rxjs';
import { map, multicast, switchMap } from 'rxjs/operators';
import { MapsAPILoader } from './maps-api-loader/maps-api-loader';

@Injectable({ providedIn: 'root' })
export class AgmGeocoder {
  protected readonly geocoder$: Observable<google.maps.Geocoder>;

  constructor(loader: MapsAPILoader) {
    const connectableGeocoder$ = new Observable(subscriber => {
      loader.load().then(() => subscriber.next());
    })
      .pipe(
        map(() => this._createGeocoder()),
        multicast(new ReplaySubject(1)),
      ) as ConnectableObservable<google.maps.Geocoder>;

    connectableGeocoder$.connect(); // ignore the subscription
    // since we will remain subscribed till application exits

    this.geocoder$ = connectableGeocoder$;
  }

  geocode(request: google.maps.GeocoderRequest): Observable<google.maps.GeocoderResult[]> {
    return this.geocoder$.pipe(
      switchMap((geocoder) => this._getGoogleResults(geocoder, request))
    );
  }

  private _getGoogleResults(geocoder: google.maps.Geocoder, request: google.maps.GeocoderRequest):
       Observable<google.maps.GeocoderResult[]> {
    const geocodeObservable = bindCallback(geocoder.geocode);
    return geocodeObservable(request).pipe(
      switchMap(([results, status]) => {
        if (status === google.maps.GeocoderStatus.OK) {
          return of(results);
        }

        return throwError(status);
      })
    );
  }

  private _createGeocoder() {
    return new google.maps.Geocoder();
  }
}

result-matching ""

    No results matching ""