Calculate whether one coordinate is within range of another

有些话、适合烂在心里 提交于 2019-12-07 07:25:21

问题


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;
    }

回答1:


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

var distance = coordinateA.GetDistanceTo(coordinateB);

(where coordinateA and B are of type GeoCoordinate)

See the MDSN documentation.




回答2:


A quick search brought up this page with a formula for computing distance between two points on the earth. Quoted directly from the linked page:

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).

Just plug in the lat/long values for your current location and another location and you should get d, which is the distance in km between those two points.



来源:https://stackoverflow.com/questions/3681236/calculate-whether-one-coordinate-is-within-range-of-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!