angulartypescriptleafletngx-leaflet

Coordinates on clickevent


I'm new to @asymmetrik/ngx-leaflet and Angular in general, so this is maybe just a newbie-issue...

I have an Angular.io (v5) project using the @asymmetrik/ngx-leaflet-tutorial-ngcli

Now I would like to get the coordinates of the point I clicked on the map. According to Issue #51 get coordinates on click?, I added this:

map.on('click', () => { console.log(e.latlng); });

to:

onMapReady(map: Map) {
    map.fitBounds(this.route.getBounds(), {
        padding: point(24, 24),
        maxZoom: 12,
        animate: true
    });
    map.on('click', () => { console.log(e.latlng); });
}

that gives me a runtime error: Cannot find name 'e'.

Which kind of makes sense to me. So, I changed the code to:

map.on('click', (e) => { console.log(e.latlng); });

But this gives me an error too: Property 'latlng' does not exist on type 'LeafletEvent'

When I just put e to the console console.log(e) I can see the latlng-Property exists... Why can't I access the coordinates with e.latlng?

My project is using:

"@angular/cli": "1.4.7",
"@asymmetrik/ngx-leaflet": "^2.5.1",
"@types/leaflet": "^1.2.0",
"leaflet": "^1.2.0",


Solution

  • The compiler is inferring that the event type is LeafletEvent, which doesn't have the latlng property. That's why you're getting this error.

    The Leaflet docs indicate that this event is actually of type LeafletMouseEvent, which extends LeafletEvent. So, you can cast the event to gain access to the properties of LeafletMouseEvent (as demonstrated below:

    map.on('click', (<LeafletMouseEvent>e) => {
        console.log(e.latlng);
    });