计算一个坐标是否在另一个范围内

问题描述:

我正在编写需要位置感知的Windows Phone 7应用程序。具体而言,我希望某些(c#)代码在电话进入特定位置(固定)范围内时运行,例如说0.5英里。我拥有存储器中所有物理位置的纬度/经度数据。我将使用Geo Coordinate Watcher class来获取设备的当前坐标。现在唯一的技巧是计算用户是否在任何位置的范围内。计算一个坐标是否在另一个范围内

谢谢!

更新:作为承诺这里的小C#功能,它使用Spherical Law of Cosines计算距离的方法。希望它可以帮助别人。注意:我正在编写Windows Phone 7应用程序,因此使用了GeoLocation类。如果你使用“regular”c#,那么你可以改变函数来接受函数需要的两个坐标对。

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

出于好奇,为什么不使用在同一页上呈现的更简单(更快)的余弦定律?作者指出,对于大于1米的距离,建议和准确。 – ctacke 2010-09-20 01:30:20

+0

我刚刚重新阅读文章,你说得对,Cosines的球形法更简单。实际上,我实现了这两个方法来看看它是如何完成的 - 我也会发布该代码。谢谢... – will 2010-09-20 16:24:44

既然您正在使用GeoCoordinate,那么为什么当它已经存在于该类中时自己实现呢?

var distance = coordinateA.GetDistanceTo(coordinateB); 

(其中coordinateA和B型的会有地理座标)

MDSN documentation

+0

我不知道这是在那里。我爱* ...谢谢! – will 2011-02-03 04:06:44

+0

哇!我不知道这是在那里! – 2012-01-05 03:11:39

一个快速搜索带来了this 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). 

在纬度/长值,只需将您的当前位置,另一个位置,你应该得到d,这是这两个点之间的千米的距离。

+1

这种方法很扎实,只要确定了解它的局限即可。这是不确切的,如果你在山区,那么剧烈的海拔变化也会发挥作用。不过,对于大多数用途而言,这应该会很好。 – Brad 2010-09-09 23:40:59

+0

谢谢你们。无视高程问题一分钟,对准确度有什么限制?你是否说我想要的精细粒子精确度不高?即50英里的范围相当准确,但是50米的范围不是很准确? – will 2010-09-10 01:11:34

+1

这是一个大圆计算。计算本身没有错误,你的估计位置确实如此。你的GPS接收器知道你在哪里+/-某些数量(取决于接收器,卫星数量等)。比方说,例如,它是+/- 25米。好吧,如果你说的是50英里的距离,那么百分比就不会太远。如果你说的是50米的距离,那么这是一个非常大的数字。 – ctacke 2010-09-10 01:26:15