方式一:PHP
/**
*求两个已知经纬度之间的距离,单位为千米(测试)
*@param lng1,lng2 经度
*@param lat1,lat2 纬度
*@return float 距离,单位千米
**/
public function getDistance($lng1, $lat1, $lng2, $lat2)
{
方法一:
// $earthRadius = 6367000; //approximate radius of earth in meters
// $lat1 = ($lat1 * pi()) / 180;
// $lng1 = ($lng1 * pi()) / 180;
// $lat2 = ($lat2 * pi()) / 180;
// $lng2 = ($lng2 * pi()) / 180;
// $calcLongitude = $lng2 - $lng1;
// $calcLatitude = $lat2 - $lat1;
// $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
// $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
// $calculatedDistance = $earthRadius * $stepTwo;
// if ($calculatedDistance < 1000) return $calculatedDistance . '米';
// if ($calculatedDistance >= 1000) return $calculatedDistance / 1000 . '公里';
// return round($calculatedDistance); // 0.34092299665475米
方法二:
$EARTH_RADIUS = 6378.137;
$radLat1 = $this->rad($lat1);
$radLat2 = $this->rad($lat2);
$a = $radLat1 - $radLat2;
$b = $this->rad($lng1) - $this->rad($lng2);
$s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
$s = $s * $EARTH_RADIUS * 1000;
if ($s < 1000) return round($s, 2) . '米';
if ($s >= 1000) return round($s / 1000, 2) . '公里';
}
private function rad($d)
{
return $d * M_PI / 180.0;
}
方式二:SQL
$arr = Db::select('SELECT *, (2 * 6378.137 * ASIN(SQRT(POW(SIN(PI() * (' . $lng . ' - longitude) / 360),2) + COS(PI() * 39.916527 / 180) * COS(latitude * PI() / 180) * POW(SIN(PI() * (' . $lat . ' - latitude) / 360),
2)))) AS distance FROM f_dining WHERE dining_status = 1 AND is_delete = 1 ORDER BY distance ASC');
$res = json_decode(json_encode($arr), true);
if ($res) {
foreach ($res as &$v) {
if ($v['distance'] < 1) {
$v['distance'] = round($v['distance'] * 1000) . '米';
} else {
$v['distance'] = round($v['distance']) . '公里';
}
}
}