这两天在看小程序的地图,写写笔记记录一下
小程序官方文档提供的方法
https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html
腾讯地图提供的jssdk
http://lbs.qq.com/qqmap_wx_jssdk/qqmapwx.html
根据提示使用腾讯地图jssdk需要申请,在实例化的时候填入密匙,接下来就可以使用他提供的各种方法了
我先说说我做关键词搜索和点击搜索结果进行路线规划(规划目前可能只是按自驾的路线,不完善的地方麻烦大家赐教了)
搜索我先使用getLocation获取当前位置坐标
wx.getLocation({type: 'wgs84',success: function (res) {latitude = res.latitudelongitude = res.longitudevar speed = res.speedvar accuracy = res.accuracy},fail: function (res) {console.log(res)},complete: function (res) {console.log('Complete')}})
接着利用获取到的城市坐标获取城市名字
qqmapsdk.reverseGeocoder({location: {latitude: latitude,longitude: longitude},success: function(res){//console.log(res)cityName = res.result.address_component.cityconsole.log(cityName)},fail: function (res) {console.log(res);},complete: function (res) {console.log('获取当前城市完成');}})
然后调用getSuggestion方法进行当前城市的关键词搜索显示功能(将获取到的关键词循环显示在搜索下面,给便利出来的每个选项加个点击事件)
qqmapsdk.getSuggestion({keyword: inputData,region: cityName,success: function (res) {let searchData = res.dataconsole.log(searchData);that.setData({searchPlace: searchData})},fail: function (res) {console.log(res);},complete: function (res) {console.log(res);}});
点击所选地名进行地名的坐标存储
placeChoose: function (options){//console.log(options)let location = options.currentTarget.dataset.locationwx.setStorageSync('location', location)console.log(wx.getStorageSync('location'))wx.navigateBack({// 返回的页面数data: 1})}
进行线路规划(画路线)
//前往搜索地goSearchPlace: function(){let that = thislet searchLat = wx.getStorageSync('location').latlet searchLon = wx.getStorageSync('location').lngwx.request({url: 'https://apis.map.qq.com/ws/direction/v1/driving/?from=24.488476,118.096247&to=' + searchLat + ',' + searchLon + '&output=json&callback=cb&key=22VBZ-REEK5-WVSI7-QKCOP-QPM6E-W7BPO',success: function (res) {coors = res.data.result.routes[0].polylinefor (var i = 2; i < coors.length; i++) {coors[i] = coors[i - 2] + coors[i] / 1000000}console.log(coors)that.project()}})}
画线路函数我单独抽出来
project: function(){var b=[]for (var i=0;i){b[i / 2] = {latitude: coors[i], longitude: coors[i + 1]}console.log(b[i / 2])}console.log(b.length)that2.setData({polyline: [{points: b,color: "#9999FF",width: 4,dottedLine: false}]})}