uniapp 提供了地圖組件<map>,app端使用map推薦使用nvue,官網https://uniapp.dcloud.io/component/map
<map>要顯示的設置寬高,不要設置百分比
只支持 gcj02
坐標
示例,地圖顯示在上海區域,起點是虹橋火車站,當點擊虹橋火車站這個地點marker,在地圖上顯示出目的地迪士尼,顯示出路線圖,並且控制在可視區域內
以下代碼是在nvue中實現,只在app 中可用
坐標轉換插件使用gcoord,https://github.com/hujiulong/gcoord
圖標設置使用@2x,@3x的圖標,在地圖上會顯示的清晰一點,其他的會很模糊
<template> <view> <map id="map" class="mapView" :style="{'width':screenWidth+'px','height':screenHeight+'px'}" scale="9" :longitude="center[0]" :latitude="center[1]" :markers="markers" :include-points="includePoints" :polyline="polyline" @markertap="showRoute"></map> </view> </template> <script> import gcoord from '../../common/gcoord.js' export default { data() { return { screenWidth: 0, screenHeight: 0, center: [121.506379, 31.245414], //地圖中心點坐標,高德系經緯度 //百度坐標 points: { longitude: 121.346817, latitude: 31.203347, tolng: 121.671964, tolat: 31.148267 }, markers: [], includePoints: [], polyline:[], line: { width: 7, // dottedLine: true, arrowLine: true }, } }, onLoad() { var that = this; uni.getSystemInfo({ success: function(e) { that.screenWidth = e.screenWidth; that.screenHeight = e.screenHeight; } }) let center = this.transformBaiduToAm(this.center[0], this.center[1]); this.center = center;//可以通過設置地圖的longitude和latitude屬性來移動地圖到不同的城市 //首先將百度坐標轉為高德系,引入gcoord插件 let start = this.transformBaiduToAm(this.points.longitude, this.points.latitude); this.markers = [{ longitude: start[0], latitude: start[1], iconPath: '../../static/start@3x.png', width: 30, height: 30 }]; this.start = start; }, onReady() { //路線檢索,會返回兩個地點之間的經緯度,最后連線 this.mapContext = uni.createMapContext('map', this); this.search = new plus.maps.Search(this.mapContext); let that = this; this.search.onRouteSearchComplete = function(state, result) { if (state == 0) { if (result.routeNumber <= 0) { console.log("沒有檢索到結果"); } for (var i = 0; i < result.routeNumber; i++) { let points = result.getRoute(i).pointList; that.line.points = points; that.polyline = [that.line];//畫路線 that.includePoints = points; } } else { console.log("檢索失敗"); } } }, methods: { //百度經緯度轉成高德經緯度 transformBaiduToAm(lng, lat) { return gcoord.transform( [lng, lat], // 經緯度坐標 gcoord.BD09, // 當前坐標系 gcoord.GCJ02 // 目標坐標系 ); }, //點擊marker時,在地圖上上顯示這個地點對應的另一個端點,並顯示出路線 showRoute() { //增加或者減少地圖上的marker時,要重新賦值markers, //如果兩個marker有遮蓋,后添加的層級更高 let point = this.transformBaiduToAm(this.points.tolng, this.points.tolat); this.markers = [...this.markers, { longitude: point[0], latitude: point[1], iconPath: '../../static/end@3x.png', width: 30, height: 30 }]; //在地圖上畫出兩個地點的線路 //並且要把所有顯示在地圖上的marker都顯示在可視區域內 //轉為 point 對象 let start = new plus.maps.Point(this.start[0], this.start[1]); let end = new plus.maps.Point(point[0], point[1]); this.search.drivingSearch(start, '上海', end, '上海'); } } } </script> <style> </style>
注:屬性的更改比如markers,include-points 等設置在map 上的屬性都是重新賦值進行更新,沒有提供方法進行直接修改的