查询附近
@Test
public void testNear() {
//构造坐标点
GeoJsonPoint point = new GeoJsonPoint(116.404, 39.915);
//构造半径
Distance distanceObj = new Distance(1, Metrics.KILOMETERS);
//画了一个圆圈
Circle circle = new Circle(point, distanceObj);
//构造query对象
Query query = Query.query(Criteria.where("location").withinSphere(circle));
List<Places> list = mongoTemplate.find(query, Places.class);
list.forEach(System.out::println);
}
查询并获取距离
我们假设需要以当前坐标为原点,查询附近指定范围内的餐厅,并直接显示距离
//查询附近且获取间距
@Test
public void testNear1() {
//1、构造中心点(圆点)
GeoJsonPoint point = new GeoJsonPoint(116.404, 39.915);
//2、构建NearQuery对象
NearQuery query = NearQuery.near(point, Metrics.KILOMETERS).maxDistance(1, Metrics.KILOMETERS);
//3、调用mongoTemplate的geoNear方法查询
GeoResults<Places> results = mongoTemplate.geoNear(query, Places.class);
//4、解析GeoResult对象,获取距离和数据
for (GeoResult<Places> result : results) {
Places places = result.getContent();
double value = result.getDistance().getValue();
System.out.println(places+"---距离:"+value + "km");
}
}