The haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes. Important in navigation, it is a special case of a more general formula in spherical trigonometry, the law of haversines, that relates the sides and angles of spherical triangles. (Wikipedia)
Personally, I have always found it easier to handle and store coordinates as strings. Very rarely is it required to perform any arithmetic operations on the values.
Add the following to an existing query builder instance, and then not forgetting to call
The query assumes that your table contains columns called
longitude. You may need to adapt these to suit your use case.
// the centre of your search$latitude = '56.32124';$longitude = '-1.342934';// search radius$distance = 5; //(miles - see note)$query->selectRaw('(3959 * acos (cos ( radians(?) )* cos( radians( latitude ) )* cos( radians( longitude ) - radians(?) )+ sin ( radians(?) )* sin( radians( latitude )))) AS distance',[$latitude,$longitude,$latitude]);$query->havingRaw('distance <= ? OR 0', [$distance]);