经度和纬度的距​​离计算有不同的结果

时间:2013-08-27 07:12:09

标签: php mysql google-maps gps latitude-longitude

我试图获得两个位置的距离,我真的需要用mySQL完成,因为我必须过滤大量的记录。不幸的是,mysql语句结果与谷歌地图结果不同。可能是什么原因。

我的Mysql语句是(值硬编码)

SELECT ((ACOS(SIN(6.914556 * PI() / 180) * SIN(6.913794 * PI() / 180) + COS(6.914556 * PI() / 180) * COS(6.913794 * PI() / 180) * COS((79.973194- 79.97330) * PI() / 180)) * 180 / PI()) * 60 * 1.609344 * 1000) AS `distance` 

距离我有74.27米。

然后我使用了我发现的另一个SQL语句,它给出了85.53米。

SELECT (1.609344 * 1000 * 3959 * acos( cos( radians(6.914556) ) * cos( radians( 6.913794 ) ) * cos( radians( 79.97330 ) - radians(79.973194) ) + sin( radians(6.914556) ) * sin( radians( 6.913794) ) ) ) AS distance 

但如果我使用谷歌API

http://maps.googleapis.com/maps/api/directions/json?origin=6.914556,79.973194&destination=6.913794,79.97330&sensor=false

我距离是28米。

无论如何,我可以解决这个问题。我需要一个在MySQL端工作的解决方案。赞赏你所有的支持。

编辑:

我尝试使用PHP仍然有距离差异。

<?php
function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } 
  else if ($unit == "M") {
     return ($miles * 1.609344 * 1000);
  }else if ($unit == "N") {
    return ($miles * 0.8684);
  } else {
    return $miles;
  }
}

 function getDrivingDistance($inLatitude,$inLongitude,$outLatitude,$outLongitude)
    {
        if(empty($inLatitude) || empty($inLongitude) ||empty($outLatitude) ||empty($outLongitude))
            return 0;

        // Generate URL
        $url = "http://maps.googleapis.com/maps/api/directions/json?origin=$inLatitude,$inLongitude&destination=$outLatitude,$outLongitude&sensor=false";

        // Retrieve the URL contents
        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_URL, $url);
        $jsonResponse = curl_exec($c);
        curl_close($c);

        $dataset = json_decode($jsonResponse);
        if(!$dataset)
            return 0;
        if(!isset($dataset->routes[0]->legs[0]->distance->value))
            return 0;
        $distance = $dataset->routes[0]->legs[0]->distance->value;

        return $distance;
    }
echo distance(6.914556,79.973194,6.913794,79.97330,'M') . "<br>";
echo getDrivingDistance(6.914556,79.973194,6.913794,79.97330);

?>

2 个答案:

答案 0 :(得分:4)

我尝试了大圈公式,结果是85.5米(你的公式不太正确,但很接近)。与谷歌的不同之处在于,谷歌试图计算出道路上两点的距离,不知何故,它会向道路投射一点。见下图。 (红线是坐标图,距离为85.5米,蓝线由谷歌渲染,不知何故被“抢购”到了道路上) The actual line is red has a distance of 85.5m, the blue line is render by Google, is 'snapped' to the road

答案 1 :(得分:2)

您提供的地图链接具有不同的纬度和经度。

        "northeast" : {
           "lat" : 6.913845999999999,
           "lng" : 79.9733002
        },
        "southwest" : {
           "lat" : 6.913794800000001,
           "lng" : 79.9730488
        }

通过在查询中使用它,它可以提供正确的距离。

相关问题