1、经常无法获取经纬度
2、如果定位了,无论成功与否,皆会导致定位之后,所有联网的图片无法加载(就好像被定位阻塞了)
那么只能使用微信js-sdk的定位方法了。
安装
1、因为uni-app如果没有使用npm的方法,根目录就没有package.json,首先在项目根目录运行
npm init如果已经有package.json,直接进入下一步
2、安装jweixin-module
npm i jweixin-module -S此外,您也可以直接下载:https://unpkg.com/jweixin-module@1.4.1/out/index.js
使用
1、在您的js公共文件夹下创建wechat.js
import Vue from "vue";
var jweixin = require('jweixin-module');
export default {
//调试模式
debug:false,
//权限
jsApiList:[
'getLocation'
],
//判断是否在微信中
isWechat: function() {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/micromessenger/i) == 'micromessenger') {
return true;
} else {
return false;
}
},
//初始化sdk配置
initJssdk: function(callback, url) {
if (!this.isWechat()) {return;}
//服务端进行签名 ,可使用uni.request替换。 签名算法请看文档
Vue.prototype.$func.api(Vue.prototype.$apiConfig.wxjssdk(),{
url:url || location.href.split('#')[0],
},res => {
jweixin.config({
debug: res.debug || this.debug,
appId: res.appId,
timestamp: res.timestamp,
nonceStr: res.nonceStr,
signature: res.signature,
jsApiList: res.jsApiList || this.jsApiList
});
//配置完成后,再执行分享等功能
if (typeof callback === 'function') {
callback(res.data);
}
})
},
//准备就绪
ready:function(callback, url)
{
if (!this.isWechat()) {return;}
this.initJssdk(function(){
jweixin.ready(function() {
//配置完成后,再执行
if (typeof callback === 'function') {
callback(jweixin);
}
})
}, url)
},
closeWindow:function() {
this.ready(function(wx) {
wx.closeWindow();
})
},
//在需要定位页面调用
location: function(success, fail) {
this.ready(function(wx) {
wx.getLocation({
type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
if (typeof success === 'function') {
success(res);
}
},
fail:function(res){
if (typeof fail === 'function') {
fail(res);
}
}
});
});
}
}
2、main.js加载该文件,这样就可以全局使用wechat.js了
// #ifdef H5 import wechat from './static/js/wechat.js'; Vue.prototype.$wechat = wechat; // #endif3、页面中使用
// #ifdef H5
//获取定位经纬度
const that = this;
if (this.$wechat && this.$wechat.isWechat()) {
this.$wechat.location(function (res) {
that.latitude = res.latitude; //纬度
that.longitude = res.longitude; //经度
});
}
// #endif
至此,定位总算解决了!