1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- // utils/location.js
- const location = {
- /**
- * 获取地理位置(跨平台统一 Promise 版本)
- * @param {Object} options
- * type: 'wgs84' | 'gcj02' (默认 wgs84)
- * text: 授权提示文案 (默认 '需要获得您的位置,请您授权')
- * @returns {Promise} res: { latitude, longitude, speed, accuracy, ... }
- */
- get(options = {}) {
- const type = options.type || 'wgs84';
- const text = options.text || '需要获得您的位置,请您授权';
- return new Promise((resolve, reject) => {
- const doGet = () => {
- uni.getLocation({
- type,
- altitude: true,
- success(res) {
- resolve(res);
- },
- fail(err) {
- reject(err);
- }
- });
- };
- // H5 平台
- // #ifdef H5
- if (!navigator.geolocation) {
- reject({
- errMsg: '浏览器不支持定位'
- });
- return;
- }
- doGet();
- // #endif
- // App / 小程序平台
- // #ifndef H5
- uni.getSetting({
- success(res) {
- if (res.authSetting['scope.userLocation']) {
- doGet();
- } else {
- uni.authorize({
- scope: 'scope.userLocation',
- success() {
- doGet();
- },
- fail() {
- uni.showModal({
- title: '提示',
- content: text,
- showCancel: false,
- confirmText: '去授权',
- success() {
- uni.openSetting({
- success(setRes) {
- if (setRes.authSetting[
- 'scope.userLocation'
- ]) {
- doGet();
- } else {
- reject({
- errMsg: '用户未授权定位'
- });
- }
- },
- fail(err) {
- reject(err);
- }
- });
- }
- });
- }
- });
- }
- },
- fail(err) {
- reject(err);
- }
- });
- // #endif
- });
- }
- };
- export default location;
|