2

我试图找到附近的地方。下面的代码工作正常。但是我无法从给定的纬度,经度获得实际的位置距离。

Criteria criteria = new Criteria("coordinates")
    .near(new Point(searchRequest.getLat(),searchRequest.getLng()));

Query query = new Query();
query.addCriteria(criteria);
query.addCriteria(criteriaName);
query.limit(5);
List<Place> ls = (List<Place>) mongoTemplate.find(query, Place.class);
4

2 回答 2

3

您可以使用geoNear 聚合来做到这一点。在 spring-data-mongodb GeoNearOperation中表示此聚合。

扩展或创建Place具有您希望获得距离信息的字段的继承类(继承示例):

public class PlaceWithDistance extends Place {
    private double distance;

    public double getDistance() {
        return distance;
    }

    public void setDistance(final double distance) {
        this.distance = distance;
    }
}

而不是Criteria使用Query聚合。的第二个参数geoNear是应设置距离的字段名称:

final NearQuery nearQuery = NearQuery
    .near(new Point(searchRequest.getLat(), searchRequest.getLng()));
nearQuery.num(5);
nearQuery.spherical(true); // if using 2dsphere index, otherwise delete or set false

// "distance" argument is name of field for distance
final Aggregation a = newAggregation(geoNear(nearQuery, "distance"));

final AggregationResults<PlaceWithDistance> results = 
    mongoTemplate.aggregate(a, Place.class, PlaceWithDistance.class);

// results.forEach(System.out::println);
List<PlaceWithDistance> ls = results.getMappedResults();

只是为了让它更容易 - 相关的进口:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.geoNear;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;

import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GeoNearOperation;
import org.springframework.data.mongodb.core.query.NearQuery;
于 2015-09-27T02:11:31.560 回答
1

Walery Strauch 的例子对我很有用......

但是我想:

  • 运行聚合查询以获取以公里或米为单位的给定距离内的 2dsphere 索引中的所有点。您可以使用 Metrics.KILOMETERS & Metrics.MILES
  • 集合名称未指定为 pojo 的一部分

我有 2dsphere 索引,在 MongoDB 中有旧的表示方式。我使用 Mongo 作为地理空间查询的分片数据库。我的 nearSphere 查询(没有聚合)只有在我有 2dsphere 索引的同一个集合中添加了一个分片键时才会失败。

在同一集合中使用以下实现与分片键后。我成功地获取了所需的数据。

这是示例:

import org.springframework.data.geo.Metrics;


final NearQuery query = NearQuery.near(new Point(longitude, latitude), Metrics.KILOMETERS)
        .num(limit)
        .minDistance(distanceInKiloMeters)
        .maxDistance(maxNearByUEDistanceInKiloMeters)
        .spherical(true);

final Aggregation a = newAggregation(geoNear(query, "distance"));

final AggregationResults<PlaceWithDistance> results = offlineMongoTemplate.aggregate(a, "myCollectionName", PlaceWithDistance.class);

final List<PlaceWithDistance> measurements = new ArrayList<PlaceWithDistance>(results.getMappedResults());
于 2016-09-01T17:12:31.460 回答