2012-06-07 105 views
5

我有興趣確定lat/lng位置是否在邊界內並尋找算法推薦。 (JavaScript或PHP)確定Lat/Lng是否在邊界

這是我到目前爲止有:

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 
} 

這項工作?謝謝

+3

你問我們是否會工作?我正要問你是否工作。 –

+1

我認爲如果你的界限包括東西經度座標,你會遇到一些問題。根據你使用的座標系統,這可能是覆蓋南/北極,0度經度(英格蘭,非洲等)和180W/E(在太平洋)的區域 – netfire

+0

@ScottSaunders是我更少問是否合乎邏輯。 –

回答

9

您的文章中的簡單比較將適用於美國的座標。但是,如果你想一個解決方案,是安全的跨越國際日期變更線檢查(其中經度±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; 
} 
4

當你問到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; 
} 
相關問題