我們在 mongodb 篇中介紹瞭如何使用 mongodb 進行地圖的距離排序和篩選,今天我們來介紹一下,用 Java 和 SpringData 來實現的時候,需要注意的一些知識點。
首先,我們需要爲實體設置地圖索引。在 SpringData 中,我們可以通過使用 @GeoSpatialIndexed 註解來設置索引。但是這個索引註解默認使用的是2d索引,我們希望使用 2dsphere 索引,因此我們需要將重新設置這個註解的 type(type= GeoSpatialIndexType.GEO_2DSPHERE)。姿勢如下:
@Document(collection = "location")
public class Location {
@Field(value = "lng")
private double lng;
@Field(value = "lat")
private double lat;
@Field(value = "location")
@GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
private double[] location;
}
在設置好索引之後,我們就可以愉快的開始距離的排序了,第一種方式默認按照由近到遠排序。姿勢如下:
public List<Location> getNearLocation(double lng, double lat) {
Query query = new Query();
Point point = new Point(lng, lat);
Criteria locCri = Criteria.where("location").nearSphere(point);
query.addCriteria(locCri);
return mongoAccess.find(query, Location.class);
}
除了上面這種方式,按照離我最近,還可以使用 Aggregate 來實現。姿勢如下:
public List<Location> getNearLocation(double lng, double lat) {
Point point = new Point(lng, lat);
Sort disSort = new Sort(Sort.Direction.ASC, "distance");
List<AggregationOperation> aggregationOperations = new ArrayList<>();
aggregationOperations.add(Aggregation.geoNear(NearQuery.near(point).inKilometers().spherical(true), "distance"));
aggregationOperations.add(Aggregation.sort(disSort));
Aggregation aggregation = Aggregation.newAggregation(aggregationOperations);
AggregationResults<Location> results = this.mongoAccess.aggregate(aggregation, Location.class, Location.class);
return results.getMappedResults();
}
如果我們希望查詢以某個點爲中心的圓幾公里以內的位置數據,那你的姿勢可以如下:
public List<Location> getCircleLocation(double lng, double lat, double radius) {
//獲取半徑內的所有位置
Point point = new Point(lng, lat);
Distance distance = new Distance(radius, Metrics.KILOMETERS);
Circle circle = new Circle(point, distance);
Criteria locCri = Criteria.where("location").withinSphere(circle);
Query query = new Query();
query.addCriteria(locCri);
return mongoAccess.find(query, Location.class);
}
注:代碼中的 mongoAccess 爲 mongodb 的基本操作封裝,大家替換爲自己的實現即可。