在业务需求中,需要对地理坐标进行存储,mongodb是一种很好的选择,因为它提供了许多关于地理位置的方法,但是它提供的GeoJson却是一个接口,当然也提供了对应的点、线、面的实现类,不过在业务需求中,往往需要前端传一个GeoJson数据格式,后端做一个点、线、面的适配,已达到简单使用,简单存储的功能;
基于上面的场景,写了这篇文章,下面就贴代码了(关于maven及mongdb的配置下面就不贴了,只贴核心代码)
1.首先自定义一个GeoJson类
@Data
public class CustomGeoJson implements GeoJson, Serializable {
private static final long serialVersionUID = 1;
private String type;
private Iterable<?> coordinates;
}
2.添加mongdb的convert转换器,读写用的
1)CustomReadGeoJsonConverter
@Configuration
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;
}
}
2)CustomWriteGeoJsonConverter
@Configuration
public class CustomWriteGeoJsonConverter implements Converter<CustomGeoJson, Document> {
@Override
public Document convert(CustomGeoJson geoJson) {
Document document = new Document();
document.put(GeoJsonConstant.TYPE, geoJson.getType());
document.put(GeoJsonConstant.COORDINATES, geoJson.getCoordinates());
return document;
}
}
3.geoJson数据的键名称
public final class GeoJsonConstant {
/**
* type(类型)
*/
public static final String TYPE = "type";
/**
* coordinates(坐标位置)
*/
public static final String COORDINATES = "coordinates";
}
4.geoJson的type
public final class GeoJsonTypeConstant {
/**
* 点
*/
public static final String POINT = "Point";
/**
* 线
*/
public static final String LINESTRING = "LineString";
/**
* 面
*/
public static final String POLYGON = "Polygon";
}
- 实体类
@Data
@Document(collection = "map_data")
public class MapData {
@Id
private String id;
private CustomGeoJson geometry;
}
6.Config
@Configuration
public class Config {
@Autowired
private CustomReadGeoJsonConverter customReadGeoJsonConverter;
@Autowired
private CustomWriteGeoJsonConverter customWriteGeoJsonConverter;
@Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<>();
converterList.add(customReadGeoJsonConverter);
converterList.add(customWriteGeoJsonConverter);
return new MongoCustomConversions(converterList);
}
}
7.TestController
@RestController
@Api
public class TestController {
@Autowired
private MongoTemplate mongoTemplate;
@PostMapping("test")
public MapData test(@RequestBody MapData mapData){
return mongoTemplate.insert(mapData);
}
}
8.测试效果图
swagger入参
9.mongdb 存储数据的值
以上就是GeoJson存储地理位置的实现;
有疑问或者有更好的实现方式可以讨论,本文属于原创,转载需指明出处
QQ交流群: 132312549