Created
January 25, 2019 19:29
-
-
Save hamg26/0ef9e8c98598db70e5d803dbdbcc365a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//example data | |
db.venues.insert( { | |
name: "Central Park", | |
location: { type: "Point", coordinates: [ -73.97, 40.77 ] }, | |
category: "Parks" | |
} ); | |
db.venues.insert( { | |
name: "Sara D. Roosevelt Park", | |
location: { type: "Point", coordinates: [ -73.9928, 40.7193 ] }, | |
category: "Parks" | |
} ); | |
db.venues.insert( { | |
name: "Polo Grounds", | |
location: { type: "Point", coordinates: [ -73.9375, 40.8303 ] }, | |
category: "Stadiums" | |
} ); | |
//using a 2dsphere index | |
db.venues.createIndex( { location: "2dsphere" } ) | |
// method as promise to find an array of venues | |
// near a `point {long, lat}` | |
// within certain `radius` in the specified `unit` | |
// with 'km' as the default unit | |
findNearVenuesWithinRadius(point, radius, unit = 'km') { | |
const earthRadius = { | |
km: 6378.1, // Kilometers | |
mi: 3963.2, // Miles | |
}; | |
const query = { | |
location: { | |
$geoWithin: { | |
$centerSphere: [ [ point.long, point.lat ], radius / earthRadius[unit] ] ] | |
} | |
} | |
}; | |
// the `toArray` method returns a Promise when Callback is not provided | |
return db.venues.find(query).toArray(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment