agm-marker's markerClick() is returning null
Asked Answered
J

2

5

From the angular google maps API, we have a markerClick() function with the following definition,

 @Output() markerClick: EventEmitter<void> = new EventEmitter<void>();

But when I am using in my application, I am getting NULL.

I have the following code for the application,

In my HTML file,

<agm-map [latitude]="latitude" [longitude]="longitude" [zoom]="zoom">
        <agm-marker *ngFor="let marker of coordinates;" 
        [iconUrl]="icon" 
        [latitude]="marker.latitude" 
        [longitude]="marker.longitude"
        [markerClickable]="true"
        (markerClick)="markerClicked($event)">
    </agm-marker>
    </agm-map>

And in .TS file,

 markerClicked($event: MouseEvent) {
    console.log('clicked'); ----------------(1)
    console.log($event);--------------------(2)
  }

For statement (2), I am getting NULL as the console output. I am expecting it to be marker Object. Is my understanding wrong? How to get the lat and lng from the markerClick() function.

Note, I am already using mapClick() function for the agm-map tag, but when I am using that function, It is not responding to clicks on already drawn markers on the Map.

Jess answered 27/3, 2018 at 6:50 Comment(0)
D
9

If you look into the FILE deeper it always emits null :

this.markerClick.emit(null); // line no : 192

What you can do is change this :

(markerClick)="markerClicked($event)"

To :

(markerClick)="markerClicked(marker)" // this way you will get the marker object

WORKING DEMO (Click on any available marker)

Dieselelectric answered 27/3, 2018 at 7:10 Comment(4)
@Jess , please check the WORKING DEMO , stackblitz.com/edit/angular-google-maps-demo2Dieselelectric
Thank You, got the required info, i did not knew, we can pass properties in html.Jess
@Jess , Glad to know that , Happy Coding BTW :) .Dieselelectric
Is there any way to get the marker object without clicking the marker?Salience
T
1

In the app.component.html

<agm-map>
<agm-marker  *ngFor="let place of markers" [latitude]=place.lat [longitude]=place.lng  title={{place.title}}  (markerClick)="clickedMarker(place.lat, place.lng)" >
<agm-info-window><strong>{{place.label}}</strong></agm-info-window>
</agm-marker>
</agm-map>

In the app.components.ts

markers: any[] = [];

selectedLat: Number = 0;
selectedLng: Number = 0;

clickedMarker(lat: number, lng: number) {
this.selectedLat = lat;
this.selectedLng = lng;
}

Here when the marker is clicked it calls clickedMarker(lat: number, lng: number) function. In there selectedLat and selectedLng variables are updated from the sending parameters of the (markerClick)="clickedMarker(place.lat, place.lng)

Doesn't use in this way (markerClick)="markerClicked($event)"

Trapshooting answered 27/9, 2018 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.