Lucky for you I dug out a database from old project with geometry calculations :)
Tested and it is working as intended, enjoy:
// Sample model method
public static function findByRawSql($params = null)
{
// A raw SQL statement
$sql = '
SELECT *, 111.045 * DEGREES(ACOS(COS(RADIANS(:lat))
* COS(RADIANS(X(coords)))
* COS(RADIANS(Y(coords)) - RADIANS(:lng))
+ SIN(RADIANS(:lat))
* SIN(RADIANS(X(coords)))))
AS distance_in_km
FROM object_locations
ORDER BY distance_in_km ASC
LIMIT 0,5;
';
// Base model
$model = new ObjectLocations();
// Execute the query
return new \Phalcon\Mvc\Model\Resultset\Simple(
null,
$model,
$model->getReadConnection()->query($sql, $params)
);
}
// How to use:
\Models\ObjectLocations::findByRawSql([
'lat' => 42.4961756,
'lng' => 27.471543300000008
])
P.S. note that I replaced your latitude
& longitude
with X(coords)
and Y(coords)
since I was storing coordinates in a single POINT
field, make sure to replace with your fields :)