I'm trying to use Leaflet to get the map coordinates of somewhere a user has right clicked. I've been going through the Leaflet API and so far I've figured out that I need to listen to the contextmenu
event and use mouseEventToLatLng
method to get the coordinates when clicked. However, when I go through and debug my code I'm not seeing an accessible latLng variable anywhere. Did I miss understand something in the API?
function setMarkers() {
document.getElementById("transitmap").addEventListener("contextmenu", function( event ) {
// Prevent the browser's context menu from appearing
event.preventDefault();
var coords = L.mouseEventToLatLng( event );
});
};
Layergroup allows to control all markers at once. Ok, removing the layer seems to be the solution, but the more straightforward answer to the question, how to remove a marker is the one given by @HarijsKrūtainis : marker. remove() , it worked perfectly to me.
Once you enter to the js file leaflet.permalink.js, you can change your default coordinates at the very top (lines 3-6): getMapLocation: function (zoom, center) { 'use strict'; zoom = (zoom || zoom === 0) ? zoom : 16; center = (center) ? center : [52.26869, 0.11034];
To add map to our web page, simple web technologies like HTML, CSS and JavaScript are required. To use Leaflet in your code, you need to add the Leaflet CSS and Leaflet JS.
This reference reflects Leaflet 0.7.x. Check this list if you are using a different version of Leaflet. The central class of the API — it is used to create a map on a page and manipulate it. L.map( <HTMLElement|String> id, < Map options > options?
To use Leaflet in your code, you need to add the Leaflet CSS and Leaflet JS. You can either download them or use them by including their CDNs (see above code sample). 3. Create a Map container and create a Map object
What you want to get is mousemove event. This is basically how you do it,
var lat, lng;
map.addEventListener('mousemove', function(ev) {
lat = ev.latlng.lat;
lng = ev.latlng.lng;
});
document.getElementById("transitmap").addEventListener("contextmenu", function (event) {
// Prevent the browser's context menu from appearing
event.preventDefault();
// Add marker
// L.marker([lat, lng], ....).addTo(map);
alert(lat + ' - ' + lng);
return false; // To disable default popup.
});
The coordinates of the right click event should be directly available as latlng
property of the event
argument of the "contextmenu"
listener.
map.on("contextmenu", function (event) {
console.log("Coordinates: " + event.latlng.toString());
L.marker(event.latlng).addTo(map);
});
Demo: http://plnkr.co/edit/9vm81YsQxnkAFs35N8Jo?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With