arrowHome arrow TechBlog Thursday, 30 November 2023  
Main Menu
Home
Quality Snaps
TechBlog
PennCharts
Blog
Family
Auld Frosties
Links
Players
Players (uni)
Players (camb)
Contact Us
Pennchart Recent
pennchart radio

Converting Lat/Long to/from Web Mercator in C#

ESRI has a utility class for converting Lat Long from/to Web Mercator for use with bing/google maps.

They provide this functionality through a dll (ESRI.ArcGIS.Client.Bing) which requires Silverlight to be installed. Don’t have/want Silverlight on your web server, don’t have/want ArcObjects? Then nab this:

private void WebMercatorToGeographic(double mercatorX, double mercatorY, out double lat, out double lon)
{
if ((mercatorX < -20037508.3427892) || (mercatorX > 20037508.3427892))
{
throw new ArgumentException(”Point does not fall within a valid range of the mercator projection.”);
}
double x = mercatorX;
double y = mercatorY;
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)));
lat = num6;
lon = num7*57.295779513082323;
}

private void GeographicToWebMercator(double lat, double lon, out double mercatorX, out double mercatorY)
{
if ((lat < -90.0) || (lon > 90.0))
{
throw new ArgumentException(”Point does not fall within a valid range of a geographic coordinate system.”);
}
double num = lat * 0.017453292519943295;
double x = 6378137.0 * num;
double a = lon * 0.017453292519943295;

mercatorX = x;
mercatorY = 3189068.5*Math.Log((1.0 + Math.Sin(a))/(1.0 - Math.Sin(a)));
}

No Comments

Add your own comment...

Frosties RandomSnap
IMG_4324

IMG_4324

top of page