【问题标题】:PHP - zipcode distance function converting distance to milesPHP - 邮政编码距离函数将距离转换为英里
【发布时间】:2013-02-22 23:07:24
【问题描述】:

我在这里找到了一些代码,可以用数学方法找出两个邮政编码之间的距离。我正在使用 Google geocode api 从每个邮政编码中获取经纬度。一切正常,但我想知道如何将 $distance 返回转换为里程:

function calc_distance($zip1, $zip2)
{   
    $geo = new GoogleGeocode( $apiKey );
    $point1 = $geo->geocode( $zip1 );
    $point1 = $point1['Placemarks'][0];
    echo "P1:"; print_r( $zip1 );
    $point2 = $geo->geocode( $zip2 );
    $point2 = $point2['Placemarks'][0];
    echo "<br>P2: "; print_r( $zip2 ); echo "<br>";

    var_dump($point1); 
    echo "<br><br>";
    var_dump($point2); 
    echo "<br>";
    $radius      = 3958;      // Earth's radius (miles)
    $deg_per_rad = 57.29578;  // Number of degrees/radian (for conversion)

    $distance = ($radius * pi() * sqrt(
                ($point1['Latitude'] - $point2['Latitude'])
                * ($point1['Latitude'] - $point2['Latitude'])
                + cos($point1['Latitude'] / $deg_per_rad)  // Convert these to
                * cos($point2['Latitude'] / $deg_per_rad)  // radians for cos()
                * ($point1['Longitude'] - $point2['Longitude'])
                * ($point1['Longitude'] - $point2['Longitude'])
        ) / 180);

    echo $distance;
    return $distance;  // Returned using the units used for $radius.
}

当我使用:calc_distance(28025, 22044); 进行测试时,它返回:

P1:28025
P2: 22044
array(7) { ["Accuracy"]=> int(5) ["Country"]=> string(2) "US" ["AdministrativeArea"]=> string(2) "NC" ["Locality"]=> string(7) "Concord" ["PostalCode"]=> int(28025) ["Latitude"]=> float(35.3898417) ["Longitude"]=> float(-80.5216184) } 

array(7) { ["Accuracy"]=> int(5) ["Country"]=> string(2) "US" ["AdministrativeArea"]=> string(2) "VA" ["Locality"]=> string(12) "Falls Church" ["PostalCode"]=> int(22044) ["Latitude"]=> float(38.8607388) ["Longitude"]=> float(-77.1571443) } 
302.952750233

【问题讨论】:

  • 距离不是302英里了吗?根据google maps的行程,很有道理。

标签: php trigonometry geocode zipcode


【解决方案1】:

半径以英里为单位,因此返回的距离以英里为单位。您可能遇到的问题是您看到返回的距离 302 和从谷歌地图返回的距离 370 之间存在差异。这是因为您的函数返回的距离返回了一个精确的点到点距离……就好像一架飞机从一个点飞到另一个点一样。行驶方向包括转弯,因此距离将大于直线距离。我发现将直线距离乘以1.25 通常会返回准确的结果。

【讨论】:

  • 哦,当然。好吧,我想它可以返回半径内最近的邮政编码,这就是我真正需要的。感谢您指出这一点。
猜你喜欢
  • 1970-01-01
  • 2011-04-01
  • 2012-12-29
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多