使用 Haversine 公式计算 PHP 中两个邮政编码之间的距离

Using Haversine Formula to workout the distance between two postcodes in PHP

我正在尝试使用 php 中的 Haversine 公式来计算两个邮政编码之间的距离;到目前为止,我已经创建了一个计算距离的函数。我的数据库 table 名为 'postcode',字段 'postcode_id'、'postcode'、'lat'、'lng'.

    <script>
function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {  
    $earth_radius = 6371;  

    $postLat = deg2rad($latitude2 - $latitude1);  
    $postLon = deg2rad($longitude2 - $longitude1);  

    $a = sin($postLat/2) * sin($postLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($postLon/2) * sin($postLon/2);  
    $c = 2 * asin(sqrt($a));  
    $d = $earth_radius * $c;  

    return $d; 
}
</script>

<?php
$postcode_qry = mysqli_query($connect, "SELECT *,(((acos(sin((".$postLat."*pi()/180)) * sin(('lat'*pi()/180))+cos((".$postLat."*pi()/180)) * cos(('lat'*pi()/180)) * cos(((".$postLon."- 'lng')*pi()/180))))*180/pi())*60*1.1515) as distance
FROM `postcode` WHERE distance = ".$d."");

?>

您可以使用 google 服务请求它:

    function getLongLat($address) {
        $url = 'http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&language=nl&address='+$address;

        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        curl_close($ch);  
        $obj = simplexml_load_string($response);
        if ($obj) {
            $obj = $obj->result;
            return array( 'latitude' => $obj->geometry->location->lat.'', 'longitude' => $obj->geometry->location->lng.'',);
        }else{
            return [];
        } 

   }

Google 将尝试为您解析地址,猜测 postal code, Country 应该作为地址为您工作,然后您可以将所需数据传递给 MySQL 函数