天天看點

使用spatial4j來過濾資料

以下是使用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 
      

繼續閱讀