Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if Lat/Lng in Bounds

I'm interested in determining if a lat/lng location is within the bounds and looking for recommendations on a algorithm. (javascript or php)

Here is what I have so far:

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
}

will this work? thanks

like image 535
Tegan Snyder Avatar asked Jun 07 '12 20:06

Tegan Snyder


2 Answers

As you asked about both Javascript and PHP (and I needed it in PHP), I converted CheeseWarlock's great answer into PHP. Which, as usual with PHP, is a lot less elegant. :)

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;
}
like image 98
Chris Rae Avatar answered Oct 18 '22 04:10

Chris Rae


The simple comparison in your post will work for coordinates in the US. However, if you want a solution that's safe for checking across the International Date Line (where longitude is ±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;
}
like image 32
CheeseWarlock Avatar answered Oct 18 '22 04:10

CheeseWarlock