我有一个点列表(实际上是商店坐标),我需要确定它们是否位于特定边界内。
在 C# 中,我知道如何从 lat&lng 创建一个点
var point = new GeoCoordinate(latitude, longitude);
但是我如何检查该点是否包含在由其他两点定义的矩形中:
var swPoint = new GeoCoordinate(bounds.swlat, bounds.swlng);
var nePoint = new GeoCoordinate(bounds.nelat, bounds.nelng);
我可以使用任何类方法吗?
如果您正在使用 http://msdn.microsoft.com/en-us/library/system.device.location.geocooperative.aspx
您必须编写自己的方法来进行此检查。您可能希望将其设为扩展方法(在线扩展方法上提供了大量资源。)
那么它几乎就像
一样简单public static Boolean isWithin(this GeoCoordinate pt, GeoCoordinate sw, GeoCoordinate ne)
{
return pt.Latitude >= sw.Latitude &&
pt.Latitude <= ne.Latitude &&
pt.Longitude >= sw.Longitude &&
pt.Longitude <= ne.Longitude
}
有一个极端情况需要考虑。如果 sw、ne 定义的框跨越 180 度经度,上述方法将失败。因此必须编写额外的代码来覆盖这种情况,从而降低该方法的性能。
为了回答我的应用程序的这个问题,我对自己说:“如果北从 0 度开始,南在 180 度,东在 0 度,西在 360 度结束,那么计算一个点是否在特定范围内不是更简单吗?”当你以这种方式思考坐标时,计算起来就变得相对简单了。只需将纬度和经度转换为一个系统,就好像地球被 0 到 90 度和 0 到 360 度所束缚。
这是我想出的 C# 函数:
public static bool CheckWithinBounds(double lat, double lon, double northLat, double southLat, double eastLon, double westLon)
{
bool latOK = false;
bool lonOK = false;
/* Convert to 0 to 180 and 0 to 360 system */
lat = 90 - lat;
if (lon < 0) lon += 360;
northLat = 90 - northLat;
southLat = 90 - southLat;
if (westLon < 0) westLon += 360;
if (eastLon < 0) eastLon += 360;
/* Check if point is within the bounds */
if (lat >= northLat && lat <= southLat)
{
latOK = true;
}
/* Check if bounds are all east of the meridian... */
if (westLon < eastLon)
{
if (lon >= westLon && lon <= eastLon)
{
lonOK = true;
}
}
/* ...or straddle the meridian */
else
{
if (lon <= eastLon || lon >= westLon)
{
lonOK = true;
}
}
if (latOK && lonOK)
{
return true;
}
else
{
return false;
}
}
lat 和 lon 是您要测试的点的纬度和经度。 NorthLat、southLat、eastLon、westLon 是您想要查看测试点是否位于其中的区域的边界。