Coordinates on clickevent

本秂侑毒 提交于 2019-12-22 08:56:12

问题


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


回答1:


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);
});



回答2:


Try to "cast" it as a LeafletMouseEvent:

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


来源:https://stackoverflow.com/questions/48744952/coordinates-on-clickevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!