I'm writing a Windows Phone 7 app that needs to be location aware. Specifically I want some (c#) code to run when the phone comes within a (fixed) range of a particular location, say 0.5 miles. I have all the lat / long data for the physical locations in memory. I will be using the Geo Coordinate Watcher class to get the devices current coordinates. Now the only trick is to calculate whether the user is in range of any of the locations.
Thanks!
Update: as promised here's the little C# function which uses the Spherical Law of Cosines method of calculating distances. Hope it can help someone else. Note: I'm writing a Windows Phone 7 app so used the GeoLocation class. If you're using "regular" c# then you can change the function to accept the two coordinate pairs the function needs.
internal const double EarthsRadiusInKilometers = 6371;
/// <summary>
/// The simple spherical law of cosines formula
/// gives well-conditioned results down to
/// distances as small as around 1 metre.
/// </summary>
/// <returns>Distance between points "as the crow flies" in kilometers</returns>
/// <see cref="http://www.movable-type.co.uk/scripts/latlong.html"/>
private static double SpericalLawOfCosines(GeoCoordinate from, GeoCoordinate to)
{
return ( Math.Acos (
Math.Sin(from.Latitude) * Math.Sin(to.Latitude) +
Math.Cos(from.Latitude) * Math.Cos(to.Latitude) *
Math.Cos(to.Longitude - from.Longitude)
) * EarthsRadiusInKilometers)
.ToRadians();
}
/// <summary>
/// To a radian double
/// </summary>
public static double ToRadians(this double d)
{
return (Math.PI / 180) * d;
}