Calculating Distance From 2 GeoCoordinates in Windows Phone 8

This is a support post for the Inside Windows Phone show on location and mapping in Windows Phone 8 published here.

Calculating the distance between two GeoCoordinates in Windows Phone 8 is about as simple as it can get. First, get a GeoCoordinate. One handy way of doing this is to get the location of a tap on the Map control.

Set up the tap event hander on your Map:

 <maps:Map x:Name="myMap" Tap="ReadMapTap" />

And then translate the tap location into a GeoCoordinate like so:

 void ReadMapTap(object sender, System.Windows.Input.GestureEventArgs e)
{
    GeoCoordinate tapLocation = 
         distanceMap.ConvertViewportPointToGeoCoordinate(e.GetPosition((UIElement)sender));
}

Then we just create another GeoCoordinate, like maybe Microsoft campus:

 GeoCoordinate Msft = new GeoCoordinate(47.6396, -122.1300);

And just ask one of our GeoCoordinates how far it is to the other one.

 double distanceToMSFT = tapLocation.GetDistanceTo(Msft);
MessageBox.Show("It is " + distanceToMSFT.ToString() + " meters from there to Microsoft!");

The result will be in meters and is based on the haversine formula for calculating distance over the surface of the earth (my favorite!)