Determine if Lat/Lng in Bounds
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;
}
This is a slightly optimized version of CheeseWarlock's Js answer, that short circuits.
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
}
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;
}