uniapp app下使用地图组件
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 上的属性都是重新赋值进行更新,没有提供方法进行直接修改的