2022-11-06

【PHP】Google Maps API -- 將地址轉換成經緯度座標

參考資料 ----

建立類別 GMap,用地址轉換經緯度

GMap.php
 
class GMap
{
    function getPageData($url)
    { 
        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);  
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_NOBODY, false);
        curl_setopt($ch, CURLOPT_FILETIME, true);
        curl_setopt($ch, CURLOPT_REFERER, $url);
         
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 4);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
        //取得原始碼
        $result['data'] = curl_exec($ch);
        //$info_tmp = curl_getinfo($ch);
        //取得info資訊
        //$result['info'] = $info_tmp;
        unset($info_tmp);
        curl_close($ch);
          
        return $result;
    }


    /** 
     * 初始化 
     * @param $apikey 金鑰 
     */ 
    function __construct()
    {
        $this->apikey = '填入金鑰';
    } 


    /* 
     * 獲取地址經緯度 - 從google map
     */  
    public function getLatLng($addr='',$apikey='')
    {
        $apikey = ($apikey=='') ? $this->apikey : $apikey;
        $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$addr&key=$apikey";
        $geocode = $this->getPageData($url);
        if(isset($geocode['data']))
            $geocode = $geocode['data'];
        else
            // 當 Google map 解析不了時,回應虛擬的經緯度
            $geocode = '{"results":[{"geometry":{"location":{"lat":-1,"lng":-1}}}]}';

        $output = json_decode($geocode); 
        $latitude = $output->results[0]->geometry->location->lat;
        $longitude = $output->results[0]->geometry->location->lng; 
     
        return array('lat'=>$latitude,'lng'=>$longitude);
    }
}
 


主程式 main.php
 
<?php
date_default_timezone_set('Asia/Taipei');
include('gmap.php');

$gmap = new GMap();
// 填入地址(高雄捷運美麗島站, 22.631754649712416, 120.30137231318399)
// 像美麗島站這類大地標,像上面明確的描述,通常也解析的出來
// 注意:地址字串內不要有空白
$data = $gmap->getLatLng('高雄市新興區中山一路115號');
echo "經度:".$data['lng'].",緯度:".$data['lat'];
?>
 




沒有留言:

張貼留言