I was hunting around for how to calculate the distance between two GeoCoordinates on Windows Phone 7. Currently if you do a Google search to find how to accomplish this you will find a number of blogs talking about the need to use a Haversine formula that takes into account the curvature of the earth.
This is all well and good and the code for the Haversine formula isn’t that hard (okay the maths is beyond me, but copy and paste is within my skill level)
Anyway despite what a Google search will tell you there is a much easier way to do this. There is already support for it built right into the phone’s location API. The GeoCoordinate class itself has a GetDistanceTo() method right on it.
Returns the distance between the latitude and longitude coordinates that are specified by this GeoCoordinate and another specified GeoCoordinate.
var myLocation = new GeoCoordinate(-51.39792, -0.12084); var yourLocation = new GeoCoordinate(-29.83245, 31.04034); double distance = myLocation.GetDistanceTo(yourLocation);
Doesn’t come much easier than that.
There is one gotcha however. The GetDistanceTo() method always returns the result in
kilometers meters. If you need a result in miles I would suggest you use Dragos Manolescu’s Haversine implementation.