原因:前端用的百度地图,数据库存的百度地图坐标,需要在后台(java)计算两点坐标的直线距离,网上的一些通用方法计算出来的和使用百度js api得到的结果不一样,无奈只有阅读源码,再用java写一遍。
先看百度js api得到的结果:
//这是百度api获取距离的方法
var range=map.getDistance(new BMap.Point(116.404, 39.915),new BMap.Point(116.399814, 39.908209));
console.log(range)
//得到的结果为 835.2724351592902 ,单位是米
然后分析源码:
//这里只列出关联的js方法
mP: 6370996.81,
getDistance: function(a, b) {
if (a && b) {
if (a.nb(b)) return 0;
var c = 0,
c = S.Xo(a, b);
if (c === p || c === j) c = 0;
return c
}
}
nb: function(a) {
return ! (a instanceof db) || this.xj() ? q: this.ve().nb(a.ve()) && this.nf().nb(a.nf())
}
Xo: function(a, b) {
if (!a || !b) return 0;
a.lng = this.OD(a.lng, -180, 180);
a.lat = this.SD(a.lat, -74, 74);
b.lng = this.OD(b.lng, -180, 180);
b.lat = this.SD(b.lat, -74, 74);
return this.Te(this.Uk(a.lng), this.Uk(b.lng), this.Uk(a.lat), this.Uk(b.lat))
}
OD: function(a, b, c) {
for (; a > c;) a -= c - b;
for (; a < b;) a += c - b;
return a
}
SD: function(a, b, c) {
b != p && (a = Math.max(a, b));
c != p && (a = Math.min(a, c));
return a
}
Te: function(a, b, c, d) {
return this.mP * Math.acos(Math.sin(c) * Math.sin(d) + Math.cos(c) * Math.cos(d) * Math.cos(b - a))
}
Uk: function(a) {
return Math.PI * a / 180
}
java代码:
public class BaiduLocationUtils {
public static Double getDistance(Point a, Point b) {
if (a!=null && b!=null) {
return XO(a, b);
}else {
return 0d;
}
}
private static Double XO(Point a, Point b) {
a.setLng(OD(a.getLng(), -180d, 180d));
a.setLat(SD(a.getLat(), -74d, 74d));
b.setLng(OD(b.getLng(), -180d, 180d));
b.setLat(SD(b.getLat(), -74d, 74d));
return Te(Uk(a.getLng()), Uk(b.getLng()), Uk(a.getLat()), Uk(b.getLat()));
}
private static Double OD(Double a, Double b, Double c) {
for (; a > c;) a -= c - b;
for (; a < b;) a += c - b;
return a;
}
private static Double SD(Double a, Double b, Double c) {
return a;
}
private static Double Te(Double a, Double b, Double c, Double d) {
return 6370996.81 * Math.acos(Math.sin(c) * Math.sin(d) + Math.cos(c) * Math.cos(d) * Math.cos(b - a));
}
private static Double Uk(Double a) {
return Math.PI * a / 180;
}
public static void main(String[] args) {
System.out.println(getDistance(new Point(116.404, 39.915),new Point(116.399814, 39.908209)));
}
}
class Point{
/**
* 经度
*/
private Double lng;
/**
* 纬度
*/
private Double lat;
public Point() {};
public Point(Double lng, Double lat) {this.lng=lng;this.lat = lat;}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
};
}
结果一致,省略了一些代码