Skip to content

Instantly share code, notes, and snippets.

@oliverheilig
Last active December 25, 2015 19:19
Show Gist options
  • Save oliverheilig/7027256 to your computer and use it in GitHub Desktop.
Save oliverheilig/7027256 to your computer and use it in GitHub Desktop.
CalcDistance
// Calcluate airline distance based on mercator distance.
// This approximation formula is sufficiently accurate for
// our needs for distances of up to 600 km and
// 80° latitude (the error is never more than 5% even for
// extreme values).
using System;
public class Program {
public static void Main () {
double lat1 = 49.0;
double lon1 = 8.0;
double lat2 = 50.0;
double lon2 = 9.0;
// convert to PTV Mercator
double x1, y1, x2, y2;
LatLonToSphereMercator(lat1, lon1, out x1, out y1);
LatLonToSphereMercator(lat2, lon2, out x2, out y2);
// mercator distance
double mercDist = Math.Sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
// real distance
double realDist = mercDist * Math.Cos(lat1 * Math.PI / 180.0);
Console.WriteLine("Distance Between {0}/{1} and {2}/{3}", lat1, lon1, lat2, lon2);
Console.WriteLine("Mercator: {0}", mercDist);
Console.WriteLine("Real: {0}", realDist);
}
// Project a geographic coordinate on the (spherical) Mercator map.
// Using the mean between major an minor axis here ("PTV standard").
// You could also use the major axis 6378137 ("Google standard").
public static void LatLonToSphereMercator(double latitude,
double longitude, out double x, out double y)
{
x = 6371000.0 * longitude * Math.PI / 180;
y = 6371000.0 * Math.Log(Math.Tan(Math.PI / 4 + latitude * Math.PI / 360));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment