GoogleMap增加標記和路線軌跡的方法


聲明:本文基於JavaScript環境編寫。

前言

按照目前的項目需求,我們需要在谷歌地圖上標記出當前倉庫的位置、司機補貨的行車路徑、司機當前班次需要補貨的機器的位置,同時根據補貨狀態的不同標記成不同狀態的圖標。

分析完需求,總結一下就是我們需要在谷歌地圖上顯示眾多標記、軌跡畫線、不同的標記顯示不同的圖標,於是前往Google Map查看Api,因為我們的需求重點是在PC瀏覽器上實現,所以我們只關注了基於JavaScript的API,本文也基於此展開敘述。

目標

從本文中我將大概總結以下幾點內容:

  • 在web項目中引入Google Map
  • 在地圖上增加位置標記
  • 在地圖上增加自定義圖標標記
  • 在地圖上根據眾多GPS點繪制路線,並標記不同顏色
  • 在地圖上清除已經繪制好的標記

我截取了一張實際的效果圖,其中圖標有藍色的倉庫、綠色狀態表示已完成的機器,未完成的機器應該是灰色的,但是這張圖中沒有這種狀態的數據。

功能實現

前期准備

1、准備好SDK引入

按照GoogleMap API中的指引,你需要引入以下JS文件:

1 <!--
2 * Load the API from the specified URL
3 * The async attribute allows the browser to render the page while the API loads
4 * The key parameter will contain your own API key (which is not needed for this tutorial)
5 * The callback parameter executes the initMap() function
6 -->
7 <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>

其中,YOUR_API_KEY是你在Google雲平台操作面板為GoogleMap API使用所申請的秘鑰,你可以通過以下指南找到答案。

申請GoogleMap API KEY:https://developers.google.com/maps/documentation/javascript/get-api-key

同時,按照上面引用的JS文件中指明的回調方法,你需要寫出函數體,並在此中初始化地圖和數據:

1 <script>
2     // Initialize and add the map
3     function initMap() {
4         ....
5     }
6 </script>

創建地圖

1、創建一個div用來放置地圖,可以給地圖設置一個id屬性,以便生成地圖時使用

 <div id="map" class="ibox-content" style="padding:15px 0 20px 0"></div> 

2、創建Google地圖對象,設置中心點和視圖層級等信息

 1 /* 初始化地圖對象 */
 2 function initMap() {
 3     var center = {lat: 13.751898, lng: 100.500565};
 4     var map = new google.maps.Map(document.getElementById('map'), {
 5         center: center, // 地圖所展現視圖的中心點
 6         zoom: 10,
 7         mapTypeId: google.maps.MapTypeId.ROADMAP,
 8         mapTypeControl: false,
 9         panControl: false,
10         zoomControl: true,
11         streetViewControl: false
12     });
13 }

3、添加倉庫位置標記

 1 /* 獲取倉庫位置數據,並在地圖上顯示倉庫圖標 */
 2 function showWarehousePosition(map) {
 3     var warehouseId = $("#warehouse").val();
 4     $.ajax({
 5         url: 'getWarehouseGpsData',
 6         type: 'GET',
 7         dataType: 'JSON',
 8         data: {warehouseId: warehouseId},
 9         success: function (data) {
10             if(data.code == 200) {
11                 if(data.result != undefined) {
12                     // 從后台響應回來的是一個包含lat和lng屬性的對象
13                     var warehouseGpsPosition = {lat: Number(data.result.lat), lng: Number(data.result.lng)};
14                     // 在地圖上生成倉庫的標記,倉庫圖標自定義
15                     var marker = new google.maps.Marker({
16                         position: warehouseGpsPosition,
17                         icon: "./googlemap/images/warehouse.png",
18                         map: map
19                     });
20                 }
21             }else {
22                 alert("Failed.");
23             }
24         },
25         error: function () {
26             alert("System error.");
27         }
28     })
29 }

