mongodb地理坐标范围查询

参考地址

https://www.cnblogs.com/zhouqinxiong/p/5565107.html

线  LineString

{
            "type": "LineString",
            "coordinates": [ [1, 1],[2,1], [3,1]]
 }

{
            "type": "LineString",
            "coordinates": [ [1, 1],[2,2], [3,3]]
 }

{
            "type": "LineString",
            "coordinates": [ [1, 2],[2,3], [3,4]]
 }

  

查询相交的线

db.geolocation.find({
    "loc":{"$geoIntersects":{"$geometry":{
    "type":"LineString",
    "coordinates":[[1,2],[2,3],[3,4]]
}}} 
})

  

面 Polygon

db.polygonCol.insert({
    "name":"chengdu",
    "loc":{
        "type":"Polygon",
        "coordinates":[[[1,2],[2,3],[3,2],[1,2]]]
    }  
})

db.polygonCol.insert({
    "name":"shenzhen",
    "loc":{
        "type":"Polygon",
        "coordinates":[[[4,2],[4,4],[5,4],[5,2]]]
    }  
})

  

查询有相交的数据

db.polygonCol.find({
    "loc":{"$geoIntersects":{"$geometry":{
    "type":"Polygon",
    "coordinates":[[[1,2],[1,4],[2,4],[2,1],[1,2]]]
}}} 
})

上面的查询语句只返回了name=shenzhen的数据

db.polygonCol.find({
    "loc":{"$geoIntersects":{"$geometry":{
    "type":"Polygon",
    "coordinates":[[[2,2],[2,4],[5,1],[2,2]]]
}}} 
})
返回两条数据

  用java代码查询

import com.alibaba.fastjson.JSONObject;
import org.springframework.data.geo.Point;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPolygon;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class GEOTestService {

    @Autowired
    MongoTemplate mongoTemplate;

    public List<JSONObject> find(String jsonObject){
        Query query = new Query();
        GEOPolygon geoPolygon = JSONObject.parseObject(jsonObject, GEOPolygon.class);
        List<Point> points = new ArrayList<>();
        List<List<List<Double>>> coordinates = geoPolygon.getCoordinates();
        List<List<Double>> coordinate = coordinates.get(0);
        for (List<Double> doubles : coordinate) {
            Point point = new Point(doubles.get(0), doubles.get(1));
            points.add(point);
        }
        GeoJsonPolygon geoJsonPolygon = new GeoJsonPolygon(points);
        query.addCriteria(Criteria.where("loc").intersects(geoJsonPolygon));
        List<JSONObject> list = mongoTemplate.find(query, JSONObject.class, "polygonCol");
        return list;
    }
}
@Data
public class GEOPolygon {

    String type;

    List<List<List<Double>>> coordinates;
}

  

 

 查询参数:

{     "type":"Polygon",     "coordinates":[[[2,2],[2,4],[5,1],[2,2]]] }

 

mongodb地理坐标范围查询

上一篇:mysql8.0.18 开启远程访问


下一篇:ASP.NET中连接Sqlserver数据库时提示:未能加载文件或程序集“Microsoft.SqlServer.Management.Sdk.Sfc