因为有压力
喷泉才会比水更美丽

MongoDB LBS经纬度查询操作

获取经纬度网站

初始化数据

首先我需要初始化数据,如图是一些北京公司地点坐标:

monggodb数据格式:

LBS – $geoWithin指定形状查询

  • 创建地理空间索引(2D索引)
db.collection_name.ensureIndex({"location" : "2d"});

在指定形状查询中,$box$polygon$center分别表示按矩形、五边形、圆形进行查询。

  • $box查询矩形区域坐标点:

矩形左上起点是西直门地铁经纬度坐标,右下终点是大望路地铁站经纬度。

mongodb语句如下:

db.company.find({ 
    "location" : { 
        "$geoWithin" : {
        "$box":[[116.362078,39.945976],[116.482451,39.914176]]
        }
    }
})

对应java dao代码如下:

//        矩形
double[] box1 = {116.362078,39.945976};
double[] box2 = {116.482451,39.914176};
Box shape = new Box(box1, box2);
Criteria criteria = Criteria.where("location")
        .within(shape);

List<com.qnloft.web.model.baidu.Result> mongoResults =
        mongoTemplate.find(query(criteria),
                com.qnloft.web.model.baidu.Result.class,
                "company");
  • $center查询圆形区域坐标点:

圆心坐标点是大望路地铁站经纬度,半径为0.05

mongodb语句如下:

db.company.find({
    "location" : { 
        "$geoWithin" : {
          "$center":[[116.482451,39.914176],0.05]
        }
    }
})

对应java dao代码如下:

double radius = 0.05;
Circle circle = new Circle(new Point(116.482451,39.914176), radius);
Criteria criteria = Criteria.where("location")
        .within(circle);
List<com.qnloft.web.model.baidu.Result> mongoResults =
        mongoTemplate.find(query(criteria),
                com.qnloft.web.model.baidu.Result.class,
                "company");

我怎么知道这里Criteria需要传入哪些类呢?org.springframework.data.mongodb.core.query.GeoCommandgetCommand方法代码如下,一看便知:

LBS – $near接近点查询

这个功能相当于微信附近的人功能。这里为什么不适用2d索引?因为2d索引不能使用经纬度查询,需要传入弧度

  • 创建地理空间索引(2dsphere索引)
db.company.ensureIndex({"location" : "2dsphere"});

望京东地铁站经纬度为圆心,查询附近1000米以内公司坐标

MongoDB语句如下:

db.company.find({
   "location": {
     "$near": {
       "$geometry": {
          type: "Point" ,
          coordinates: [116.493231,40.009379]
       },
       "$maxDistance": 1000
     }
   }
})

对应java dao代码如下:

List<Double> coordinates = new ArrayList<>();
coordinates.add(116.493231);
coordinates.add(40.009379);
Bson nearBson = Filters.near("location" ,new Point(new Position(coordinates)),1000.0,0.0);

List<com.qnloft.web.model.baidu.Result> list = new ArrayList<>();
mongoTemplate.getCollection("company").find(nearBson).forEach((Block<Document>) document -> {
    // 将结果转换成bean
    com.qnloft.web.model.baidu.Result geoResult = JSON.parseObject(document.toJson(), com.qnloft.web.model.baidu.Result.class);
    System.out.println(JSON.toJSONString(geoResult.getLocation()) + ",");
});
 收藏 (0) 打赏

您可以选择一种方式赞助本站

支付宝扫一扫赞助

微信钱包扫描赞助

未经允许不得转载:R&M » MongoDB LBS经纬度查询操作

分享到: 生成海报
avatar

壮士,请留下你的言论 抢沙发