javascript - 确定坐标是否在边界框内
问题描述
我需要创建一个给定的函数a
,b
并c
返回一个布尔值,指示是否c
在a
and内b
。
所有变量都具有以下类型:
type Coordinate = {
lat: number;
lon: number;
};
我想出了一个最初我认为是正确的解决方案,但在使用谷歌地图进行测试后,我发现它是错误的。
功能:
function inBoundingBox(
bottomLeft: Coordinate,
topRight: Coordinate,
point: Coordinate
) {
let isLongInRange: boolean;
if (topRight.lon < bottomLeft.lon) {
isLongInRange = point.lon >= bottomLeft.lon || point.lon <= topRight.lon;
} else {
isLongInRange = point.lon >= bottomLeft.lon && point.lon <= topRight.lon;
}
return (
point.lat >= bottomLeft.lat && point.lat <= topRight.lat && isLongInRange
);
}
一个应该起作用的例子:
const topRight: Coordinate = {
lat: -23.5273,
lon: -46.833881
};
const bottomLeft: Coordinate = {
lat: -23.537519,
lon: -46.840019
};
const point = {
lat: -23.52785,
lon: -46.840545
};
const result = inBoundingBox(bottomLeft, topRight, point);
console.log(result) // false, where should be true.
这里有一个视觉表示。
我需要帮助来找出代码到底哪里错了,以及如何修复它。
我也尝试过使用 Leaflet 看看它是否有效,但结果是一样的:
function leafletContains(bottomLeft, topRight, pos) {
var bounds = new L.LatLngBounds(
new L.LatLng(bottomLeft.lat, bottomLeft.lon),
new L.LatLng(topRight.lat, topRight.lon)
);
return bounds.contains(new L.LatLng(pos.lat, pos.lon));
}
leafLetContains({ lat: -23.537519, lon: -46.840019 }, { lat: -23.5273, lon: -46.833881 }, { lat: -23.527811, lon: -46.840201 }) // false, where should be true.
解决方案
边界框测试必须检查框的四个边。
球体表面中的框不是矩形,因此很难使用 x,y 坐标。但是使用“极”坐标(纬度,经度)很容易:
我不是 javascript 编码器,所以请原谅我在这段代码中的错误:
function inBoundingBox(
bottomLeft: Coordinate,
topRight: Coordinate,
point: Coordinate
) {
let isLongInRange: boolean;
let isLatiInRange: boolean;
isLongInRange = point.lon >= bottomLeft.lon && point.lon <= topRight.lon;
isLatiInRange = point.lat >= bottomLeft.lat && point.lat <= topRight.lat;
return ( isLongInRange && isLatiInRange );
}
假设bottomLeft.lon < topRight.lon
和bottomLeft.lat < topRight.lat
推荐阅读
- jquery - 如何在不重新加载页面的情况下从另一个 Form::select 的更改事件中更改 Form::select 的选定选项
- go - 为什么在这种情况下 float32 比 float64 更准确?
- python - 我必须归档,我需要根据文件 AddValueHere 的日期填补文件 LookupHere 的空白
- javascript - 使用 toLocalString 函数格式化为货币不起作用
- hive - sparkpy 坚持 HDFS 上的 root scratch dir: /tmp/hive 应该是可写的
- python - 将日期时间值转换为整数
- android - Flutter 从 1.5 升级到 1.7.4 后 APK 大小翻倍?
- python - 如何从 Python 中的 url 中删除“%20”?
- linux - 如何在ubuntu中使用bash从日志或命令结果中获取我需要粘贴到文件的字符串
- rest - REST API 发布请求使用 API 密钥进行身份验证