Problem:
While working on a project using Laravel back-end and JavaScript front-end. I had a situation where I needed to get all the locations for the map with given bounds. First, I tried just doing a bounding box check, which worked but only sometimes.
Solution:
In this problem, I was not alone. After reading and trying some various approaches, this one by FatMonk on SO did the trick.
// Google Maps API map.getBounds()
$north = $lat1_ne || 90;
$east = $lng1_ne;
$south = $lat2_sw || -90;
$west = $lng2_sw;
$locations = Location::whereBetween('lat', [$south, $north])
->where(function($query) use ($west, $east){
if ($west < $east){
$query->whereBetween('lon', [$west, $east]);
}else{
$query->whereBetween('lon', [$west, 180])
->orWhereBetween('lon', [-180, $east]);
}
})
->get();