23

I wonder, how can I get map click event's coordinates as lat,lon?

Here is my code:

map.on('click', function(evt) {
    var element = popup.getElement();
    var coordinate = evt.coordinate;

    var latLon = ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326');

    $(element).popover('destroy');
    popup.setPosition(coordinate);

Normally, coordinate value gives me an array etc: [48654.02545, 3265468.45455]

But I need lat lon etc:([39,54876,32,547821])

Abstract: I need to convert epsg:3857 coordinate to epsg:4326 coordinate (lat/lon)

Any idea?

Icarus
  • 1,627
  • 7
  • 18
  • 32
gokhangokce
  • 461
  • 3
  • 8
  • 17

1 Answers1

48

If your map view projection is Web Mercator (EPSG:3857), which is the default, then the following should work:

map.on('click', function(evt) {
  var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
  var lon = lonlat[0];
  var lat = lonlat[1];
  // …
});
erilem
  • 2,634
  • 21
  • 21
  • i solved problem but your solution is more professional. I think problem caused by android LogCat, because i coudlnt see values of array. – gokhangokce Nov 17 '14 at 19:11
  • 1
    This solution works just for evt.coordinate. It's not working for an icon object. Etc: var geometry = feature.getGeometry(); var coord = geometry.getCoordinates(); var lonlat = ol.proj.transform(coord, 'EPSG:3857', 'EPSG:4326'); var lon = lonlat[0]; var lat = lonlat[1]; returns Lon-Lat: 0.000026949458523585642 - 0.000053898917059314044 – gokhangokce Nov 17 '14 at 19:23
  • 1
    You need to provide a complete example. – erilem Nov 17 '14 at 19:45
  • Just so you know, there is also `ol.proj.toLonLat` function, that does this for us: [link]https://openlayers.org/en/latest/apidoc/module-ol_proj.html#.toLonLat But keep in mind, this method works with default projection codes, works in OpenLayers 6.6.1 – Leroy Meijer Jul 29 '21 at 08:53