根据坐标点经纬度计算两点间距离。(单位:km)
- python
import math
def cal_dis(lat1, lon1,lat2, lon2):
lat1 = (math.pi/180)*lat1
lat2 = (math.pi/180)*lat2
lon1 = (math.pi/180)*lon1
lon2= (math.pi/180)*lon2
#因此AB两点的球面距离为:{arccos[sinb*siny+cosb*cosy*cos(a-x)]}*R
#地球半径
R = 6378.137;
d = math.acos(math.sin(latitude1)*math.sin(latitude2)+ math.cos(latitude1)*math.cos(latitude2)*math.cos(longitude2-longitude1))*R
return d
if __name__ == '__main__':
print cal_dis(40.00694,116.394476,40.007538,116.375561)
- java
public static void main(String[] args) {
System.out.println(getDistance(40.00694,116.394476,40.007538,116.375561));
}
//根据经纬度计算两点距离
public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
double radLat1 = lat1 * Math.PI / 180.0;
double radLat2 = lat2 * Math.PI / 180.0;
double lng_1 = lng1 * Math.PI / 180.0;
double lng_2 = lng2 * Math.PI / 180.0;
double a = radLat1 - radLat2;// 两点纬度差
double b = lng_1 - lng_2;// 两点的经度差
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 * 6378.137;
return s;
}
- scala
def main(args: Array[String]): Unit = {
val aa :Double = getDistatce(40.00694,116.394476,40.007538,116.375561)
}
//根据经纬度计算两点距离
def getDistatce(lat1: Double, lon1: Double, lat2: Double, lon2: Double) = {
if (lat1 != 0 && lon1 != 0 && lat2 != 0 && lon2 != 0) {
val R = 6378.137
val radLat1 = lat1 * Math.PI / 180
val radLat2 = lat2 * Math.PI / 180
val a = radLat1 - radLat2
val b = lon1 * Math.PI / 180 - lon2 * Math.PI / 180
val s = 2 * Math.sin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
BigDecimal.decimal(s * R).setScale(2, BigDecimal.RoundingMode.HALF_UP).doubleValue()
} else {
BigDecimal.decimal(0).setScale(2, BigDecimal.RoundingMode.HALF_UP).doubleValue()
}
}