標籤:sys 半徑 圖計算 math i++ 16.4 earth oid git
在實際地圖項目中會碰見距離的計算,這裡寫出來,以後參考:
/**
* @author 作者 :zhaoliang
* @version : v1.0
*建立時間:2018年6月26日 下午3:32:30
* 類說明 :根據經緯度計算距離
*/
public class DistanceUtil {
private static double EARTH_RADIUS = 6378.137; //地球半徑
/**
* Google地圖計算兩個座標點的距離
* @param latitude 頁面傳遞過來的經度
* @param longitude 頁面傳遞過來的緯度
* @param gaode_lng 資料庫中停車場的經度
* @param gaode_lat 資料庫中停車場的緯度
* @return 距離(千米)
*/
public static double getDistance(double latitude, double longitude, double gaodeLng, double gaodeLat) {
double radLat1 = Math.toRadians(longitude);
double radLat2 = Math.toRadians(gaodeLat);
double a = radLat1 - radLat2;
double b = Math.toRadians(latitude) - Math.toRadians(gaodeLng);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
s = s * EARTH_RADIUS;
s = Math.round(s * 10000) / 10000;
return s;
}
public static void main(String[] args) {
long b = System.currentTimeMillis();
for(int i=0; i<1000000; i++){
getDistance(116.403933,39.914147, 116.403237,39.927919);
}
System.out.println("耗時:"+(System.currentTimeMillis()-b)+"毫秒"); //耗時:461毫秒
double dist = getDistance(116.403933,39.914147, 116.403237,39.927919);
System.out.println("兩點相距:" + dist + "千米"); //兩點相距:1.0千米
}
}
java根據經緯度計算距離