Mongodb官网参考地址:https://docs.mongodb.com/manual/core/geospatial-indexes/#calculation-of-geohash-values-for-2d-indexes
1.配置Spring 和mongodb的集成环境 mongodb-config.xml MongoTemplate
2.新建车辆位置类,用于序列化映射到mongodb,这里的id字段对应mongodb中主键,用于定位修改和删除数据
public class CarPosition {
private String id;
private double lng;//经度
private double lat;//纬度
private double[] locs = new double[2];//经纬度
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.locs[0] = lng;
this.lng = lng;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.locs[1] = lat;
this.lat = lat;
}
public double[] getLocs() {
return locs;
}
public void setLocs(double[] locs) {
this.locs = locs;
}
}
@Autowired
private MongoTemplate mongoTemplate;
public void savePosition(CarPosition carPosition) {
mongoTemplate.save(carPosition);
}
public List getPosition(CarPosition carPosition) {
//double x = 110, y = 38;
double x = carPosition.getLng(), y = carPosition.getLat();
Point point = new Point(x, y);
//6.2137119 / 3963.2为10公里范围,6.2137119是英里=10公里
Sphere sphere = new Sphere(point, 6.2137119 / 3963.2);
List positions = mongoTemplate.find(new Query(Criteria.where("locs").within(sphere)), CarPosition.class);
return positions ;
}
sql示例:
db..find( { locs : { $geoWithin :
{ $centerSphere :
[ [ 88 , 30 ] , 10 / 3963.2 ]
} } } )
计算距离需先给定单位,然后设置距离
http://blog.csdn.net/forandever/article/details/44751801