在微信小程序中要使用地图需要先注册一个 Key
下载地图组件
创建新的文件封装 Key
// 地址经纬度
import qqmap from '../libs/qqmap-wx-jssdk'
export default new qqmap({
key:'VTNBZ-GLFWT-AMXXY-VOY7N-4IS5S-G7FGK'
})
引入到页面
// map.js
import qqmap from '../../../utils/qqmap'
Page({
data:{
markers:[{
id:1,
content:'123',
latitude: 30.59982,
longitude: 114.3096,
width:24,
height:30
},{
id:2,
latitude: 32.90982,
longitude: 114.3096,
width:24,
height:30
}],
latitude: 30.59982,
longitude: 114.3096,
polyline:[],
scale:16,
},
onLoad(){
},
butMap(){
this.setData({scale:6})
this.getPolyline()
},
// 地图划线
getPolyline(){
qqmap.direction({
mode:'walking',
from:'30.59982,114.3096',
to:'32.90982,114.3096',
success: (res) => {
var ret = res;
var coors = ret.result.routes[0].polyline, pl = [];
//坐标解压(返回的点串坐标,通过前向差分进行压缩)
var kr = 1000000;
for (var i = 2; i < coors.length; i++) {
coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
}
//将解压后的坐标放入点串数组pl中
for (var i = 0; i < coors.length; i += 2) {
pl.push({ latitude: coors[i], longitude: coors[i + 1] })
}
console.log(pl)
//设置polyline属性,将路线显示出来,将解压坐标第一个数据作为起点
this.setData({
latitude: pl[0].latitude,
longitude: pl[0].longitude,
polyline: [{
points: pl,
color: '#0070d9',
width: 5
}]
})
}
})
}
})
基本样式
<!-- <text>地图导航</text> -->
<!-- 头部 -->
<!-- 底部 -->
<view class="bottom-but">
<view bindtap="butMap" class="start-navigation">开始导航</view>
</view>
<!-- 地图 -->
<view class="polyline">
<!-- 地图 -->
<map
show-scale="true"
show-scale="true"
min-scale="3"
max-scale="18"
markers="{{markers}}"
scale="{{scale}}"
polyline="{{polyline}}"
style="width: 100%; height: 100%;"
latitude="{{latitude}}" longitude="{{longitude}}"></map>
</view>
css=============================================
/* 地图 */
.bottom-but{
width: 750rpx;
height: 140rpx;
background: #FFFFFF;
position: fixed;
left: 0;
bottom: 0;
padding-bottom: 60rpx;
}
.start-navigation{
width: 414rpx;
height: 100rpx;
color: #fff;
background: #EF4F3F;
border-radius: 50rpx;
width: 414rpx;
height: 100rpx;
background: #EF4F3F;
border-radius: 50rpx;
margin: 20rpx auto;
text-align: center;
line-height:100rpx;
}
.polyline {
height: 980rpx;
z-index: -1;
}