确定经纬度是否在矩形范围内

3

如果给定左上角和右下角的经纬度,如何确定特定的经纬度是否在矩形内部?

理想情况下,我将寻找类似于以下内容的东西:

bool IsWithinArea(float topLeftLat,float topLeftLong,
   float bottomRightLat,float bottomRightLong,float testLat,float testLong)

更新

唯一的问题是,从经纬度创建的矩形可能来自旋转的地图,因此右下角不总是大于左上角...


作业?这很琐碎... - Jon Cage
1
不,这不是作业,是我的错误。我以为经度和纬度是某种巫术,没想到它这么显而易见。 - Richard Friend
由于您提到了纬度和经度,我假设您想要确定地球表面特定区域内某个点的位置。如果是这样,那么下面给出的任何答案都不适用。 - Moshi
4个回答

5
我们可以将它变得更有趣,而不是仅仅进行琐碎的检查:
return new Rect(topLeftLat, topLeftLong, bottomRightLat - topLeftLat, bottomRightLong - topLeftLong)
      .Contains(testLat, testLong);

P.S.: Rect.Contains(...) method


1
不错的解决方案!但是为什么要将左上角从右下角中减去?我会使用左上角和右下角来构造矩形,而不是使用左上角和边长... - hage
@stefanm 这是一个内置的 .Net 类,我使用了已经存在的构造函数,而不是我的选择。 - Snowbear
1
每次调用函数时,这将分配一个新的Rect对象。注意内存或性能问题。 - lzm
有一个静态的RectangleF.FromLTRB(,,,,)可以避免计算宽度和高度。 - g1ga

2

我不确定自己是否想得太简单了。

这句话与IT技术无关。
bool IsWithinArea(float topLeftLat, float topLeftLong, float bottomRightLat, float bottomRightLong, float testLat, float testLong)
{
    return (testLat >= topLeftLat && testLat <= bottomRightLat && testLong >= topLeftLong && testLong <= bottomRightLong);
}

只有在矩形与x和y轴对齐时才起作用,如果矩形被放置在某个角度上,它将失败。 - Jules

1
假设Lat是x坐标,Long是y坐标,并且假设坐标系统的原点在左上角:
public bool IsWithinArea(float topLeftLat,float topLeftLong,
       float bottomRightLat,float bottomRightLong,float testLat,float testLong) {

          return (testLat >= topLeftLat && testLat <= bottomRightLat && testLong >= topLeftLong && testLong <= bottomRightLong);

    }

1

一种方法是将您的经纬度对归一化为简单的x/y坐标。然后,确定一个点是否在矩形内就变得非常简单。

可以在这里找到从经纬度到x/y的转换:将经纬度转换为X/Y坐标


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接