Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet - draggable marker and coordinates display in a field form

I have to do a draggable marker and its coordinates should be displayed in fields. It will be a part of a contact form in PHP. I created a draggable marker, help me what to do now.

var marker = L.marker(new L.LatLng(53.471, 18.744), {
draggable: true
}).addTo(map);

http://jsfiddle.net/xTh5U/

Here is example in Google Maps API, I need the same in Leaflet.

like image 654
Helios Avatar asked Dec 03 '14 12:12

Helios


People also ask

How do you make a marker draggable in leaflet?

You should use the dragend event of L. Marker, so you known dragging has ended, then get the coordinates of the marker by using the getLatLng method of L. Marker. When you've fetched those you can assign them to the values of your text inputs.

How do you show markers in leaflet?

Adding a Simple Marker Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional). Step 2 − Create a Layer object by passing the URL of the desired tile. Step 3 − Add the layer object to the map using the addLayer() method of the Map class.


2 Answers

You should use the dragend event of L.Marker, so you known dragging has ended, then get the coordinates of the marker by using the getLatLng method of L.Marker. When you've fetched those you can assign them to the values of your text inputs.

marker.on('dragend', function (e) {
    document.getElementById('latitude').value = marker.getLatLng().lat;
    document.getElementById('longitude').value = marker.getLatLng().lng;
});

Working example on Plunker: http://plnkr.co/edit/iyMhaoAyllr2uNSOHhS9?p=preview

like image 50
iH8 Avatar answered Sep 19 '22 18:09

iH8


Came across this while looking for a similar solution. Forked the marked answer and took it a little further:

  • Both drag and click; and map centers on the marker.
  • Works in reverse as well (user-entered values in form fields can move the marker).
  • Remembers the previous location marked by the user.

operative code:

marker.on('dragend', function (e) {
    updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng);
    });
map.on('click', function (e) {
marker.setLatLng(e.latlng);
updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng);
});

function updateLatLng(lat,lng,reverse) {
if(reverse) {
marker.setLatLng([lat,lng]);
map.panTo([lat,lng]);
} else {
document.getElementById('latitude').value = marker.getLatLng().lat;
document.getElementById('longitude').value = marker.getLatLng().lng;
map.panTo([lat,lng]);
}
}

See working example: http://plnkr.co/edit/PTFlun?p=preview

like image 20
Nikhil VJ Avatar answered Sep 20 '22 18:09

Nikhil VJ