Fetch locations within a longitude/latitude with Node.js &mongoDB
To implement a feature that posts will be fetched based on your location on explore page at OXINION, i had to research so many things like geoJSON, how to query, indexing on MongoDB.
You need to understand what Mongo GeoJSON is.
{
"geometry": {
"type": "Point",
"coordinates": [125.6, 10.1]
}
}
Create a model schema first to save geoJson. In MongoDB, its called GeoSpatial Indexing to save spatial indexing with latitude and longitude
How to define schema
✅ A good example of location schema
❌ A bad example for MongoDB schema
Never do like these below
How to use async await location
This should be handle with async await. I should ensure that the post data should displayed once i received the latitude and longitude.
Get empty [] => Paged loaded => Display empty
if you cover with if statement, if (latitude & longitude), it will run the fetch() properly.
Extra : How to manually set location in chrome?
Now you can select any location remotely :) For example, if i select London, i can see all the posts based on London’s latlng.
Recommended to read
When a user visit, pass query (userlocation.coordinates.lat, userlocation.coordinates.lng)