以下是使用spatial4j来通过经纬度过滤数据的基础代码,相对比较简单,如果数据量不是特别大,使用这种方式还是比较方便的。
引入依赖包
<dependency>
<groupId>org.locationtech.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>0.8</version>
</dependency>
计算矩形的四角经纬度:
private SpatialContext spatialContext = SpatialContext.GEO;
/**
* @param distance 距离范围 单位km
* @param longitude 经度
* @param latitude 维度
* @return
*/
private Rectangle getRectangle(double distance, Double longitude, Double latitude) {
Point point = new PointImpl(longitude, latitude, spatialContext);
return spatialContext.getDistCalc().calcBoxByDistFromPt(point,
distance * DistanceUtils.KM_TO_DEG, spatialContext, null);
}
过滤数据的SQL
SELECT
longitude,
latitude
FROM
RES_SITE
WHERE
longitude BETWEEN #{minLng} AND #{maxLng}
AND latitude BETWEEN #{minLat} AND #{maxLat}
执行数据的过滤:
//1.获取外接正方形
Rectangle rectangle = getRectangle(distance, longitude, latitude);
log.info("minLng:{},maxLng:{},minLat:{},maxLat:{}",rectangle.getMinX(),rectangle.getMaxX()
,rectangle.getMinY(),rectangle.getMaxY());
//2.传入参数执行SQL语句 TODO