TALL Stack Tips

Searchâ€¦

Alpine

Laravel

Livewire

Find nearby locations using the Haversine formula in Eloquent query

Uses the haversine formula to find all DB records with a location within a specified radius

Haversine

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)

Managing coordinates

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.

If your requirements are more complex, and you have mysql 8, consider Spatial queries instead. https://dev.mysql.com/doc/refman/8.0/en/spatial-types.htmlâ€‹

Eloquent or DB Query Builder

Add the following to an existing query builder instance, and then not forgetting to call

`get()`

or `paginate()`

The query assumes that your table contains columns called

`latitude`

and `longitude`

. You may need to adapt these to suit your use case.1

// the centre of your search

2

$latitude = '56.32124';

3

$longitude = '-1.342934';

4

â€‹

5

// search radius

6

$distance = 5; //(miles - see note)

7

â€‹

8

$query->selectRaw('(3959 * acos (

9

cos ( radians(?) )

10

* cos( radians( latitude ) )

11

* cos( radians( longitude ) - radians(?) )

12

+ sin ( radians(?) )

13

* sin( radians( latitude )))) AS distance',[

14

$latitude,

15

$longitude,

16

$latitude

17

]);

18

19

$query->havingRaw('distance <= ? OR 0', [$distance]);

Copied!

The above assumes that you have distance in miles. If distance is in KM then replace 3959 with 6371.

References:

- â€‹

â€‹

Laravel - Previous

Adding column to Database Notifications table

Next - Laravel

PHP DateTime formatting cribsheet

Last modified 6mo ago

Copy link