Search This Blog

Monday, September 3, 2012

Convert coordinates between Web Mercator and WGS84 Geographic

From: http://www.gal-systems.com/2011/07/convert-coordinates-between-web.html

Convert coordinates from Web Mercator (102100/3857) to WGS84 Geog (4326) and vice versa you can use these short functions (taken from Esri):


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)));
}