Helios
Helios

Reputation: 207

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.

Upvotes: 16

Views: 23054

Answers (2)

Nikhil VJ
Nikhil VJ

Reputation: 6102

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

Upvotes: 8

iH8
iH8

Reputation: 28628

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

Upvotes: 34

Related Questions