微信小程序 封装获取定位

//获取定位
export function location() {
	return new Promise((resolve, reject) => {
		if (vuex.state.userLocation) {
			resolve(vuex.state.userLocation)
		}
		uni.getLocation({
			type: 'gcj02',
			success: function(res) {
				let userLocation = {
					longitude: res.longitude, //当前位置的经度
					latitude: res.latitude //当前位置的纬度
				}
				vuex.commit('userLocation', userLocation)
				resolve(userLocation)
		
			},
			fail: function(res) {
				checkUserLocation(() => {
					uni.getLocation({
						type: 'gcj02',
						success: function(res) {
							let userLocation = {
								longitude: res.longitude, //当前位置的经度
								latitude: res.latitude //当前位置的纬度
							}
							vuex.commit('userLocation', userLocation)
							resolve(userLocation)
					
						}
					});
				})
			}
		});


	})
}

//给用户重新授权弹窗
const checkUserLocation = function() {
	uni.getSetting({
		success(res) {
			if (!res.authSetting.hasOwnProperty('scope.userLocation')) {
				uni.authorize({
					scope: 'scope.userLocation',
					success() {
						if (typeof callback == 'function') {
							callback();
						}
					},
					fail: function() {
						checkUserLocation();
					}
				})
			} else if (res.authSetting.hasOwnProperty('scope.userLocation') && !res.authSetting[
					'scope.userLocation']) {
				uni.showModal({
					title: '请授权地理定位否则无法为您服务',
					content: '',
					cancelText: '暂不开启',
					confirmText: '开启授权',
					confirmColor: '#FF9E57',
					success: function(tip) {
						if (tip.confirm) {
							uni.openSetting({
								success: function(data) {
									if (typeof callback == 'function') {
										callback();
									}
								},
								fail: function() {
									checkUserLocation();
								}
							})
						} else {
							callback();
							// checkUserLocation();
						}
					},
				})
			} else {
				if (typeof callback == 'function') {
					callback();
				}
			}
		},
		fail: function() {
			checkUserLocation();
		}
	})
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值