我是一个坐标,我需要知道它是否在一个正方形内。为了达到这个目的,我获得了这个广场的NorthEast和SouthWest坐标。
到目前为止,我想出了以下代码:
const isInsideSquare = (center, northEast, southWest) =>
southWest.lat < center.lat &&
northEast.lat > center.lat &&
northEast.lng < center.lng &&
southWest.lng > center.lng;
但是,此代码失败,并带有以下示例:
const northEast = {lat: 42.1539732831, lng: -4.7027107182};
const southWest = {lat: 36.8340642391, lng: -11.5965440996};
const coord = {lat: 38.7223, lng: -9.1393};
console.log(isInsideSquare(coord, northEat, southWest)); //false
问题是我的函数返回false而不是true。如您所见,coord
位于广场内:
https://www.darrinward.com/lat-long/?id=59e70fdf5c8578.99150744
但不知怎的,我想念它。
我的代码有什么问题?
答案 0 :(得分:0)
应该是
const isInsideSquare = (center, northEast, southWest) =>
southWest.lat < center.lat &&
northEast.lat > center.lat &&
northEast.lng > center.lng && // <-- this condition reversed
southWest.lng < center.lng; // <-- this condition reversed
因为SouthWest边缘的纬度和经度都大于中心的坐标。东北方的两个坐标都应该更低。
答案 1 :(得分:0)
在经度上你处理一个圆圈,你的角度环绕,你必须处理它,或者以某种方式将其标准化
const normalizeDegrees = v => v < 0 ? 360 + v % 360 : v % 360;
const isInsideSquare = (center, northEast, southWest) => (
southWest.lat < center.lat &&
northEast.lat > center.lat &&
normalizeDegrees(center.lng - southWest.lng) < normalizeDegrees(northEast.lng - southWest.lng));
const northEast = {
lat: 42.1539732831,
lng: -4.7027107182
};
const southWest = {
lat: 36.8340642391,
lng: -11.5965440996
};
const coord = {
lat: 38.7223,
lng: -9.1393
};
console.log(isInsideSquare(coord, northEast, southWest));
&#13;
.as-console-wrapper{top:0;max-height:100%!important}
&#13;
中心西南方向度度远远超过东北方。