微信小程序使用腾讯定位服务api获取经纬度后调取导航功能
程序员文章站
2022-04-18 08:25:42
...
腾讯定位服务官网申请key
申请key: https://lbs.qq.com/dev/console/key/add
签名效验文档: https://lbs.qq.com/FAQ/server_faq.html#3
地址解析api文档:https://lbs.qq.com/service/webService/webServiceGuide/webServiceGeocoder
1.申请key
申请key: https://lbs.qq.com/dev/console/key/add
2.效验签名
签名效验文档: https://lbs.qq.com/FAQ/server_faq.html#3
注意:对参数进行排序:按参数名升序(按照参数首字母进行排序)
比如:接口参数为address、key,那么拼接时address在前,key在后
sig = md5("/ws/geocoder/v1?address=address&key=keysk");
调用代码(php)
//定位服务
public function getLocation(){
$address = input('post.address');
$key='腾讯定位服务申请的key';
$sk = 'Key设置里的Secret key( SK )';
//这里用的是地址解析api,获取指定地址经纬度
$sig = md5("/ws/geocoder/v1?address=$address&key=$key".$sk);
$url = 'https://apis.map.qq.com/ws/geocoder/v1?address='.$address.'&key='.$key.'&sig='.$sig;
$weixin = file_get_contents($url);
$jsondecode = json_decode($weixin);
$array = get_object_vars($jsondecode);
return output_data(200,$array);
}
小程序端
wxml
<button bindtap="location" data-address="北京市海淀区彩和坊路海淀西大街74号">开启导航</button>
js
location: function(e){
var address = e.currentTarget.dataset.address;
var name = '店铺名称';
var that = this;
wx.getLocation({
success: function(res){ //用户授权成功
that.locationApi(address,name);
},
fail: function(err){
//用户未授权
wx.getSetting({
success: function (res) {
var statu = res.authSetting;
if (!statu['scope.userLocation']) {
wx.showModal({
title: '是否授权当前位置',
content: '需要获取您的地理位置,请确认授权,否则地图功能将无法使用',
success: function (tip) {
if (tip.confirm) {
//打开用户授权
wx.openSetting({
success: function (data) {
if (data.authSetting["scope.userLocation"] === true) {
wx.showToast({
title: '授权成功',
icon: 'success',
duration: 1000
})
wx.getLocation({
success(res) {
that.locationApi(address,name);
},
});
} else {
wx.showToast({
title: '授权失败',
icon: 'success',
duration: 1000
})
}
}
})
}else{
}
}
})
}
},
fail: function (res) {
wx.showToast({
title: '调用授权窗口失败',
icon: 'success',
duration: 1000
})
}
})
}
})
},
//调用定位服务api
locationApi: function(address,name){
app.getAjax('index/api/getLocation',{address:address},function(res){
// console.log(res);
var lat = res.data.data.result.location.lat;
var lng = res.data.data.result.location.lng;
wx.openLocation({
latitude: lat,
longitude: lng,
name:name,
address:address
})
});
}
上一篇: Java面试题(持续更新中。。。)