Mark a field to be indexed using MongoDB's geospatial indexing feature.
开始没有加这个注解, 然后计算距离的时候就会报错
1, 准备测试数据:
/** * save
*/ @Test
public void test1() {for (int x = 100; x < 131; x++) {for (int y = 30; y < 61; y++) { Double loca[]
= new Double[]{Double.valueOf(x), Double.valueOf(y)}; ChargePoi chargePoi
= new ChargePoi(); chargePoi.setPoi_id(
"poiid" + x); chargePoi.setMedia_url(
"http://www.baidu.com?params=" + x); chargePoi.setPoi_name(
"vini" + Arrays.toString(loca)); chargePoi.setPrice(Math.random()
* 100); chargePoi.setLocation(loca);
mongoTemplate.insert(chargePoi);
}
}
}
2, 圆形查询
/** * circle
*/ @Test
public void test2() { Circle circle
= new Circle(30, 20, 20); List
<ChargePoi> find = mongoTemplate.find(new Query(Criteria.where("location").within(circle)), ChargePoi.class); System.
out.println(find); System.
out.println(find.size()); }
3, 球星查询
/** * spherical
*/ @Test
public void test3() { Circle circle
= new Circle(30,20, 20); List
<ChargePoi> find = mongoTemplate.find(new Query(Criteria.where("location").withinSphere(circle)), ChargePoi.class); System.
out.println(find.size()); System.
out.println(find); }
4, 矩形查询, box
/** * box
*/ @Test
public void test4() { Box box
= new Box(new Point(10, 11), new Point(10, 20)); List
<ChargePoi> find = mongoTemplate.find(
new Query(Criteria.where("location").within(box)), ChargePoi.class); System.
out.println(find.size()); System.
out.println(find); }
5, 按距离由近到元查询
/** * near
*/ @Test
public void test5() { Point point
= new Point(12, 12); List
<ChargePoi> venues = mongoTemplate.find(
new Query(Criteria.where("location").near(point).maxDistance(20)), ChargePoi.class); System.
out.println(venues.size()); System.
out.println(venues); }
6, 空间距离查询
/** * nearSphere
*/ @Test
public void test6() { Point point
= new Point(12, 12); List
<ChargePoi> venues = mongoTemplate.find(
new Query(Criteria.where("location").nearSphere(point).maxDistance(20)), ChargePoi.class); System.
out.println(venues.size()); System.
out.println(venues); }
7, 最近点查询
@Testpublic void test7() { Point location
= new Point(12, 12); NearQuery query
= NearQuery.near(location).maxDistance(new Distance(100000, Metrics.KILOMETERS)); GeoResults
<ChargePoi> result = mongoTemplate.geoNear(query, ChargePoi.class); System.
out.println(result); }