4、添加機器的位置,為不同狀態標注不同圖標

 1 // 用於記錄機器標注位置,以便於后續清除標記
 2 var deviceMarkerArray = [];
 3 
 4 /* 查詢機器位置數據 */
 5 function showMachinePosition(map) {
 6     var buzId = $("#business").val();
 7     $.ajax({
 8         url: 'getMachineGpsList',
 9         type: 'GET',
10         dataType: 'JSON',
11         data: {buzId: buzId},
12         success: function (data) {
13             if(data.code == 200 && data.result != undefined) {
14                 var finishedMachineGpsList = data.result.finishedMachineGpsList;
15                 var unfinishedMachineGpsList = data.result.unfinishedMachineGpsList;
16                 drawMachinePosition(map, finishedMachineGpsList, unfinishedMachineGpsList);
17             }else {
18                 alert("Failed.");
19             }
20         },
21         error: function () {
22             alert("System error.");
23         }
24     })
25 }
26 
27 /* 繪制機器位置 */
28 function drawMachinePosition(map, finishedMachineGpsList, unfinishedMachineGpsList) {
29 
30     // 先清除地圖上之前標記過的機器圖標
31     // 可做可不做,業務需要的話可以清除
32     clearOverlays();
33 
34     // 已完成機器位置
35     if(finishedMachineGpsList != null && finishedMachineGpsList != undefined) {
36         $.each(finishedMachineGpsList, function (index, item) {
37             var marker = new google.maps.Marker({
38                 position: item,
39                 icon: "./googlemap/images/fulfilled.png",
40                 map: map
41             });
42             deviceMarkerArray.push(marker);
43             google.maps.event.addListener(marker,"click",function(){});
44         });
45     }
46 
47     // 未完成機器位置
48     if(unfinishedMachineGpsList != null && unfinishedMachineGpsList != undefined) {
49         $.each(unfinishedMachineGpsList, function (index, item) {
50             var marker = new google.maps.Marker({
51                 position: item,
52                 icon: "./googlemap/images/unfulfill.png",
53                 map: map
54             });
55             deviceMarkerArray.push(marker);
56             google.maps.event.addListener(marker,"click",function(){});
57         });
58     }
59 
60 }
61 
62 /* 清除之前的標記 */
63 function clearOverlays() {
64     if(deviceMarkerArray != undefined && deviceMarkerArray != null && deviceMarkerArray.length > 0) {
65         for (var i = 0; i < deviceMarkerArray.length; i++ ) {
66             deviceMarkerArray[i].setMap(null);
67         }
68         deviceMarkerArray.length = 0;
69     }
70 } 

5、生成司機行車路線

通過司機手機手持app實時上報上來的GPS位置信息,我們將之在地圖上逐個標記並串聯成線,形成軌跡圖效果。

 1 /* 獲取司機行車記錄下的GPS數據串,並在地圖上連線形成路徑 */
 2 function showDriverRoute(map) {
 3     var buzId = $("#business").val();
 4     $.ajax({
 5         url: 'getDriverGpsList',
 6         type: 'GET',
 7         dataType: 'JSON',
 8         data: {buzId: buzId},
 9         success: function (data) {
10             if(data.code == 200 && data.result != undefined) {
11                 drawDriverRoute(map, data.result.driverGpsDataList, 
12                     data.result.routeColor, data.result.carLocation);
13             }else {
14                 alert("Failed.");
15             }
16         },
17         error: function () {
18             alert("System error.");
19         }
20     })
21 }
22 
23 /* 繪制行車路線 */
24 function drawDriverRoute(map, driverGpsDataList, routeColor, carLocation) {
25     // 繪制行車路線
26     // driverGpsDataList是一個后台List對象,數組對象中包含的元素都是包含lat和lng屬性的對象
27     var driverPath = new google.maps.Polyline({
28         path: driverGpsDataList,
29         geodesic: true,
30         strokeColor: routeColor, // #ff0000
31         strokeOpacity: 1.0,
32         strokeWeight: 2
33     });
34     driverPath.setMap(map);
35 
36     // 抓取最后的一個點,繪制一個車的圖標,表示車在這里
37     // carLocation是一個包含lat和lng屬性的后台對象
38     var latLng = {lat: Number(carLocation.lat), lng: Number(carLocation.lng)};
39     var carMarker = new google.maps.Marker({
40         position: latLng,
41         icon: "./googlemap/images/vehicle.png",
42         map: map
43     });
44 }

參考資料

1、https://developers.google.com/maps/documentation/javascript/tutorial


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM