Getting coordinates to near me using node js and mongodb - node.js

I am using Node.JS, MongoDB and express.js. I keep coordinates in my database. And I want to get the coordinates to near me. How can I do it?
I thought about converting the meridians to km. I was able to calculate at the equator, but due to the shape of the earth, the distance between the meridian was not equal everywhere. I couldn't find any other solution.
My coordinate parameter in Mongo Model:
coordinate: {
type: String,
},
Example value:
coordinate: "41.08112226606513,29.066728949546814"

{
<location field>: {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ <longitude> , <latitude> ]
},
$maxDistance: <distance in meters>,
$minDistance: <distance in meters>
}
}
}
use this above query in your query
please read this above official document

Related

List locations near by to a lat, lon point from stored lat, lon in database

I have [lat, lon] pairs of different locations stored in MongoDb. Now I want to compare a certain coordinates pair by distance like in circle of 2 km from that point and want to take results of all from database.
You should have a look at geoNear command.
Generic example is the following:
db.runCommand(
{
geoNear: "places", // Your target collection
near: { type: "Point", coordinates: [ -73.9667, 40.78 ] }, // Point coordinates
spherical: true, // 2dsphere index required for using this option
query: { yourField: "someFilterVale" }, // Additional regular filtering
maxDistance: 2000 // Maximum distance in meters/radians
}
)
minDistance is also available for querying
For this purpose you should have 2d or 2dsphere index in your collection.
Also there is a $geoNear aggregation.

Multiple near with mongoose

I have the following "query":
MySchema
.where('address1.loc').near({
center: {
type: 'Point',
coordinates: user.address1.loc
},
maxDistance: 10 * 1000
}).where('address2.loc').near({
center: {
type: 'Point',
coordinates: user.address2.loc
},
maxDistance: 10 * 1000
})
.exec(function(err, objects) {
console.log(err);
console.log(objects);
if(err) return eachCallback(err);
return eachCallback();
});
My schema has two addresses (one pickup- and one handover-address). So I have to use two "nears". But this doesn't seem to be possible:
{ [MongoError: Can't canonicalize query: BadValue Too many geoNear expressions] name: 'MongoError' }
What are my alternatives?
Update:
I talked to some guys from MongoDB. Although my use case for this is valid, this doesn't seem to be possible out-of-the-box. So I'm looking for a "workaround". If you need details about the use case, let me know.
And here is how I defined the location inside my "addresses":
...
loc: {type: [Number], index: '2dsphere'},
...
I had encountered the same issue and error message. But I cannot remember exactly how I could overcome. I hope we can overcome your issue!
If your schema definition like the following, please try to the below solution;
loc : {
'type': { type: String, default: 'Point' },
coordinates: [Number]
}
Could you check address.loc.coordinates stores as number on your collection?
Alternate way
Try to use $geoWithin operator
I think you can change your questioning clauses like the following. You should use $geoWithin and $centerSphere instead of $near and $maxDistance. You've tried to find records that have loc fields in 10.000 meters proximity. $centerSphere indicates radius, it uses legacy coordinate values (only [longitude, latitude]) and it can used with geoJSON field and 2dsphere index. And your $centerSphere definition must be 10/6371 for 10 km. (tutorial).
If you use a second operator with $near operator it occurs a problem on MongoDB side.
You cannot combine the $near operator, which requires a special geospatial index, with a query operator or command that uses a different type of special index. For example you cannot combine $near with the $text query.
var r = 10/6371;
var area1 = { center: address1.loc.coordinates, radius: r, unique: true }
var area2 = { center: address2.loc.coordinates, radius: r, unique: true }
MySchema
.where('address1.loc').
.within()
.circle(area1)
.where('address2.loc').
.within()
.circle(area2)
.exec(function(err, objects) {
console.log(err);
console.log(objects);
if(err) return eachCallback(err);
return eachCallback();
});
Hope this helps..

Mongodb geospatial query for searching lat, long within a radius

I am trying to get the results based on geospatial query of mongodb within a circle of 5 km radius of a given lat,long.
For that i am using this query
{coords :
{ $nearSphere :{
$geometry: {
type : "Point",
coordinates : [ data.longitude, data.latitude]
},
$maxDistance: 5000
}
}
}
But it is giving me undefined output. But when i remove the $maxDistance it is giving me all the results. I want to get the results only under the specified maxDistance.

Using geoJSON in mongoose schema and use it in a query

I'm new to mongoDB and the usage of geoJSON within it.
I have the following schema I created using the mongoose module:
var mongoose = require('mongoose');
var hikeSchema = mongoose.Schema({
name: String,
area: String,
length: Number,
time: String,
Difficulty: { type : Number, min : 0 , max :5 },
start_coord: {
lon: Number,
lat: Number
},
rank_count: Number,
avg_overall_rating: { type : Number, min : 0 , max :5 },
completed_count: Number,
description: String,
ranking_pages: [
mongoose.Schema.Types.ObjectId
]
});
module.exports = mongoose.model('Hike', hikeSchema);
I used a simple Number type to represent to longitude and latitude inside a sub object within the schema.
I don't know if this is the way to go about it. I want it to be saved as a geoJSON object and then run queries on this object.
I recommand you to see the mongoDB part for geolocation datas : http://docs.mongodb.org/manual/core/2d/
To store longitude, latitude, MongoDB take you the correct data structure to save items :
To store location data as legacy coordinate pairs, use an array or an embedded document.
When possible, use the array format:
loc : [ < longitude > , < latitude > ]
Consider the embedded document form:
loc : { lng : , lat : }
Arrays are preferred as certain languages do not guarantee associative map ordering.
For all points, if you use longitude and latitude, store coordinates in longitude, latitude order.
On your shema, change
start_coord: {
lon: Number,
lat: Number
},
By :
start_coord: {
lng: Number,
lat: Number
},
Then you should add a 2dindex for your field start_coords to use all mongoDB geospatial queries :
db.collection.ensureIndex( { start_coord : "2d" } , { min : <l ower bound > , max : < upper bound > } )
EDIT It's important to set min and max if your longitude and latitude is not a real lng/lat (for example if you could use 2dindexes in a orthonormal map)
Now you can use all geospatial query operators : http://docs.mongodb.org/manual/reference/operator/query-geospatial/
You can also do it this way:
start_coord: {
type: [Number], // [<longitude>, <latitude>]
index: '2d' // create the geospatial index
}
Check this tutorial: How to use geospatial indexing in mongoDb

How do I perform a find using $geoIntersects / 2dsphere in an array subfield?

I have a collection with documents and each has a field array with polygons.
I want to test if my polygon geoIntersects any of those polygons. They are all box-shaped if it helps.
I will add bounty points if you add in the possibility of having my polygon in that array I'm testing. I wouldn't want it intersect with itself...
Cities:
{_id, buildings:[ {coo:{shape:"Polygon", coordinates:[ [0,0], [4,0], [4,5], [5,0],[0,0] ] }, {coo:{shape:"Polygon", coordinates:[ [0,0], [4,0], [4,5], [5,0],[0,0] ] } ] }}
Imagine I have around 100 or so elements in the array.
I want to determine if, for a given shape, that might be included inside the array, if it intersects any or none of the other polygons (again, excluding itself it is in there).
This page will help you make the geospatial index on your compound spatial documents:
http://docs.mongodb.org/manual/core/geospatial-indexes/
And then you can use this page to figure out your query
http://docs.mongodb.org/manual/reference/operator/box/#op._S_box
try this :
<collection>.findOne({ 'polygons': { $geoIntersects: { $geometry: { type: "Point", coordinates: [Longitude, Latitude] } } } }

Resources