Skip to content

Instantly share code, notes, and snippets.

@JeffreyHyer
Created September 22, 2016 00:48
Show Gist options
  • Save JeffreyHyer/f79f8e6ba3a98831bf2347e5f30358e7 to your computer and use it in GitHub Desktop.
Save JeffreyHyer/f79f8e6ba3a98831bf2347e5f30358e7 to your computer and use it in GitHub Desktop.
/**
* webMercatorToLatLong
*
* Convert supplied Web Mercator coordinates to WGS84-compatible latitude and longitude coordinates.
*
* Sources: http://www.neercartography.com/latitudelongitude-tofrom-web-mercator/
* https://developers.arcgis.com/javascript/3/jsapi/esri.geometry.webmercatorutils-amd.html#xytolnglat
*
* @param double x The X coordinate in Web Mercator format
* @param double y The Y coordinate in Web Mercator format
*
* @return object {x, y, lat, lon} The given X, Y, and their equivalent
* Latitude and Longitude (WGS84)
*/
function webMercatorToLatLong(x, y) {
if ((Math.abs(x) > 20037508.3427892) || (Math.abs(y) > 20037508.3427892)) {
return false;
}
const SEMIMAJOR_AXIS = 6378137.0;
let lat = (((x / SEMIMAJOR_AXIS) * (180.0 / Math.PI)) - (Math.floor((((x / SEMIMAJOR_AXIS) * (180.0 / Math.PI)) + 180.0) / 360.0) * 360.0)),
lon = (((Math.PI / 2) - (2.0 * Math.atan(Math.exp((-1.0 * y) / SEMIMAJOR_AXIS)))) * (180 / Math.PI));
return { x: x, y: y, lat: lat, lon: lon };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment