js实现方法, 从微信小程序官方SDK中分离出来的
var EARTH_RADIUS = 6378136.49;
/**
* 计算角度
*/
function rad(d) {
return d * Math.PI / 180.0;
}
/**
* 计算两点间直线距离
* @param a 表示纬度差
* @param b 表示经度差
* @return 返回的是距离,单位m
*/
function getDistance(latFrom, lngFrom, latTo, lngTo) {
var radLatFrom = rad(latFrom);
var radLatTo = rad(latTo);
var a = radLatFrom - radLatTo;
var b = rad(lngFrom) - rad(lngTo);
var distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLatFrom) * Math.cos(radLatTo) * Math.pow(Math.sin(b / 2), 2)));
distance = distance * EARTH_RADIUS;
distance = Math.round(distance * 10000) / 10000;
return parseFloat(distance.toFixed(0));
}
php实现方法
/**
* 计算两点之间的距离
* @param $lng1 经度1
* @param $lat1 纬度1
* @param $lng2 经度2
* @param $lat2 纬度2
* @param bool $unit 单位
* @param int $decimal 位数
* @return float
*/
function getDistance($lng1, $lat1, $lng2, $lat2, $unit = true, $decimal = 2)
{
$EARTH_RADIUS = 6378136.49; // 地球半径系数
$PI = M_PI;
$radLat1 = $lat1 * $PI / 180.0;
$radLat2 = $lat2 * $PI / 180.0;
$radLng1 = $lng1 * $PI / 180.0;
$radLng2 = $lng2 * $PI / 180.0;
$a = $radLat1 - $radLat2;
$b = $radLng1 - $radLng2;
$distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
$distance = $distance * $EARTH_RADIUS;
if($unit) {
if($distance >= 1000) {
$distance /= 1000;
$distance = round($distance, $decimal);
$distance .= 'km';
}else{
$distance = intval($distance);
$distance .= 'm';
}
}else{
$distance = round($distance, $decimal);
}
return $distance;
}