微信公众号获取地理位置
uniapp转h5
用户一进入首页就需要获取当前地理位置,
1.
//引入jssdk
const wx = require('../../static/utils/jweixin-module@1.4.1.js')
//调用函数
getSingure(){
app.httpRequest({
url:'getuser/getSignPackage',
method:'POST'
},{}).then(res=>{
console.log(res,"====>获取后台返回的appId,时间戳,随机字符串,数字签名")
wx.config({
debug: false,
appId: res.data.data.appId,
timestamp: res.data.data.timestamp,
nonceStr: res.data.data.noncestr,
signature: res.data.data.signature,
jsApiList: [
// 所有要调用的 API 都要加到这个列表中
'getLocation',
]
});
wx.ready(function(){
wx.checkJsApi({
jsApiList: [
'getLocation'
],
success: function (res) {
console.log(res,'checkJsApi');
// alert(JSON.stringify(res));
// alert(JSON.stringify(res.checkResult.getLocation));
if (res.checkResult.getLocation == false) {
alert('你的微信版本太低,不支持微信JS接口,请升级到最新的微信版本!');
return;
}
}
});
wx.error(function(res){
//alert("接口调取失败")
});
wx.getLocation({
success: function (res) {
//拿到经纬度存到本地
//uni.setStorageSync('lon',res.longitude);
//uni.setStorageSync('lat',res.latitude);
}, cancel: function (res) {
alert('用户拒绝授权获取地理位置');
}, complete:function(res){}
});
})
})
},
有时候getLoaction调取成功有时候是失败
2.
后台说他用php模板字符串就一直是好的,所以跟客户沟通需求说在首页前加一个登录页,将经纬度拼在a链接之后
//引入jssdk
<script src="__ADMIN__/js/jweixin-module@1.4.1.js"></script>
<script>
var latitude,longitude;
wx.config({
debug: false,
appId: '<?php echo $signPackage["appId"]; ?>',
timestamp: '<?php echo $signPackage["timestamp"]; ?>',
nonceStr: '<?php echo $signPackage["nonceStr"]; ?>',
signature: '<?php echo $signPackage["signature"]; ?>',
jsApiList: [
'getLocation',
] // 必填,需要使用的JS接口列表
});
wx.ready(function() {
wx.checkJsApi({
jsApiList: [
'getLocation'
],
success: function(res) {
// alert(JSON.stringify(res));
// alert(JSON.stringify(res.checkResult.getLocation));
if (res.checkResult.getLocation == false) {
alert('你的微信版本太低,不支持微信JS接口,请升级到最新的微信版本!');
return;
}
}
});
wx.error(function(res) {
alert("接口调取失败")
});
wx.getLocation({
success: function(res) {
latitude = res.latitude,longitude = res.longitude;
},
cancel: function(res) {
alert('用户拒绝授权获取地理位置');
}
});
document.getElementById('button').onclick = function(){
//跳往至真的首页
window.location.href = "https://baidu.com?latitude="+latitude+'&longitude='+longitude;
}
});
</script>
//然后在index.vue中接收
getPosition(){
let url = location.search;
var newArr = [],newObj={
latitude:'',
longitude:''
}
let aurl = url.substr(1);
newArr = aurl.split('&');
newObj.latitude = newArr[0].split('=')[1];
newObj.longitude = newArr[1].split('=')[1]
uni.setStorageSync('locationObj',newObj);
}
我用的是第二种方法.