Skip to content

Instantly share code, notes, and snippets.

@neekey
Created May 22, 2012 15:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save neekey/2769656 to your computer and use it in GitHub Desktop.
Save neekey/2769656 to your computer and use it in GitHub Desktop.
Mongoose 地理位置搜索 代码示例
/**
* 商品种类
*/
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 ] } ]
*/
});
@zj8487
Copy link

zj8487 commented Jul 21, 2014

why do not you use LocationModel.geonear or LocationModel.seach?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment