mongodb实现lbs地理位置查找附近的商家

时间:2021-03-24 10:54:59
本文借鉴 http://blog.csdn.net/fdipzone/article/details/46285521



Java 代码
//查询地理位置的条件
List<JSONObject> listJson=new ArrayList<>();
Double lng = 113.323568d; //经度
Double lat = 23.146436d; //纬度
Integer radius =1000;//范围
Position pt = new Position(lng,lat);
Point po = new Point(pt);
Filters.nearSphere("loc",po,radius.doubleValue(),0.00);
MongoCursor<Document> list=MongoDBUtil.find(db, Filters.nearSphere("loc",po ,radius.doubleValue(),0.00));
while(list.hasNext()){
Document d=list.next();
listJson.add(JSON.parseObject(diyObjectIdToJson(d)));
}
System.out.println(listJson.toString());
 1.创建lbs集合存放地点坐标

b.lbs.insert(
{
loc:{
type: "Point",
coordinates: [113.332264, 23.156206]
},
name: "广州东站"
}


db.lbs.insert(
{
loc:{
type: "Point",
coordinates: [113.330611, 23.147234]
},
name: "林和西"
}
)

db.lbs.insert(
{
loc:{
type: "Point",
coordinates: [113.328095, 23.165376]
},
name: "天平架"
}
)

2.创建地理位置索引

db.lbs.ensureIndex(
{
loc: "2dsphere"
}
)

3.查询附近的坐标
当前位置为:时代广场,
坐标:113.323568, 23.146436

搜寻附近一公里内的点,由近到远排序

db.lbs.find(
{
loc: {
$near:{
$geometry:{
type: "Point",
coordinates: [113.323568, 23.146436]
},
$maxDistance: 1000
}
}
}
)