這兩天在看小程序的地圖,寫寫筆記記錄一下
小程序官方文檔提供的幾種位置方法
小程序的官方文檔也有提供幾個方法(這幾個方法很簡單,看看就知道了),但是一般都滿足不了~~
騰訊地圖提供的jssdk
根據提示使用騰訊地圖jssdk需要申請,在實例化的時候填入密匙,接下來就可以使用他提供的各種方法了
我先說說我做關鍵詞搜索和點擊搜索結果進行路線規劃(規劃目前可能只是按自駕的路線,不完善的地方麻煩大家賜教了)
搜索我先使用getLocation獲取當前位置座標
wx.getLocation({
type: 'wgs84',
success: function (res) {
latitude = res.latitude
longitude = res.longitude
var speed = res.speed
var 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.city
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
console.log('獲取當前城市完成');
}
})
然後調用getSuggestion方法進行當前城市的關鍵詞搜索顯示功能(將獲取到的關鍵詞循環顯示在搜索下面,給便利出來的每個選項加個點擊事件)
qqmapsdk.getSuggestion({
keyword: inputData,
region: cityName,
success: function (res) {
let searchData = res.data
that.setData({searchPlace: searchData})
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
console.log(res);
}
});
點擊所選地名進行地名的座標存儲
placeChoose: function (options){
let location = options.currentTarget.dataset.location
wx.setStorageSync('location', location)
wx.navigateBack({
// 返回的頁面數
data: 1
})
}
進行線路規劃(畫路線)
//前往搜索地
goSearchPlace: function(){
let that = this
let searchLat = wx.getStorageSync('location').lat
let searchLon = wx.getStorageSync('location').lng
wx.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].polyline
for (var i = 2; i < coors.length; i++) {
coors[i] = coors[i - 2] + coors[i] / 1000000
}
that.project()
}
})
}
畫線路函數我單獨抽出來
project: function(){
var b=[]
for (var i=0;i<coors.length;i=i+2){
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
}]
})
}