25

I am using OSM with Leaflet API. Now I want to get the lat and long of a clicked location. I meant something similar to this. ex: http://openlayers.org/dev/examples/click.html

map.events.register("click", map, function(e) {
            var position = map.getLonLatFromPixel(e.xy);
                alert("Lat, Lon : "+position.lon.toFixed(3),position.lat.toFixed(3));

        });

This code in OpenLayers helps to get the lat ,long values... looking for something similar using Leaflet...

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
DomincJune
  • 399
  • 2
  • 6
  • 10

2 Answers2

70

You can easily get click events using the map's 'on' event subscription method:

map.on('click', function(e) {
    alert("Lat, Lon : " + e.latlng.lat + ", " + e.latlng.lng)
});
Marc Pfister
  • 4,097
  • 17
  • 11
-1

Try Reverse geocoding with esri-leaflet and openstreetmap tile.

var map = L.map('map').setView([0,0], 2);
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

var geocodeService = L.esri.Geocoding.geocodeService();

map.on('click', function (e) { geocodeService.reverse().latlng(e.latlng).run(function (error, result) { if (error) { return; } alert(result.latlng) }); });

Source Code: https://github.com/CTRLTAB-WORKS/reverse-geocoding

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
CTRLTAB
  • 1
  • 2
  • A bit contradictory to provide a proprietary library (esri) with much more complicated solution than the native open source Leaflet functions provided by the other answer.... almost 8 years after. – Cyrille Feb 27 '23 at 07:20