Archive

Posts Tagged ‘Mercator coordinates’

JavaScript: How to convert latitude and longitude to Mercator coordinates

August 1st, 2011 No comments

     Continuing the previous post about converting Mercator Sphere coordinates to latitude and longitude, I’d like to show an inverse JavaScript function for converting latitude and longitude to Mercator coordinates:

function LatLonToMercator(lat, lon) {

    var rMajor = 6378137; //Equatorial Radius, WGS84
    var shift  = Math.PI * rMajor;
    var x      = lon * shift / 180;
    var y      = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
    y = y * shift / 180;
    
    return {'X': x, 'Y': y};
}

The use of it is very simple:

var XY = LatLonToMercator(38.878586, -76.989626);
alert('Mercator X:' + XY.X + ', Mercator Y:' + XY.Y);
Related posts:

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

July 29th, 2011 No comments

     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: