Search code examples
javascriptopenlayersopenmap

Spherical Mercator Lat/Lon from OpenLayers, want EPSG:4326 format


I am trying to get the EPSG:4236 format of longitude and latitude from OpenLayer, however I spent several hours trying to figure this out and I really don't get what I am doing wrong. I keep getting the spherical mercator format.

For setup I have the following:

var map = new OpenLayers.Map("mapdiv");
map.addLayer(new OpenLayers.Layer.OSM());
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);

This is my center of the map:

  var lonLatCenter =  new OpenLayers.LonLat( -73.0,  40.5 )
      .transform(
        new OpenLayers.Projection("EPSG:4326"), 
        map.getProjectionObject()
  );

  var zoom=14;

For click event I have the following code:

map.events.register("click", map, function(e) {
            var position = map.getLonLatFromPixel(e.xy);
            alert(JSON.stringify(position));
});

I get the following result when clicking on JFK airport in New York City:

{"lon":-8215245.2836805,"lat":4960351.5608374}

I have been reading information here but it seems to only show how to transform from EPSG:4326 to spherical mercator. Help would be appreciated and the link below is to the documentation :

http://docs.openlayers.org/library/spherical_mercator.html


Solution

  • Click event on map object return coordinates using map projection (shperical mercator). You need to transform them to lat lon, like this

    map.events.register("click", map, function(e) {
                var position = map.getLonLatFromPixel(e.xy);
                position.transform(map.getProjectionObject(), new OpenLayers.Projection('EPSG:4326'));
                alert(JSON.stringify(position));
    });