Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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",

like image 640
CaptainInler Avatar asked Feb 12 '18 11:02

CaptainInler


Video Answer


2 Answers

Try to "cast" it as a LeafletMouseEvent:

map.on('click', <LeafletMouseEvent>(e) => { console.log(e.latlng) });
like image 161
ghybs Avatar answered Sep 22 '22 08:09

ghybs


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);
});
like image 21
Pterrat Avatar answered Sep 20 '22 08:09

Pterrat