Mongo
Last updated
Was this helpful?
Last updated
Was this helpful?
There are many ways to implement finding nearest locations by given latitude and longitude .
Some of the implementations can be achieved through a backend logic,
and the other ways can be done by utilizing some features(Spatial Indexes) provided by DBMSs’(Mysql, SQL, MongoDB,….etc).
In this post I will explain by example how we can do it with MongoDB.
What are Latitude and Longitude? , You can find more from here https://www.latlong.net/
Let’s create a collection in MongoDb and we call it locations
.
To Achieve the query of finding nearest locations by given latitude and longitude, we do the following Steps:
First Step : Each stored document must follow a structure called GeoJSON .
Second Step : We have to create 2dsphere Index in that collection .
Third Step : We run the Find query! .
The locations
collection will store a list of documents, each one of them represents a location(or an address) on the map.
Each document will follow this example/structure:
This Structure is following GeoJSON Structure!
— What’s GeoJSON Structure?
It is a JSON document that must have an object inside it , as follows :
Projection on the previous (Dubai Mall) document :
Read more about : GeoJSON Object https://docs.mongodb.com/manual/reference/geojson/
Ok, Great!, till now we’ve created locations
collection that has a list of documents that follow GeoJSON structure, so let’s suppose we have those documents inside locations
:
We need to run createIndex Command to tell MongoDb that this collection is following the GeoJSON structure, so we can achieve the query of finding nearest locations successfully.
Command syntax:
Projection:
As Per MongoDb documentation, here is the syntax of finding nearest locations by given latitude/longitude:
If I want to get the nearest locations to my current location, I should provide my current latitude/longitude, so let’s suppose
My Current Latitude: 25.087626 / Longitude: 55.151134 . (Dubai Marina)
So when I query the collection, we do:
Query Result: (ordered by nearest, according to my Latitude :25.087626/Longitude : 55.151134)
This is it!, Hope you find this information useful!