【问题标题】:PHP Latitude Longitude to AddressPHP纬度经度地址
【发布时间】:2012-09-30 09:52:23
【问题描述】:

我的网站上有一个表单,用户可以在其中输入某个地点的地址。当他们提交表单时,我将此位置转换为纬度/经度并将其存储在 MySQL 数据库中。我正在使用 Google 的地理编码服务进行此转换。问题是我找不到将纬度/经度转换回地址的类或服务,据我所知,Google 的地理编码服务是单向转换。我意识到我可以将物理地址存储在数据库中,但随着时间的推移,当它可以以更简单的格式存储时,这是浪费空间。有没有人知道从纬度/经度转换为地址的类/服务,或者我错了,我可以使用谷歌的地理编码系统?这几天我一直在寻找答案,但找不到任何东西。感谢您的帮助!

【问题讨论】:

    标签: php geolocation location latitude-longitude


    【解决方案1】:

    将地理坐标转换为地址称为反向地理编码。在此脚本中,我们使用 Google 地图 API,因为它免费、快速且无需 API 密钥。

    Google 尊重地理编码的速率限制是每个 IP 每天 2500 次 API 调用。

    Reveres 地理编码的 PHP 函数

    <?
      function getaddress($lat,$lng)
      {
         $url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lat).','.trim($lng).'&sensor=false';
         $json = @file_get_contents($url);
         $data=json_decode($json);
         $status = $data->status;
         if($status=="OK")
         {
           return $data->results[0]->formatted_address;
         }
         else
         {
           return false;
         }
      }
    ?>
    

    在 getaddress() 函数中传递纬度和经度。成功时返回地址字符串,否则返回布尔值 false。

    示例

    <?php
      $lat= 26.754347; //latitude
      $lng= 81.001640; //longitude
      $address= getaddress($lat,$lng);
      if($address)
      {
        echo $address;
      }
      else
      {
        echo "Not found";
      }
    ?>
    

    【讨论】:

    • URL 应该是 https。 Google 现在要求对该 API 的请求必须通过 SSL。否则,您会收到“REQUEST_DENIED”错误。
    【解决方案2】:
    <?php
    
    /* 
    * Given longitude and latitude in North America, return the address using The Google Geocoding API V3
    *
    */
    
    function Get_Address_From_Google_Maps($lat, $lon) {
    
    $url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";
    
    // Make the HTTP request
    $data = @file_get_contents($url);
    // Parse the json response
    $jsondata = json_decode($data,true);
    
    // If the json data is invalid, return empty array
    if (!check_status($jsondata))   return array();
    
    $address = array(
        'country' => google_getCountry($jsondata),
        'province' => google_getProvince($jsondata),
        'city' => google_getCity($jsondata),
        'street' => google_getStreet($jsondata),
        'postal_code' => google_getPostalCode($jsondata),
        'country_code' => google_getCountryCode($jsondata),
        'formatted_address' => google_getAddress($jsondata),
    );
    
    return $address;
    }
    
    /* 
    * Check if the json data from Google Geo is valid 
    */
    
    function check_status($jsondata) {
        if ($jsondata["status"] == "OK") return true;
        return false;
    }
    
    /*
    * Given Google Geocode json, return the value in the specified element of the array
    */
    
    function google_getCountry($jsondata) {
        return Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"]);
    }
    function google_getProvince($jsondata) {
        return Find_Long_Name_Given_Type("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
    }
    function google_getCity($jsondata) {
        return Find_Long_Name_Given_Type("locality", $jsondata["results"][0]["address_components"]);
    }
    function google_getStreet($jsondata) {
        return Find_Long_Name_Given_Type("street_number", $jsondata["results"][0]["address_components"]) . ' ' . Find_Long_Name_Given_Type("route", $jsondata["results"][0]["address_components"]);
    }
    function google_getPostalCode($jsondata) {
        return Find_Long_Name_Given_Type("postal_code", $jsondata["results"][0]["address_components"]);
    }
    function google_getCountryCode($jsondata) {
        return Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"], true);
    }
    function google_getAddress($jsondata) {
        return $jsondata["results"][0]["formatted_address"];
    }
    
    /*
    * Searching in Google Geo json, return the long name given the type. 
    * (If short_name is true, return short name)
    */
    
    function Find_Long_Name_Given_Type($type, $array, $short_name = false) {
        foreach( $array as $value) {
            if (in_array($type, $value["types"])) {
                if ($short_name)    
                    return $value["short_name"];
                return $value["long_name"];
            }
        }
    }
    
    /*
    *  Print an array
    */
    
    function d($a) {
        echo "<pre>";
        print_r($a);
        echo "</pre>";
    }
    

    【讨论】:

    • 我在 PHP 中使用上面的代码,通常效果很好 - 但是有时 Get_Address_From_Google_Maps($lat, $lon) 会为 $address 返回 null。你见过这个问题和任何建议吗?这是非常间歇性的,但确实会发生。 lat、lon 是有效的,并且之前返回了一个有效的地址,但是在第二次调用、第三次调用或第 n 次调用相同的 lat 时,lon 会为地址返回 null 吗?有什么想法吗?
    • URL 应该是 https。 Google 现在要求对该 API 的请求必须通过 SSL。否则,您会收到“REQUEST_DENIED”错误。
    【解决方案3】:

    您正在寻找 Google(或其他任何人)的 reverse geocoding service

    【讨论】:

    • 好吧,太棒了,这很完美。这几天一直在找这个,谢谢!
    • 请注意 google 的 TOS(注意:Geocoding API 只能与 Google 地图一起使用;禁止地理编码结果而不显示在地图上。)developers.google.com/maps/documentation/geocoding
    【解决方案4】:

    地理位置 PHP 将纬度经度转换为地址。 首先,您需要获取使用以下链接找到的 google map api 的 api 密钥:

    https://developers.google.com/maps/documentation/geocoding/start#ReverseGeocoding

    将以下函数放入您的辅助类并在您想要简单传递 lat 和 long 的任何地方调用该函数。在传递 lat long 之后,它们返回有关 lat long 值的地址。整个过程称为反向地理编码。

    /**
     * find address using lat long
     */
    public static function geolocationaddress($lat, $long)
    {
        $geocode = "https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=false&key=AIzaSyCJyDp4TLGUigRfo4YN46dXcWOPRqLD0gQ";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $geocode);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $response = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($response);
        $dataarray = get_object_vars($output);
        if ($dataarray['status'] != 'ZERO_RESULTS' && $dataarray['status'] != 'INVALID_REQUEST') {
            if (isset($dataarray['results'][0]->formatted_address)) {
    
                $address = $dataarray['results'][0]->formatted_address;
    
            } else {
                $address = 'Not Found';
    
            }
        } else {
            $address = 'Not Found';
        }
    
        return $address;
    }
    

    更多详情请查看以下链接: Geolocation PHP Latitude Longitude to Address - Lelocode

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      相关资源
      最近更新 更多