确定坐标是否在边界框内

时间:2019-10-17 17:06:02

标签: javascript node.js typescript geometry leaflet

我需要创建一个函数,给定abc返回一个布尔值,指示布尔值c是否在a和{{1 }}。

所有变量具有以下类型:

b

我最初提出的解决方案虽然是正确的,但是在使用Google Maps测试后,我发现它是错误的。

功能:

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
  );
}

视觉表示为here

我需要帮助来找出确切的代码错误以及如何修复它。

我还尝试使用Leaflet来查看它是否有效,但结果是相同的:

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.

2 个答案:

答案 0 :(得分:1)

这行是错误的

else {
  isLongInRange = point.lon >= bottomLeft.lon && point.lon <= topRight.lon;
}

必须是||而不是&&,并且必须是以下之一:切换 >=<=bottomLeft.lontopRight.lon的切换位置

else {
  isLongInRange = point.lon <= bottomLeft.lon || point.lon >= topRight.lon;
}

答案 1 :(得分:1)

包围盒测试必须检查盒子的四个侧面。

球体表面的盒子不是矩形,因此很难使用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

相关问题