计算一个坐标是否在另一个坐标范围内 [英] Calculate whether one coordinate is within range of another

查看:474
本文介绍了计算一个坐标是否在另一个坐标范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Windows Phone 7应用,该应用需要位置识别.具体来说,当电话进入特定位置的(固定)范围(例如0.5英里)时,我希望运行一些(c#)代码.我在内存中拥有物理位置的所有经/纬度数据.我将使用地理坐标观察器类获取设备的当前坐标.现在,唯一的技巧就是计算用户是否在任何位置的范围内.

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.

谢谢!

更新:如所承诺的那样,这是使用

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

推荐答案

既然您使用的是GeoCoordinate,为什么要在该类中已经存在的情况下自己实现它?

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

var distance = coordinateA.GetDistanceTo(coordinateB);

(其中坐标A和B的类型为GeoCoordinate)

(where coordinateA and B are of type GeoCoordinate)

请参见 MDSN文档

这篇关于计算一个坐标是否在另一个坐标范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