Calculate if one coordinate is within the range of another

I am writing a Windows Phone 7 application that should be aware of the location. In particular, I want some kind of code (C #) to start when the phone enters the (fixed) range in a certain place, say, 0.5 miles. I have all the lat / long data for physical locations in memory. I will use the Geo Coordinate Watcher class to get the current coordinates of devices. Now the only trick is to calculate whether the user is within any of the locations.

Thank!

Update : as promised here is a small C # function that uses the Spherical Law of Cosines method to calculate distances. Hope this helps someone else. Note. I am writing a Windows Phone 7 application, so I used the GeoLocation class. If you use "normal" C #, you can change the function to accept the two pairs of coordinates that 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;
    }
+5
source share
2 answers

Since you are using GeoCoordinate, why implement it yourself when it is already in this class?

var distance = coordinateA.GetDistanceTo(coordinateB);

(where coordinates A and B are of type GeoCoordinate)

See the MDSN documentation .

+4
source

. :

Haversine formula:

R = earth’s radius (mean radius = 6,371km)
Δlat = lat2− lat1
Δlong = long2− long1
a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
c = 2.atan2(√a, √(1−a))
d = R.c

(Note that angles need to be in radians to pass to trig functions).

lat/long , d, .

+2

All Articles