2022-11-06

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

參考資料 ----

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

GMap.php
  1.  
  2. class GMap
  3. {
  4. function getPageData($url)
  5. {
  6. $ch = curl_init();
  7. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  8. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));
  9. curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  10. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  11. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  12. curl_setopt($ch, CURLOPT_URL, $url);
  13. curl_setopt($ch, CURLOPT_NOBODY, false);
  14. curl_setopt($ch, CURLOPT_FILETIME, true);
  15. curl_setopt($ch, CURLOPT_REFERER, $url);
  16. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  17. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  18. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 4);
  19. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  20. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  21. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
  22. //取得原始碼
  23. $result['data'] = curl_exec($ch);
  24. //$info_tmp = curl_getinfo($ch);
  25. //取得info資訊
  26. //$result['info'] = $info_tmp;
  27. unset($info_tmp);
  28. curl_close($ch);
  29. return $result;
  30. }
  31.  
  32.  
  33. /**
  34. * 初始化
  35. * @param $apikey 金鑰
  36. */
  37. function __construct()
  38. {
  39. $this->apikey = '填入金鑰';
  40. }
  41.  
  42.  
  43. /*
  44. * 獲取地址經緯度 - 從google map
  45. */
  46. public function getLatLng($addr='',$apikey='')
  47. {
  48. $apikey = ($apikey=='') ? $this->apikey : $apikey;
  49. $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$addr&key=$apikey";
  50. $geocode = $this->getPageData($url);
  51. if(isset($geocode['data']))
  52. $geocode = $geocode['data'];
  53. else
  54. // 當 Google map 解析不了時,回應虛擬的經緯度
  55. $geocode = '{"results":[{"geometry":{"location":{"lat":-1,"lng":-1}}}]}';
  56.  
  57. $output = json_decode($geocode);
  58. $latitude = $output->results[0]->geometry->location->lat;
  59. $longitude = $output->results[0]->geometry->location->lng;
  60. return array('lat'=>$latitude,'lng'=>$longitude);
  61. }
  62. }
  63.  


主程式 main.php
  1.  
  2. <?php
  3. date_default_timezone_set('Asia/Taipei');
  4. include('gmap.php');
  5.  
  6. $gmap = new GMap();
  7. // 填入地址(高雄捷運美麗島站, 22.631754649712416, 120.30137231318399)
  8. // 像美麗島站這類大地標,像上面明確的描述,通常也解析的出來
  9. // 注意:地址字串內不要有空白
  10. $data = $gmap->getLatLng('高雄市新興區中山一路115號');
  11. echo "經度:".$data['lng'].",緯度:".$data['lat'];
  12. ?>
  13.  


相關筆記 ----


沒有留言:

張貼留言