0

I have a leaflet map where i am using Control Geocoder to get some locations on search,then i add the coordinates on 2 input fields,also i added a popup for the search result,the problem is that when the marker is moved the popup doesn't update with the new place,how can this be done?

Mmap = L.map('Modalmap').setView([8.7144, 125.7481],8);
L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright"></a>',
    subdomains: ['a','b','c']
}).addTo(Mmap);
var geocoder = L.Control.geocoder({
    defaultMarkGeocode: false,
    draggable:true
})
.on('markgeocode', function(e) {
    var box = e.geocode.center;
    var name=e.geocode.name;
    document.getElementById("Latitude").value = box.lat;
    document.getElementById("Longitude").value = box.lng;
    MarkLayer=L.marker([box.lat,box.lng],{draggable:true}).addTo(Mmap). 
    on('dragend', onDragEnd). 
    bindPopup(e.geocode.name). 
    openPopup(); 
    displayLatLng(box); 

    group = new L.featureGroup([MarkLayer]);

    Mmap.fitBounds(group.getBounds());
}).addTo(Mmap); 

function onDragEnd(event) 
{
    var latlng = event.target.getLatLng();

    displayLatLng(latlng);
}

function displayLatLng(latlng) {
    document.getElementById("Latitude").value = latlng.lat;
    document.getElementById("Longitude").value = latlng.lng;
}
  • I tried your code. It is quite logical, if you drag the marker, it won't necessary fall on a new place with a name. Or do you want to put lat, long data into your popup? – juminet Feb 24 '17 at 15:50
  • @juminet...when geocoding done at the first time,it shows street name or building number,when i drag it,it is supposed to give me the new street name for example but it gives me the same result of the first point. – New at Leaflet Feb 25 '17 at 11:27
  • crosspost: stackoverflow.com/questions/42418216/… – scai Feb 26 '17 at 17:47
1

You can use the .reverse function to do a reverse geocoding, that is, retrieving a name for a latitude-longitude coordinate.

To use that you have to create a geocoder instance. I chose the default here, which is Nominatim. It might help to rename your current geocoder control to geocoderControl or something else.

var geocoderNominatim = new L.Control.Geocoder.Nominatim();
var geocoderControl = L.Control.geocoder({
    geocoder: geocoderNominatim
}) // etc.

And then perform this reverse lookup in your onDragEnd and apply the new popup contents:

function onDragEnd(event) {
    var latlng = event.target.getLatLng();

    geocoderNominatim.reverse(latlng, Mmap.options.crs.scale(Mmap.getZoom()), function(reverseGeocoded){
      event.target.setPopupContent(reverseGeocoded[0].name).openPopup();
    }, this)

    displayLatLng(latlng);
}

Plunker demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.