I am trying to find coordinates on map when user click on it, but not when he double click to zoom in. The goal being to create a marker at this point and remember it for later.
As I am using svelte, I believe i should use a premade svelte module, I found svelte-leaflet that should be able to do the job.
I downloaded their sample project and start editing from there.
So I just want to get an event so far, so I create a function in App.svelte
const on_map_click = (e) => {
console.log('click')
console.log(e)
}
And add the event handler:
<div style="width: 100%; height: 100%;">
<LeafletMap bind:this={leafletMap} options={mapOptions} on:click={on_map_click}>
<TileLayer url={tileUrl} options={tileLayerOptions} />
</LeafletMap>
</div>
Unfortunately I don't get any event.
So I tried another aproach (not svelte-oriented) :
onMount(() => {
leafletMap.getMap().fitBounds([[60.9, -4.8], [45.5, 10.2]]);
leafletMap.getMap().on('click', on_map_click) // <---
});
This approach works, but if I double click it still trigger the event. So I believe there is another way, more adapted to the use case.
Please let me know what I am doing wrong ?
CodePudding user response:
There's a section in the docs https://ngyewch.github.io/svelte-leaflet/event-handling. According to that you have to set events
on the component for which you want to listen, so
<LeafletMap ... events="{['click']}" on:click={on_map_click}>
The event object will be a CustomEvent
with the original event in the detail
function on_map_click(event) {
console.log(event.detail.originalEvent)
}
but if I double click it still trigger the event
I think that's normal behaviour that the click event is also triggered when double clicked. Should a visible marker be set? Maybe this could be done by adding a button which must be pressed while clicking? Or use the contextmenu
right click?
As I am using svelte, I believe i should use a premade svelte module
There's no obligation to do so. It might be handy to use a special svelte library, but it is also possible to use the js library directly
This is how you could do it directly with leaflet
installed REPL
<script>
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
function initMap(node) {
const map = L.map(node).setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
L.marker([51.5, -0.09]).addTo(map)
.bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
.openPopup();
map.on('click', (event) => console.log(event))
}
</script>
<div use:initMap></div>
<style>
div {
height: 600px;
}
</style>