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.

`GeoCoordinate.GetDistanceTo() `

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.

### Like this:

Like Loading...

*Related*

I was searching the formula, i didn’t see the GeoCoordinate’s method. Thank you for this little article.

GetDistanceTo() return the result in meters not in kilometers

Another Haversine implementation just because you cannot convert meters to miles??

How about: miles = distanceInMeters/1609.344; ? 😉

Whats the formula for Km???

1 km is 1000 meters.

no, we can’t say miles = distanceInMeters/1609.344, because this distance’s formula works only if we measure distances in the plane. Remember the sphere shape of the planet Earth. That’s why we need to use the Dragos Manolescu’s Haversine implementation.

hi, I want to use variables instead of numbers

for exemple:

var myLocation = new GeoCoordinate(lat1, lon1);

var yourLocation = new GeoCoordinate(lat2, lon2);

double distance = myLocation.GetDistanceTo(yourLocation);

Values of variable are defined but i’ve an Error.

“Latitude or longitude is not a number NaN”

My question is: Is it possible to use variable? and if it’s possible: how?

Thank you.

SamD

I can’t tell you why you are getting a NaN error with your code, but I can say that it is definitely possible to variables as you are trying to do. I would check the values of “lat1”, “lon1”, “lat2” and “lon2”. One of those is most likely not a valid GeoCoordinate value.

I know that this is a old post but figured I would give the answer here. Aiden is correct, I just ran across the same issue using the emulator and I did not setup test locations for it so thats why I was not getting valid lat and lon