1. 引入jssdk
在需要調用JS接口的頁面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.6.0.js
如需進一步提升服務穩定性,當上述資源不可訪問時,可改訪問:http://res2.wx.qq.com/open/js/jweixin-1.6.0.js (支持https)。
備註:支持使用 AMD/CMD 標準模塊加載方法加載
//安裝
npm install weixin-js-sdk --save
//引入
import wx from 'weixin-js-sdk';
2. 通過config接口注入權限驗證配置
第一步:獲取當前頁面的url( 作爲請求接口的參數,從後臺換取 config 驗證配置的參數值 )
第二步:檢查當前微信版本是否支持指定 JS 接口,支持批量判斷
第三步:引入獲取地理位置 API ( 獲取經緯度:wx.getLocation() 打開地圖:wx.openLocation() )
getLoationInfo(){ //獲取門店
var that = this;
var _url = window.location.href;
Api.ajax({
key: "getSignatureUrl",
type: "GET",
data: {
url:_url
}
}).then(res => {
wx.config({
debug: false, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
appId: res.appId, // 必填,公衆號的唯一標識
timestamp: res.timestamp, // 必填,生成簽名的時間戳
nonceStr: res.nonceStr, // 必填,生成簽名的隨機串
signature: res.signature,// 必填,調用js簽名,
jsApiList: ['checkJsApi','getLocation', 'openLocation','hideOptionMenu'] // 必填,需要使用的JS接口列表,這裏只寫支付的
});
wx.ready(function(){
// 1 判斷當前版本是否支持指定 JS 接口,支持批量判斷
wx.checkJsApi({
jsApiList : [ 'getLocation' ],
success : function(res) {
// 以鍵值對的形式返回,可用的api值true,不可用爲false// 如:{"checkResult":{"getLocation":true},"errMsg":"checkJsApi:ok"}
if (res.checkResult.getLocation == false) {
alert('你的微信版本太低,不支持微信JS接口,請升級到最新的微信版本!');
return;
}
}
});
wx.getLocation({
type: 'wgs84',
success: function (res) {
var latitude = res.latitude; // 緯度,浮點數,範圍爲90 ~ -90
var longitude = res.longitude ; // 經度,浮點數,範圍爲180 ~ -180。
console.log(latitude,longitude)
//打開地圖 (經緯度爲要到達位置的經緯度信息)
wx.openLocation({
latitude: Number(this.latitude), // 緯度,浮點數,範圍爲90 ~ -90
longitude: Number(this.longitude), // 經度,浮點數,範圍爲180 ~ -180。
name: storeDetail.storeName, // 位置名
address: storeDetail.storeAddress, // 地址詳情說明
scale: 16, // 地圖縮放級別,整形值,範圍從1~28。默認爲最大
infoUrl: '' // 在查看位置界面底部顯示的超鏈接,可點擊跳轉
});
},
cancel:function(res){
// alert('獲取當前位置失敗',res);
// console.log(res)
}
});
})
},res => {
// console.log(res)
});
}