How to Find Nearest Location Using Latitude and Longitude In Sequelize 2022
Sometimes you need to find the nearest location using latitude and longitude within a radius.
In this article, we gonna learn how to use sequelize orm for finding nearby locations.
DB Structure - users table

models/connection.js
Here is an example for finding nearby 5 users within 1 km.
Note:- In case of miles just replace the 6371 with 3959 in the haversine formula.
Miles - 3959
Kilometer - 6371
you can also round the distance in query.
We can also make it reusable by defining this as a scope inside the model.
models/user.model.js
Note:- I have passed km as the default unit. so you don't need to pass in case of kilometer calculation.
Now in the controller, you can call this scope.
In the case of miles.
Checkout my full sequelize-geo example.
https://github.com/ultimateakash/sequelize-geo
If you facing any issues. don't hesitate to comment below. I will be happy to help you.
Thanks.
Leave Your Comment