复杂:getCityByCheck
- 首次检查权限,没有权限则弹出系统定位提示框;
- 非首次查询权限,权限为拒绝后则弹出确认框,确定->去设置页面,返回简单查询结果,不确定->返回'';
- 有权限-> 简单查询结果。
简单: getCity
- 获取经纬度之后地址逆解析。
const checkLocation = () => {
return new Promise((resolve, reject) => {
wx.getSetting({
success:(res) => {
if (res.authSetting['scope.userLocation']== false) {
resolve(false);
} else {
wx.authorize({
scope: 'scope.userLocation',
success:() => {
resolve(true);
},fail:() => {
reject();
}
})
}
}
})
})
}
const openSetting = (content = '请打开定位,以显示当前城市可配送商品!') => {
return new Promise((resolve) => {
wx.showModal({
title: '提示',
content: content,
showCancel: true,
cancelText: '取消',
cancelColor: '#000000',
confirmText: '确定',
confirmColor: '#3CC51F',
success: res => {
if (res.confirm) {
wx.openSetting({
success() {
res.authSetting = { "scope.userLocation": true };
resolve(true);
},
fail() {
resolve(false)
}
})
} else if (res.cancel) {
resolve(false);
}
}
});
});
};
const getLocation = () => {
return new Promise((resolve, reject) => {
wx.getLocation({
type: 'wgs84',
success(res) {
resolve(res);
},
fail(err) {
reject(err)
}
})
})
};
const getCityByLocation = (location) => {
return new Promise ((resolve,reject)=>{
wx.request({
url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${location.latitude},${location.longitude}&key=LIMBZ-LTCWU-U65VE-2L5SW-N54I7-X6FAW`,
header: {
'content-type': 'application/json'
},
success(res) {
resolve(res.data.result.address_component.city);
},
fail() {
resolve('');
}
})
})
};
const getCity = () => {
return getLocation().then((res) => {
return getCityByLocation(res);
}).catch(() => {
return ''
});
};
const getCityByCheck = (content = '定位') => {
return new Promise((resolve) => {
checkLocation().then((locationRole) => {
if (locationRole) {
getCity().then((res) => {
resolve(res);
});
} else {
openSetting(content).then((openSetting) => {
if (openSetting) {
getCity().then((res) => {
resolve(res);
});
} else {
resolve('');
}
})
}
}).catch(() => {
resolve('');
})
})
}
module.exports = {
checkLocation,
openSetting,
getLocation,
getCityByLocation,
getCity,
getCityByCheck
}