Reputation: 207
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);
Here is example in Google Maps API, I need the same in Leaflet.
Upvotes: 16
Views: 23054
Reputation: 6102
Came across this while looking for a similar solution. Forked the marked answer and took it a little further:
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
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