Home > ArcGIS, JavaScript > JavaScript: How to convert Mercator Sphere coordinates to latitude and longitude

JavaScript: How to convert Mercator Sphere coordinates to latitude and longitude

     In one of my previous posts I told about How to implement Drag’n’Dropping of pushpin using ArcGIS JavaScript API. According to the ArcGIS JavaScript API help, the map’s spatial reference is based on the first layer added to the map and it cannot be overridden (http://resources.esri.com/help/9.3/arcgisserver/apis/javascript/arcgis/help/jshelp_start.htm#jshelp/inside_guidelines.htm). I use World Street Map as the first layer, that means that the current spatial reference corresponds to such coordinate system as Web Mercator Auxiliary Sphere (WKID 102100) with decimal degrees as Units of measure (http://www.arcgis.com/home/item.html?id=3b93337983e9436f8db950e38a8629af and http://help.arcgis.com/en/arcgisonline/content/index.html#//011q00000002000000.htm). Therefore, the coordinates of pushpin’s current position will be in the spherical Mercator projection.

When intending to integrate with other services or systems, it’s reasonable to convert Mercator Sphere coordinates to latitude and longitude that are the most popular for specifying geographical locations. Below is the JavaScript function, which performs the conversion:

function MercatorToLatLon(mercX, mercY) {

    var rMajor = 6378137; //Equatorial Radius, WGS84
    var shift  = Math.PI * rMajor;
    var lon    = mercX / shift * 180.0;
    var lat    = mercY / shift * 180.0;
    lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2.0);

    return { 'Lon': lon, 'Lat': lat };            
}

How to use the function:

var currentPushpinPoint = pushpin.GetCurrentLocation();
var LatLon = MercatorToLatLon(currentPushpinPoint.x, currentPushpinPoint.y);
alert('Result: Lat = ' + LatLon.Lat + ', Lon = ' + LatLon.Lon);

The inverse JavaScript function is here

Related posts:
 
  1. No comments yet.
  1. No trackbacks yet.