Search code examples
javascriptleafletgeocoding

Leaflet geosearch: return lat/lng from address found event


I use great Leaflet plugins for geocoding such as https://github.com/smeijer/L.GeoSearch

While these are perfect for showing address locations on the map when found, I would also like to be able to use the coordinates from the result to other functions that I have included in my map (e.g. I've written one which finds nearby points from a data layer based on the locationfound event fired from Leaflet's inbuilt locate function).

I know the answer (probably) lies in accessing the events from the geosearch plugin, but that's a bit beyond my skills at the moment. Any help would be very welcome.


Solution

  • The L.GeoSearch plugin fires it's events on your map instance. You'll need to listen for the geosearch_foundlocations event. The object that's returned when the event is fired holds a Locations property which contains an array with L.GeoSearch.Result objects. Each object has four properties; Label, X, Y and bounds

    Example in code:

    map.on('geosearch/showlocation', function (e) {
        e.Locations.forEach(function (Location) {
            // Location.Label = full address
            // Location.X = longitude
            // Location.Y = latitude
            // Location.bounds = boundaries
        });
    });