Skip to content

Instantly share code, notes, and snippets.

@JeffJacobson
Created October 23, 2012 18:12
Show Gist options
  • Save JeffJacobson/3940440 to your computer and use it in GitHub Desktop.
Save JeffJacobson/3940440 to your computer and use it in GitHub Desktop.
Functions to convert between web mercator and geographic coordinates.
// from http://www.gal-systems.com/2011/07/convert-coordinates-between-web.html
private void ToGeographic(ref double mercatorX_lon, ref double mercatorY_lat)
{
if (Math.Abs(mercatorX_lon) < 180 && Math.Abs(mercatorY_lat) < 90)
return;
if ((Math.Abs(mercatorX_lon) > 20037508.3427892) || (Math.Abs(mercatorY_lat) > 20037508.3427892))
return;
double x = mercatorX_lon;
double y = mercatorY_lat;
double num3 = x / 6378137.0;
double num4 = num3 * 57.295779513082323;
double num5 = Math.Floor((double)((num4 + 180.0) / 360.0));
double num6 = num4 - (num5 * 360.0);
double num7 = 1.5707963267948966 - (2.0 * Math.Atan(Math.Exp((-1.0 * y) / 6378137.0)));
mercatorX_lon = num6;
mercatorY_lat = num7 * 57.295779513082323;
}
private void ToWebMercator(ref double mercatorX_lon, ref double mercatorY_lat)
{
if ((Math.Abs(mercatorX_lon) > 180 || Math.Abs(mercatorY_lat) > 90))
return;
double num = mercatorX_lon * 0.017453292519943295;
double x = 6378137.0 * num;
double a = mercatorY_lat * 0.017453292519943295;
mercatorX_lon = x;
mercatorY_lat = 3189068.5 * Math.Log((1.0 + Math.Sin(a)) / (1.0 - Math.Sin(a)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment