[개요] 프로그램 포장 방법에 대한 중요하다, 시간을 많이 저장, 작업 부하를 줄일 수 있습니다 또한 프로그램의 볼륨을 줄일 수 있지만 아닙니다.
[실시 예 1] 요청 권한 체크 (단일 콜백)
코드 : Util.js에서 쓰기, 당신은 같은 방법의 module.exports을 추가해야합니다 :
module.exports = {
formatTime: formatTime,
checkPermisson:checkPermisson,
getPermission: getPermission,
openSetting: openSetting,
getAddress:getAddress
}
/**检查是否获得权限 */
function checkPermisson(obj,callback) {
wx.getSetting({
success(res) {
if (!res.authSetting[obj]) {
return typeof callback == "function" && callback(false);
}else{
return typeof callback == "function" && callback(true);
}
}
})
}
/**获取权限 */
function getPermission(per){
wx.authorize({
scope: per,
success() {
return typeof callback == "function" && callback(true);
},fail(res){
console.log(res)
return typeof callback == "function" && callback(false);
}
})
}
말했다 : checkPermisson 일회용, 팝업 권한 요청을 확인 필요한 모든 권한을 추가하여 원 추가되지 않았습니다 만, 애플릿 요청 된 사용자 정보가 자동으로 팝업되지 않기 때문에 검사의 권한은 별도로 허가를 요청하는 경우 직접 반환 참 또는 거짓 그렇게 그것은 할 수 있습니다.
위의 방법을 사용하여 :
//获取用户信息
util.checkPermisson("scope.userInfo", function (res) {
if (!res) {
console.log("未授权获取用户信息")
//显示用户信息权限请求
that.setData({
info_per:false
})
}else{
console.log("已经获取用户权限")
}
});
[실시 예 2], 지리적 좌표 및 위치 정보 취득 요구 (전달 함수 콜백)
설명 : 작은 애플릿 프로그램이 좌표 API를 장비를 얻을 수 있습니다, 당신이 그것을 얻을 싶어이 같은 다른 지리적 설명을 통해 : 높은 독일어, 탕 쑤, 바이두는 취득 법 먼저 지리적 좌표를 획득 설명 있도록 API를 매핑 getAddress에 다음 설명의 위치를 취득
//腾讯地图api
var QQMapWX = require('./qqmap-wx-jssdk.min.js');
// 实例化API核心类
var demo = new QQMapWX({
key: 'RT2BZ-ZD2KK-C35JO-****-WZFLH-SYBKB' // 必填
});
/**获取地理坐标 */
function getAddress(callback){
wx.getLocation({
type: 'wgs84',
success(res) {
const latitude = res.latitude
const longitude = res.longitude
return retrunAddress(latitude, longitude,callback);
}
})
}
/**根据坐标获得位置描述 */
function retrunAddress(latitude,longitude,callback){
demo.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
console.log(res);
return typeof callback == "function" && callback(res);
}
})
사용 방법 :
//获取用户地理位置
util.checkPermisson("scope.userLocation", function (res) {
if (res) {
// console.log("以获取位置")
util.getAddress(function (callback){
// console.log(callback)
var add = callback.result.address_component.district + callback.result.address_component.street_number;
var mHeader = that.data.header;
mHeader.address = add;
// console.log(mHeader)
that.setData({
header:mHeader
})
})
} else {
util.getPermission("scope.userLocation",function (res){
if(!res){
wx.showToast({
title: '请打开设置页面',
})
util.openSetting()
}else{
}
});
}
})