Java按兩點經緯度計算距離
1.Java計算
package com.hd123.cloudscm.web.controller.mdata.warehouse;
public class Test {
// 經度
double longitude;
// 維度
double dimensionality;
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getDimensionality() {
return dimensionality;
}
public void setDimensionality(double dimensionality) {
this.dimensionality = dimensionality;
}
/*
* 計算兩點之間距離
*
* @param start
*
* @param end
*
* @return 米
*/
public static double getDistance(Test start, Test end) {
double lon1 = (Math.PI / 180) * start.longitude;
double lon2 = (Math.PI / 180) * end.longitude;
double lat1 = (Math.PI / 180) * start.dimensionality;
double lat2 = (Math.PI / 180) * end.dimensionality;
// 地球半徑
double R = 6371;
// 兩點間距離 km,如果想要米的話,結果*1000就可以了
double d = Math.acos(
Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1))
* R;
return d * 1000;
}
public static void main(String[] args) {
// 測試經緯度:116.368904, 39.923423
// 測試經緯度2:116.387271, 39.922501
Test start = new Test();
start.setLongitude(116.368904);
start.setDimensionality(40.923423);
Test end = new Test();
end.setLongitude(116.387271);
end.setDimensionality(39.922501);
System.out.println(getDistance(start, end));
}
}
這樣的演算法誤差較小,覺得可以忽略。
2.如果想要在頁面上直接計算,可以呼叫高德的API。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>兩點間距離</title>
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.2&key=您申請的key值"></script>
<script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<body>
<div id="container"></div>
<div class="button-group">
<input id="calc" type="button" class="button" value="計算兩點間距離"/>
</div>
<script type="text/javascript">
//初始化地圖物件,載入地圖
var map = new AMap.Map("container", {
resizeEnable: true,
zoom: 13
});
new AMap.Marker({
map: map,
position: [116.368904, 39.923423]
});
new AMap.Marker({
map: map,
position: [116.387271, 39.922501]
});
map.setFitView();
var lnglat = new AMap.LngLat(116.368904, 40.923423);
AMap.event.addDomListener(document.getElementById('calc'), 'click', function() {
alert('兩點間距離為:' + lnglat.distance([116.387271, 39.922501]) + '米');
});
</script>
</body>
</html>
呼叫高德的API,算出來的距離是準確的,他和百度的計算結果千米誤差為20。