个人主体的小程序如何利用腾讯地图 webServiceAPI 配合map组件 来做路线规划?

623 阅读2分钟

**前言:

  最近在做一个自己的小程序的工具集‘web小白成长之旅’ ,里面的包括一些地图等工具。但是个人主体开发小程序在添加插件里面无论如何都无法添加  ‘腾讯位置服务路线规划’插件。既然找不到这个插件,那么,只能绕过这个插件,去使用其他的。今天我就用腾讯地图 webServicr API服务来做一些简单的地图展示。**

image.png

image.png

一、前期准备工作

1.在设置—第三方设置-----第三方平台授权管理中 -添加 腾讯位置授权

image.png

2. 在腾讯位置服务后台 控制台 添加应用 以及 添加key: 这里有一个重点: 在下面勾选上微信小程序选项 并且把自己小程序的appid复制在里面

image.png

二、项目配置工作(我是用uniapp写的小程序,所以在这里我说的是uniapp 里面的配置)

1.在manifest.json 里面 打开 源码视图 找到mp-weixin,配置

"permission" : {

“scope.userLocation” : {

“desc” : “你的位置信息将用于小程序定位组件效果展示”

}

},

image.png

2.配置requiredPrivateInfos ,如果不配置报错:选择地址:{“errMsg”:“getLocation:fail the api need to be declared in the requiredPrivateInfos field in app/ext.json”}

image.png

三、页面使用

我的步骤:

1.通过chooseLocation 获取到出发地和目的地的经纬度,调用腾讯weibService API给的接口,有一些bug,但是可以大致的规划出路线。 以下是做路线规划一个大代码片段,大家可以自己运行试试,不过必要的参数还是要具备的:

<template>

<map name="" :latitude="latitude" :longitude="longitude" show-location :markers="covers" :scale="scale" :polyline="polyline_Object"></map>

</template>

<script>

export default{

data(){

return{

start_address:{

longitude:0,

latitude :0

},

end_address:{

longitude:0,

latitude :0

},

//这个数据就是渲染所有的点,利用map组件中的polyline 进行点的渲染

polyline_Object:[

{

points:[],

color: "#3FB837",

width: 3,

dottedLine: false

}

]

}

}

methods:{
//路线规划中的 开车
getRouteDriving() {

let that=this;

uni.request({

url: 'https://apis.map.qq.com/ws/direction/v1/driving/?from=' + that.start_address.latitude +

',' + that.start_address.longitude + '&to=' + that.end_adress.latitude + ',' + that

.end_adress.longitude + '&accuracy=30&output=json&callback=cb' + '&key=' + that.keyCode,

success(res) {

// console.log(res)

if (res.data.status == 0) {

let coors = res.data.result.routes[0].polyline;

for (let i = 2; i < coors.length; i++) {

coors[i] = coors[i - 2] + coors[i] / 1000000

}

// console.log('路线坐标点串解压完毕!')

// console.log('路线坐标点串解压结果如下:')

// console.log(coors);

/** 将解压后的坐标点串进行拼接成polyline想要的样子 */

var coors_new = [] //记住微信小程序声明一个数组这样写

for (var j = 0; j < coors.length; j++) {

coors_new.push({

latitude: parseFloat(coors[j]),

longitude: parseFloat(coors[j + 1])

})

j++;

}

// console.log('路线坐标点串格式化完毕!')

// console.log('路线坐标点串格式化结果如下:')

// console.log(coors)

// console.log('已经产生新的经纬度数组coors_new如下:')

// console.log(coors_new)

// console.log('路线坐标点串解压后一共:' + coors.length + '个')

// console.log('路线坐标点串转换后一共:' + coors_new.length + '个')

that.polyline_Object=[{

points:coors_new,

color: "#3FB837",

width: 3,

dottedLine: false

}]

}

},

fail(err) {

console.log(err)

}

})

},

}

}

</script>

拿到的数据结果如图所示:

image.png

如果感兴趣,大家可以去看一下腾讯webServie API的文档,当然也可以看一下我的小程序,查看一下效果

image.png