MongoDB LBS经纬度查询操作

今天需要对mongodb中的数据进行处理的时候发现有很多经纬度数据需要按照一定的范围进行分类,正好看到mongodb有一个对LBS进行处理的功能,特此进行填坑操作~!

初始化数据

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

MongoDB LBS经纬度查询操作_第1张图片

  • mongodb中经纬度数据格式是这样的(经纬度字段的定义是以百度地图的格式为准),注意存储的时候要用Double类型:

在这里插入图片描述

  • 再附上获取经纬度的网站:获取经纬度网站

LBS - $geoWithin指定形状查询

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

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

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

矩形左上起点是西直门地铁经纬度坐标,右下终点是大望路地铁站经纬度。
MongoDB LBS经纬度查询操作_第2张图片

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 LBS经纬度查询操作_第3张图片

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方法代码如下,一看便知:

MongoDB LBS经纬度查询操作_第4张图片

LBS - $near接近点查询

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

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

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

MongoDB LBS经纬度查询操作_第5张图片

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()) + ",");
});

你可能感兴趣的:(填坑之旅,MongoDB,LBS,经纬度)