[Cordova] 透過Geolocation外掛取得目前裝置所在的經緯度,並顯示在Google Map上

Cordova可以用html來開發行動裝置跨平台的app,當然一些底層的功能應用也少不了
開啟GPS取得目前裝置的所在位置並顯示在Google Map上也是很容易就可以作到的

要作到取得目前裝置的位置,並顯示在Google Map上的步驟很容易,照著下面的步驟就可以很快的完成這樣的功能了

首先先到Google Cloud Platform上建立一個新專案,然後進入API資料庫

由於是撰寫Cordova的App,所以在資料庫中點選[Google Maps Javascript API]的項目

接著啟用這個API項目

啟用後,點選左方選單中的[憑證],然後點選[建立憑證],然後選擇[API 金鑰]

接著把建立出來的金鑰複製起來,等一下會用到

接著回到Visual Studio中,在Cordova專案裡建立一個LocationGoogleMap.html的檔案

在LocaionGoogleMap.html檔案中,最上方的Content-Security-Policy,加入下方的內容

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com https://csi.gstatic.com;
script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.gstatic.com https://*.googleapis.com;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
font-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://fonts.gstatic.com;
media-src *;
img-src 'self' 'unsafe-inline' https://*.gstatic.com https://*.googleapis.com; 
connect-src *;">

在這邊關於安全性宣告的部份,主要是將googleapis.comgstatic.com這兩個網域的安全性加入至允許的列表中,若是不加入的話,會無法載入Google Map的內容

接著點選專案中的config.xml,進入[外掛程式],安裝[Goelocation]這一個外掛程式

將下面的html內容放入LocationGoogleMap.html檔案中

<script src="https://maps.googleapis.com/maps/api/js?key=[Google Map API Key]"></script>
<div>
    <div id="map" style="height:300px; width:100%"></div><br />
    <button id="btnGetGeolocation" onclick="javascript: funGetLocation();">Get Location</button><br />
    <span id="geolocation"></span>
</div>

這段內容主要是放置一個用於顯示Google Map的div在畫面上,並放置一個按鈕,當按下按鈕時可以讀取目前的位置並載入地圖
當然,第一行中載入GoogleMap的API,需要將剛剛複製下來的金鑰貼上

最後,將下面的Script放入至html或是js檔之中

var onSuccess = function (position) {
    /* 顯示position所有資料
    alert('Latitude: ' + position.coords.latitude + '\n' +
            'Longitude: ' + position.coords.longitude + '\n' +
            'Altitude: ' + position.coords.altitude + '\n' +
            'Accuracy: ' + position.coords.accuracy + '\n' +
            'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
            'Heading: ' + position.coords.heading + '\n' +
            'Speed: ' + position.coords.speed + '\n' +
            'Timestamp: ' + position.timestamp + '\n');
    */

    var element = document.getElementById('geolocation');
    element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
                        'Longitude: ' + position.coords.longitude + '<br />' +
                        '<hr />' + element.innerHTML;

    // 放入Google地圖
    getMap(position.coords.latitude, position.coords.longitude);
};

// onError Callback receives a PositionError object
//
function onError(error) {
    alert('code: ' + error.code + '\n' +
            'message: ' + error.message + '\n');
}

function funGetLocation()
{
    // 是否啟用高精確定位:是,等待GPS啟動與回傳訊息時間:30秒,該GPS保存時間:5秒
    var options = { enableHighAccuracy: true, timeout: 30000, maximumAge: 5000,};
    navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
}

function getMap(latitude, longitude) {

    var mapOptions = {
        center: new google.maps.LatLng(0, 0),
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map"), mapOptions);

    var latLong = new google.maps.LatLng(latitude, longitude);
    var marker = new google.maps.Marker({position: latLong});

    marker.setMap(map);
    map.setZoom(15);
    map.setCenter(marker.getPosition());
}

這段內容是從funGetLocation()開始,取得目前的位置後,在onSuccess的副程式裡,將位置資訊送至getMap()中,並載入Google地圖顯示在畫面上

從執行的結果可以看到,在模擬器上設定的位置跟透過Geolocation套件取得的資訊並載入Google Map後的位置是一樣的,也順利的將目前的行動裝置所在的位置顯示在Google Map上了

透過Geolocation的外掛搭配Google Map的應用,可以很快速的整合裝置與地圖的呈現,讓app的開發與功能有更多的整合與運用

參考資料
apache/cordova-plugin-geolocation

範例程式已放上Github,請參考
https://github.com/madukapai/CordovaProject