實作 Google map v3 (上)

Google map 從 v1 一直演進到目前的 v3 已經有兩年多的時間了,而 v1 的版本在 2012.12.3就停止支援了,在 Google map v1 頁面可以看到如下的聲明:

Note: Version 1 of the Google Maps Android API has been officially deprecated as of December 3rd, 2012. This means that from March 18th, 2013 you will no longer be able to request an API key for this version. No new features will be added to Google Maps Android API v1. However, apps using v1 will continue to work on devices. Existing and new developers are encouraged to use Google Maps Android API v2.

在這之後 Google map v2 問世,經過兩多的時間慢慢的也轉換成 v3 的版本了,在 Google map v3 裡也提到:

注意: Google Maps JavaScript API 第 3 版為現行的正式 JavaScript API 版本。根據我們的汰換政策,此 API 的第 2 版已正式由第 3 版取代。我們建議您將程式碼遷移至這個功能更新、更完善的新版本!

因此,這篇內容就不多說明 v1 及 v2 的功能及使用方式,就直接介紹 v3 的特性及在 Android 上的使用方式吧。

在 v2 使用 map 時需要用到 fragment 的方式嵌入 google map ,而在 v3 就改為使用 JavaScript 及 html 的方式呈現,從這裡就可以發現在 Android 中使用 v3 就需要用到 WebView 入嵌入 google map 了,不再是以 fragment 的方式。

首先先新增 assets 資料夾在 Android 專案裡,並在資料夾加入 GoogleMap.html 檔案,此 html 檔內容如下

<!DOCTYPE html><html>
  <head>
    <metaname="viewport"content="initial-scale=1.0, user-scalable=no"/>
    <styletype="text/css">
      html {height:100%}
      body {height:100%;margin:0;padding:0}
      #map_canvas {height:100%}
    </style>
    <scripttype="text/javascript"
      src="http://maps.googleapis.com/maps/api/js?sensor=false">
    </script>
    <scripttype="text/javascript">
      function initialize(){
        var mapOptions ={
          center:new google.maps.LatLng(25.033146,121.5637343), //中心點
          zoom:8,  //顯示大小
          mapTypeId: google.maps.MapTypeId.ROADMAP //顯示的樣式
        };
        var map =new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
      }
    </script>
  </head>
  <bodyonload="initialize()">
    <divid="map_canvas"style="width:100%;height:100%"></div>
  </body></html>

如此新增一個 WebView 將此 html 載入就可以了, URL 會是 “file:///android_asset/GoogleMap.html"

WebView googleMap = new WebView(this);
googleMap.loadUrl("file:///android_asset/GoogleMap.html");

如 此 google map 就會以網頁方式 load 進來,不過由於目前所有參數控制都在 html 中,如果要修改中心點以目前的方式是無法操作,因此會需要借由 JavaScriptInterface 來做到 app 與 html 傳遞參數,此部份在實作 Google map v3 (下) 將會說明如何實作。

發表留言