Show how far each of ~4,500 stores is from the user.
ST_Distance returns 2400. What unit is that?
Reveal answer
✓ Answer
Metres, so 2.4 km.
Eloquent performanceLesson 25 of 28
Distances belong in SQL: ST_Distance returns metres.
1 min readIntermediateLesson
Show how far each of ~4,500 stores is from the user.
Let MySQL calculate it with ST_Distance on two GPS points.
Store::all()->map(function ($store) use ($lat, $lng) {
$store->distance = haversine($lat, $lng, $store->latitude, $store->longitude);
return $store;
});
// loads all ~4,500 stores into PHP
In scopeSelectDistanceTo($query, array $coordinates):
if (is_null($query->getQuery()->columns)) {
$query->select('*');
}
$query->selectRaw('ST_Distance(
ST_SRID(Point(longitude, latitude), 4326),
ST_SRID(Point(?, ?), 4326)
) as distance', $coordinates);
The database calculates every distance, so you can paginate, filter and sort on it.
ST_SRID(Point(lng, lat), 4326) builds a proper GPS point (4326 is the standard GPS coordinate system). The distance comes back in metres.
select('*') first if nothing is selected yet, otherwise you only get the distance column.number_format($store->distance / 1000, 2).
scopeSelectDistanceTo: it adds select('*') if no columns are selected yet, then selectRaw('ST_Distance(ST_SRID(Point(longitude, latitude), 4326), ST_SRID(Point(?, ?), 4326))'). The result is in metres.
Distances belong in SQL: ST_Distance returns metres.
ST_Distance returns 2400. What unit is that?
✓ Answer
Metres, so 2.4 km.