In my Angular project, I needed to include a map component. I integrated the Google Maps API service in a file called map.service.ts
. My goal was to draw circles (polygons) on the map and send values to the backend. To achieve this, I added event listeners such as circlecomplete and radius_changed in my services.
public initMap(mapElement: ElementRef, search: ElementRef, options: MapOptions) {
return this.init().pipe(
switchMap(() =>
this.createGoogleMap(mapElement.nativeElement, search.nativeElement, options)
),
exhaustMap(() =>
forkJoin(
this.subscribeToDrawingEvents('circlecomplete').pipe(
map(d => console.log(d))
),
this.subscribeToCenterChangeEvents('center_changed').pipe(
map(d => console.log(d))
),
this.subscribeToRadiusChangeEvents('radius_changed').pipe(
map(d => console.log(d))
),
this.subscribeToSearchboxEvents('places_changed')
)
)
);
}
In the initMap method, I created the JavaScript code and appended it to the component. Then, createGoogleMap function is used to generate the map, followed by adding event listeners. This service is then subscribed to from a map.component.ts
.
ngOnInit() {
this.option = {
center: this.center ? this.center : { lat: 0, lng: 0 },
zoom: this.zoom ? this.zoom : 4,
markers: this.markers ? this.markers : []
};
this.subscribe_event$ = this.service.initMap(this.googleMap, this.searchInput, this.option);
this.subscribe_event$.subscribe();
} // ngOnInit()
I successfully received values during the center change event:
this.subscribeToCenterChangeEvents('center_changed').pipe(
map(d => console.log(d))
),
However, I faced issues when trying to get values into the subscribing component. Here is how I set up the observer:
private subscribeToCenterChangeEvents<E>(eventName: string): Observable<any> {
console.log('Circle Center Change listener added');
return Observable.create((observer: Observer<any>) => {
google.maps.event.addListener(this.drawingManager, eventName, drwnCircle => {
const circle_radius: Number = drwnCircle.getRadius();
const circle_center: LatLng = drwnCircle.getCenter();
console.log(circle_radius);
observer.next({ drawn_circle: circle_radius });
});
});
} // subscribeToCenterChangeEvents