Skip to content

Instantly share code, notes, and snippets.

@zj8487
Forked from neekey/mongooseGeoSerach.js
Created July 19, 2014 08:10
Show Gist options
  • Save zj8487/f0c055344759b791d6d6 to your computer and use it in GitHub Desktop.
Save zj8487/f0c055344759b791d6d6 to your computer and use it in GitHub Desktop.
/**
* 商品种类
*/
var Location = new schema({
// 地点位置
name: { type: String, required: true },
// 位置GPS坐标
location: { type: Array, index: "2d" }
});
mongoose.model( 'location', Location );
var LocationModel = mongoose.model( 'location' );
// 地球半径
var earthRadius = 6378; // km
// 计算距离在地球表面对应的弧度
// mongoDB中的maxDistance需要使用弧度
function getDistance( km ){
return km / earthRadius;
}
var TestData = [
{
name: '浙江工业大学', // 0
location: [ 120.02992629999994, 30.2244392 ]
},
{
name: '纽约', // 17687
location: [ -74.0059731, 40.7143528 ]
},
{
name: '浙江省温州', // 327
location: [ 120.68499999999995, 27.98 ]
},
{
name: '杭州鼓荡', // 12.2
location: [ 120.12440500000002, 30.275874 ]
},
{
name: '浙江省中医院下沙院区', // 40.4
location: [ 120.35459270000001, 30.3041019 ]
},
{
name: '阿里巴巴总部', // 15
location: [ 120.18971299999998, 30.18886 ]
}
];
LocationModel.find( { location: { $nearSphere: TestData[ 0 ].location, $maxDistance: getDistance( 16 ) } }, function ( err, results ){
console.log( results );
/* 结果:按照距离的近远排序
[ { name: '浙江工业大学',
_id: 4fbba76fd98934819a000001,
location: [ 120.02992629999994, 30.2244392 ] },
{ name: '杭州鼓荡',
_id: 4fbba76fd98934819a000004,
location: [ 120.12440500000002, 30.275874 ] },
{ name: '阿里巴巴总部',
_id: 4fbba76fd98934819a000006,
location: [ 120.18971299999998, 30.18886 ] } ]
*/
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment