@Column(columnDefinition ="point")private Point location;//位置地理信息
2.3、GeoJSONUtil工具类
publicclassGeoJSONUtil{Point类型转geoJSON格式字符串publicstatic String getGeoJSON(Point geometry){if(geometry==null){return null;}
StringWriter writer =newStringWriter();
GeometryJSON g =newGeometryJSON();try{
g.write(geometry, writer);}catch(IOException e){
e.printStackTrace();}
String json = writer.toString();if("null".equals(json)){
json = null;}return json;}//geoJSON格式字符串转Point类型publicstatic Point getGeometryFromGeoJSON(String geoJSON){if(StringUtils.isEmpty(geoJSON)){return null;}
GeometryJSON g =newGeometryJSON();
Point geometry =null ;try{
geometry=(Point)g.read(geoJSON);}catch(IOException e){// TODO Auto-generated catch block
e.printStackTrace();}return geometry;}//数据库AsText查询出来的wkt格式的字符串转为geoJSON返回到前端publicstatic String getGeoJSONFromWKT(String geoWkt){if(StringUtils.isEmpty(geoWkt)){return null;}
WKTReader reader =newWKTReader();
String ret = null;try{
Geometry geometry = reader.read(geoWkt);
StringWriter writer =newStringWriter();
GeometryJSON g =newGeometryJSON();
g.write(geometry, writer);
ret = writer.toString();}catch(Exception e){
e.printStackTrace();}return ret;}}
2.4原生sql根据位置查询排序
public List<Map>findBuildingByLocation(String locationPointStr, String buildingName){
StringBuilder sql=newStringBuilder();
sql.append(" select b.*,AsText(b.location) as locationText,ST_DISTANCE_SPHERE(b.location,:location) as distance from buildings b where b.del_flag=0 ");if(StringUtils.isNotEmpty(buildingName)){
sql.append(" and b.building_name like :building_name ");}
sql.append(" order by distance");
Query query = entityManager.createNativeQuery(sql.toString());
query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
query.setParameter("location",GeoJSONUtil.getGeometryFromGeoJSON(locationPoint));
query.setFirstResult(0);
query.setMaxResults(10);if(StringUtils.isNotEmpty(buildingName)){
query.setParameter("building_name","%"+buildingName+"%");}
List<Map> mapList=query.getResultList();return mapList;}