我有两个矩形,想检测矩形在地理坐标中是否与其他矩形相交。我的实际代码仅适用于正的地理坐标值
if (rect1.MaxLongitude < rect2.MinLongitude || rect2.MaxLongitude < rect1.MinLongitude || rect1.MaxLatitude < rect2.MinLatitude || rect2.MaxLatitude < rect1.MinLatitude)
{
return false;
}
else
{
return true;
}
如何在具有负值和正值(甚至在一个坐标中)的地理坐标中实现检测?
矩形是否可以自由旋转,或者线条是否严格水平和垂直?前者的难度略高。您的代码暗含了后者。
假设是后者,我希望您的代码即使对于负数也可以使用...
0
|
LON(-)/LAT(+) | LON(+)/LAT(+)
|
---------------+-----------------0
|
LON(-)/LAT(-) | LON(+)/LAT(-)
|
除了顺序很重要。如果这些比较中的任何一个为真,则您的算法在某些条件下会中断,例如:
rect1.minLon < rect2.minLon
rect1.maxLon < rect2.maxLon
让我们通过算法获取一些示例矩形:
两个相交的正矩形:rect1 {(1,1)-(4,4)} rect2 {(2,2)-(6,6)}
给我们返回假值,因为我们只需要一个真值
rect1.MaxLongitude(4) < rect2.MinLongitude(2) false
rect2.MaxLongitude(6) < rect1.MinLongitude(1) false
rect1.MaxLatitude(4) < rect2.MinLatitude(2) **true**
rect2.MaxLatitude(6) < rect1.MinLatitude(1) false
如果它们不相交但rect2在地图上比rect1低,会发生什么:rect1 {(10,10)-(40,40)}矩形{(2,2)-(6-6)}
这也使我们返回了false,但是三角形不相交,因为这仍然是正确的:
rect1.MaxLongitude(40) < rect2.MinLongitude(2) false
rect2.MaxLongitude(6) < rect1.MinLongitude(10) **true**
rect1.MaxLatitude(40) < rect2.MinLatitude(2) false
rect2.MaxLatitude(6) < rect1.MinLatitude(20) **true**
这是您的算法的一种极端情况问题,其中(rect1.minLon> rect2.minLon && rect1.minLat> rect2.minLat)。确保您的算法在这两种情况下都有效的一种方法是,确定要比较rect1始终较低且在rect2的左侧(向西)的位置。但是,仍然存在问题,因为您仍然不允许以下操作:(rect1.minLon> rect2.minLon && rect1.minLat 我已经精疲力尽,并不会为您实际解决问题,但是您可以通过将问题分为4种情况来解决该问题:场景1:(rect1.minLon> rect2.minLon && rect1.maxLon> rect2.maxLon)方案2:(rect1.minLon 每个方法都有一个单独的方法,每个方法都具有与您当前算法一样简单的解决方案,但实际上它们并不相同。