In a CakePHP (v3) application, how can I retrieve the closest results based on passed lat lng values?
I'd like to have them back as native CakePHP entities, so something like this:
public function closest($lat, $lng) {
$sightings = //records within given lat lng
$this->set(compact('sightings'));
$this->set('_serialize', ['sightings']);
}
I know this SQL works:
SELECT *,
( 3959 * acos( cos( radians(50.7) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-1.8) ) + sin( radians(50.7) ) * sin( radians( latitude ) ) ) ) AS distance
FROM sightings
HAVING distance < 10
ORDER BY distance
LIMIT 0 , 20
Struggling to combine the two.
UPDATE
I've added
class Sighting extends Entity {
public $_virtual = ['distance'];
//rest of class...
}
So now the distance
is showing up in my json output (with the value of null as would be expected right now, but I feel it's a step at lease).
I've taken a look here: http://www.mrthun.com/2014/11/26/search-distance-cakephp/ which seems to be what I'm trying to achieve so assumed something like this:
$latitude = 51.145;
$longitude = -1.45;
$distance = 100;
$this->Sightings->virtualFields
= array('Sightings.distance'
=> '(3959 * acos (cos ( radians('.$latitude.') )
* cos( radians( Sightings.latitude ) )
* cos( radians( Sightings.longitude )
- radians('.$longitude.') )
+ sin ( radians('.$latitude.') )
* sin( radians( Sightings.latitude ) )))');
$sightings = $this->Sightings->find('all', [
'conditions' => ['Sightings.distance <' => $distance]
]);
$this->set(compact('sightings'));
$this->set('_serialize', ['sightings']);
Results in: Column not found: 1054 Unknown column 'Sightings.distance' in 'where clause'
Not sure if it's possible CakePHP v2 as opposed to v3?