Flyer - dragged marker and coordinates are displayed in field form

I need to make a draggable marker and its coordinates should be displayed in the fields. It will be part of the 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's an example at the Google Maps API. I need the same in the Leaflet.

+3


source to share


2 answers


You have to use the L.Marker drag event so you know the drag is over, then get the marker coordinates using L.Marker's getLatLng method. When you select them, 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

+10


source


It's time to look for a similar solution. Laid out a notable answer and took it a little further:

  • Both drag and drop; and the centers of the maps on the marker.
  • Works in reverse order (user-entered values ​​in form fields can move the marker).
  • Retains the previous location marked by the user.

operational 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

+1


source







All Articles