我对确定lat / lng位置是否在边界内并寻找算法建议感兴趣。 (javascript或php)
这是我到目前为止所做的:
var lat = somelat;
var lng = somelng;
if (bounds.southWest.lat < lat && lat < bounds.northEast.lat && bounds.southWest.lng < lng && lng < bounds.northEast.lng) {
'lat and lng in bounds
}
这会有效吗?感谢
答案 0 :(得分:14)
您帖子中的简单比较适用于美国的坐标。但是,如果您想要一个可以安全检查国际日期变更线(经度为±180°)的解决方案:
function inBounds(point, bounds) {
var eastBound = point.long < bounds.NE.long;
var westBound = point.long > bounds.SW.long;
var inLong;
if (bounds.NE.long < bounds.SW.long) {
inLong = eastBound || westBound;
} else {
inLong = eastBound && westBound;
}
var inLat = point.lat > bounds.SW.lat && point.lat < bounds.NE.lat;
return inLat && inLong;
}
答案 1 :(得分:5)
当你询问Javascript和PHP(我在PHP中需要它)时,我将CheeseWarlock的优秀答案转换为PHP。像往常一样,PHP不那么优雅。 :)
function inBounds($pointLat, $pointLong, $boundsNElat, $boundsNElong, $boundsSWlat, $boundsSWlong) {
$eastBound = $pointLong < $boundsNElong;
$westBound = $pointLong > $boundsSWlong;
if ($boundsNElong < $boundsSWlong) {
$inLong = $eastBound || $westBound;
} else {
$inLong = $eastBound && $westBound;
}
$inLat = $pointLat > $boundsSWlat && $pointLat < $boundsNElat;
return $inLat && $inLong;
}
答案 2 :(得分:0)
这是我为MySQL修改的我的代码 现在,它可以通过mysql查询直接检查我们的长纬度是否在界限内。
特别感谢CheeseWarlock和Chris Rae的解决方案先生
select inBounds("58.25173","-100.21041","89.71691425364952","180","-88.9294031317244","-180")
,您可以像这种方式在查询中调用此函数
DELIMITER $$
CREATE FUNCTION inBounds(pointLat FLOAT, pointLong FLOAT, boundsNElat FLOAT, boundsNElong FLOAT, boundsSWlat FLOAT, boundsSWlong FLOAT) RETURNS VARCHAR(30)
BEGIN
DECLARE westBound FLOAT ;
DECLARE eastBound FLOAT ;
DECLARE inLong FLOAT DEFAULT 0 ;
DECLARE inLat FLOAT DEFAULT 0 ;
IF (pointLong < boundsNElong) THEN
SET eastBound = 1;
End if;
IF (pointLong > boundsSWlong) THEN
SET westBound = 1;
End if;
IF (boundsNElong < boundsSWlong) THEN
IF (eastBound || westBound) THEN
SET inLong = 1;
END if;
ELSE
IF (eastBound && westBound) THEN
SET inLong = 1;
END IF;
END IF;
IF (pointLat > boundsSWlat && pointLat < boundsNElat) THEN
SET inLat = 1;
END IF;
RETURN inLat && inLong;
END$$
DELIMITER ;
答案 3 :(得分:0)
这是CheeseWarlock的Js答案的稍微优化的版本,它会短路。
const inBounds = (point, bounds) => {
const inLat = point.lat > bounds.sw.lat && point.lat < bounds.ne.lat
if (!inLat) return false
const eastBound = point.lng < bounds.ne.lng
const westBound = point.lng > bounds.sw.lng
return (bounds.ne.lng < bounds.sw.lng)
? eastBound || westBound
: eastBound && westBound
}