好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

springboot + mongodb 通过经纬度坐标匹配平面区域的方法

java api 自带的mongodb实体无法满足环状多边形的区域匹配(大概是我没用对方法可能)所以我们要自定义一个空间坐标类型

废话不多说 上代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

/**

  *

  * @author cy

  */

@Configuration

@ReadingConverter

public class CustomReadGeoJsonConverter implements Converter<Document, CustomGeoJson> {

 

     @Override

     public CustomGeoJson convert(Document document) {

         CustomGeoJson geoJson = new CustomGeoJson();

         geoJson.setType(document.get(GeoJsonConstant.TYPE, String. class ));

         geoJson.setCoordinates(document.get(GeoJsonConstant.COORDINATES, Iterable. class ));

         return geoJson;

     }

 

}

?

1

2

3

4

5

6

7

8

9

10

11

@Configuration

public class Config {

     @Autowired

     private CustomReadGeoJsonConverter customReadGeoJsonConverter;

     @Bean

     public MongoCustomConversions customConversions() {

         List<Converter<?, ?>> converterList = new ArrayList<>();

         converterList.add(customReadGeoJsonConverter);

         return new MongoCustomConversions(converterList);

     }

}

自定义的空间坐标类型插入实体
其中的coordinates 可自定义插入point

?

1

2

3

4

5

6

7

8

9

10

/**

  * @author cy

  */

@Data

public class CustomGeoJson implements GeoJson, Serializable {

     private String type;

 

     private Iterable<?> coordinates;

 

}

在我们定义的mongodb实体中加入我们自定义的类型

?

1

2

3

4

5

6

7

8

9

10

11

12

13

/**

  * @author cy

  * @since 2021-10-20

  */

@Data

@Document (collection = "demo_mdb" )

public class DemoMdb implements Serializable {

 

     private String id;

 

     @GeoSpatialIndexed (type = GeoSpatialIndexType.GEO_2DSPHERE)

     private CustomGeoJson customGeoJson;

}

插入数据

?

1

2

3

4

5

6

7

8

9

10

public void saveData() {

     //这里自定义point点集合(这里不固定格式参照mongdb官方文档)

     List<List<Point>> pointList = new ArrayList<>();

     DemoMdb db= new DemoMdb();

     //自行查看需要的类型

     db.setType( "***" );

     db.setCoordinates(pointList);

     //mongoTemplate自行引入不做赘述

     mongoTemplate.insert(db, DemoMdb . class );

}

查询数据

?

1

2

3

4

5

6

7

8

9

/**

  ** 经度x纬度y

  **/

public List<DemoMdb> findData(String x, String y) {

         Query query = new Query(Criteria.where( "customGeoJson" ).

         intersects( new GeoJsonPoint(Double.valueOf(x), Double.valueOf(y))));

         List<DemoMdb> dbList = mongoTemplate.find(query, DemoMdb. class );

         return dbList;

}

只是一种方法,还不完美欢迎评论指教

到此这篇关于springboot + mongodb 通过经纬度坐标匹配平面区域的方法的文章就介绍到这了,更多相关springboot mongodb 经纬度内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_43947404/article/details/121024360

查看更多关于springboot + mongodb 通过经纬度坐标匹配平面区域的方法的详细内容...

  阅读:25次