日前,一位客戶問說為什麼我給它寫的google地圖api連結程式,有些地址查出來的位置會和google官網的不一樣?我聽到時當然覺得不大可能,試了一下對方給我的地址…啊咧,還真的不一樣!
google maps api的敗筆 GClientGeocoder地址轉譯有誤 使用經驗

我想了想,可能是google maps api連接的資料庫,和google maps直接查詢的資料庫有差異。

搜搜google,我們在使用地址轉地圖位置時,都會用到GClientGeocoder這個函式,它會把輸入的地址先去google資料庫查詢座標,再拿這座標去查詢地址。

看一下google官方給的範例demo):

var map = new GMap2(document.getElementById("map_canvas"));
var geocoder = new GClientGeocoder(); 

function showAddress(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
        map.setCenter(point, 13);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(address);
      }
    }
  );
}

既然GClientGeocoder查出的座標有問題,就換個連結通道試試,找到Geocoding via HTTP,它是透過位址 http://maps.google.com/maps/geo 再帶參數查詢座標。

參考了此篇將中文地址寫入資料庫時透過 google maps 取得作標的作法,取出座標,再帶入google maps api來查詢:

1. 用php取出座標:

$address = $_POST['address'];
$map_api_key = 'ABQIAAAATEOf9wLppH9P5Zgz_mbvGhTQKjgTyenlgzz_Jmf84ElUIhrNPBTph578IhrUkgnO7SFaO9P03-E0pQ';
$csv_url = "http://maps.google.com/maps/geo?q=".urlencode($address)."&output=csv&key=".$map_api_key;
$ch = curl_init($csv_url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$get_contents = curl_exec($ch);
curl_close($ch);
$string = explode(',', $get_contents);
$longitude = $string[2]; // 經度
$latitude = $string[3]; // 緯度

2. 用javascript至google查詢:

function initialize() {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(<?=$longitude?>,<?=$latitude?>), 13);
    map.setUIToDefault();
  }
}

結果…查出來的位置還是不對T_T


最後,跟客戶確認狀況,他希望地址位置對比較重要,那麼就用iframe去嵌 http://maps.google.com.tw/maps 的位址,再帶入參數:

<iframe width="770" height="500" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src=http://maps.google.com.tw/maps?f=q&hl=zh-TW&geocode=&q=<?=urlencode($address)?>&z=16&output=embed&t=></iframe>

更多參數,可瀏覽此文Google Map Parameters
搞到最後,還是用iframe,不是用google maps api,讓人覺得有xxx


註1:此文範例略掉一些東西,不談基本,所以比較適合有用過google maps api的朋友瀏覽

註2:有用google maps api(GClientGeocoder)做地址轉譯的人,可以試試這個地址(宜蘭縣壯圍鄉美城村大福路3段53巷9號),會和google maps網站查出來的位置不一樣

註3:基礎文章(Google Maps API 實作範例 | 使用google map api來做地址定位 | Google Maps API 輸入地址轉經緯度,並產生地圖程式分享!! | I love Google Map II

註4:最近api出v3版本,有空再玩看看

 
  • Hemidemi
  • MyShare
  • Udn
  • funP
  • Furl