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.
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.
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.
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
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
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