首页 > 解决方案 > 确定坐标是否在边界框内

问题描述

我需要创建一个给定的函数abc返回一个布尔值,指示是否caand内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.

标签: javascriptnode.jstypescriptgeometryleaflet

解决方案


边界框测试必须检查框的四个边。

球体表面中的框不是矩形,因此很难使用 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.lonbottomLeft.lat < topRight.lat


推荐阅读