Google Maps API - 地理編碼服務 ( 地址定位 )

一開始使用地圖,總會用經緯度來標記位置,但經緯度往往不夠直覺,而且要知道某個地點的經緯度也是個問題,所以這時就必須使用 Google Maps API 的地理編碼服務來實現「地址定位」,只要輸入對應的地址,就可以在地圖上標記。

啟用 Google Maps Geocoding API

要使用地理編碼服務,首先要前往 Google API Console,進入之後,建立新的專案或是選擇現有的專案 ( 不知道怎麼做可以參考 Google Maps (1) - 網頁載入地圖 ( 起手式 ) ),接著點選上方「啟用 API 和服務」。

Google Maps API - 地理編碼服務 ( 地址定位 )

在搜尋欄位搜尋「Google Maps Geocoding API」,找到後點選並且啟用。

Google Maps API - 地理編碼服務 ( 地址定位 )

啟用後,在資訊主頁最下方的 API 就會看到 Google Maps Geocoding API 的訊息, 依據 Google API 標準方案,免費版本一天可以呼叫這個 API 2500 次,每秒可以 50 次,對於自己要練習或是簡單的程式,應該都相當夠用。

Google Maps API - 地理編碼服務 ( 地址定位 )

使用地址定位

要使用地址定位,第一步要先透過google.maps.Geocoder物件存取程式碼內的 Google Maps API 地理編碼服務,而Geocoder.geocode()方法會初始化對地理編碼服務的要求。

geocoder = new google.maps.Geocoder();

接著使用geocoder.geocode({ 'address': address}, callback(results, status))對地址進行地理編碼,在擷取到地理編碼時會依序傳遞兩個參數 results 和 status,results 包含以下的結果物件,而最常使用的應該就是geometry.location,因為這回傳的就是地圖常用的經緯度 LatLng。

results[]: {
 types[]: string,
 formatted_address: string,
 address_components[]: {
   short_name: string,
   long_name: string,
   postcode_localities[]: string,
   types[]: string
 },
 partial_match: boolean,
 place_id: string,
 postcode_localities[]: string,
 geometry: {
   location: LatLng,
   location_type: GeocoderLocationType
   viewport: LatLngBounds,
   bounds: LatLngBounds
 }
}

然而 status 回傳的是成功與否的狀態,如果回傳 OK 表示順利剖析地址並且已至少傳回一個地理編碼,以下面的範例來說,就可以透過地址編碼,將地圖標記放在「總統府」的地址上。

範例:使用地址定位

var map, geocoder;

function initMap() {
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 17
  });

  var address = '總統府';

  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == 'OK') {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      console.log(status);
    }
  });
}

Google Maps API - 地理編碼服務 ( 地址定位 )

簡單的查詢地址功能

如果已經會使用地址定位,就可以來透過 HTML 的 input 和 button 做點變化,下面的例子在網頁中放入一個輸入欄位,輸入地址之後按下定位,就可以將自己指定的地址在地圖上置中,並放上標記。

範例:使用地址定位

submitBtn.on('click', function() {
  console.log(addressInput.val());
  geocoder.geocode({
    'address': addressInput.val()
  }, function(results, status) {
    if (status == 'OK') {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
    } else {
      console.log(status);
    }
  });
});

Google Maps API - 地理編碼服務 ( 地址定位 )

參考資料

地理編碼服務是參考 Google 官方文件 地理編碼服務,如果想要了解 results 回傳的參數細節用法就可以前往閱讀,文件的後半段也提到一些地址反查的功能,不過目前還沒想到該怎麼用,就等有用到的時候再寫篇文章記錄一下好了。

有興趣瞧瞧其他新文章嗎?