const requestLocation = () => {
uni.getLocation({
success: (res) => {
vdata.lng = res.longitude;
vdata.lat = res.latitude;
console.log(vdata);
uni.showToast({
title: '位置获取成功',
icon: 'none'
});
},
fail: (err) => {
uni.showToast({
title: '位置获取失败',
icon: 'none'
});
console.error('获取位置失败: ', err);
}
});
};
const getCurrentLocation = () => {
// #ifdef APP-PLUS
console.log('APP环境');
checkPermission();
// #endif
// #ifdef H5 || MP-WEIXIN
console.log('MP-WEIXIN环境');
wxcheckPermission();
// #endif
console.log(process.env.NODE_ENV, 'process.env.NODE_ENV');
};
const checkPermission = () => {
// 检查权限
const locationManager = plus.android.importClass('android.location.LocationManager');
const Context = plus.android.importClass('android.content.Context');
const main = plus.android.runtimeMainActivity();
const lm = main.getSystemService(Context.LOCATION_SERVICE);
if (!lm.isProviderEnabled(locationManager.GPS_PROVIDER)) {
uni.showModal({
title: '提示',
content: '请在系统设置中打开GPS定位服务',
showCancel: false
});
return;
}
plus.navigator.requestPermission(
'ACCESS_FINE_LOCATION',
(result) => {
if (result === 'granted') {
requestLocation();
} else {
uni.showModal({
title: '提示',
content: '需要获取您的地理位置,请到设置页面打开授权',
success: (res) => {
if (res.confirm) {
// 引导用户打开设置页面
plus.runtime.openSystemSetting();
}
}
});
}
},
(error) => {
console.error('Request permission error: ', error);
}
);
};
const wxcheckPermission = () => {
uni.getSetting({
success: (res) => {
if (res.authSetting['scope.userLocation'] !== undefined && !res.authSetting['scope.userLocation']) {
// 用户之前拒绝了位置权限
uni.showModal({
title: '授权提示',
content: '需要获取您的地理位置,请到设置页面打开授权',
success: (res) => {
if (res.confirm) {
uni.openSetting({
success: (res) => {
if (res.authSetting['scope.userLocation']) {
// 用户重新授权,获取位置
requestLocation();
}
}
});
}
}
});
} else if (res.authSetting['scope.userLocation'] === undefined || res.authSetting['scope.userLocation']) {
// 用户已经授权或首次授权,直接获取位置
requestLocation();
}
}
});
};
同时兼容小程序和app获取经纬度
最新推荐文章于 2024-11-16 14:33:00 发布