taro 获取经纬度及城市

193 阅读1分钟
app.config.js 权限设置
export default {
    ...,
    permission: {
        'scope.userLocation': {
            desc: '需要获取您的位置信息为您推荐合适的工作岗位'
        }
    },
   ...
};
import { getSetting, authorize } from '@tarojs/taro';

/**
 * 百度定位
 * @returns
 */
const getMap = () => {
    return new Promise((reslove, reject) => {
    	// https://github.com/baidumapapi/wxapp-jsapi/blob/master/src/bmap-wx.min.js
        const bmap = require('@/assets/js/bmap-wx.min.js');
        const BMap = new bmap.BMapWX({
            ak: ''
        });
        BMap.regeocoding({
            fail: (data) => {
                reject(data);
            },
            success: (data) => {
                const {
                    originalData: {
                        result: {
                            location,
                            addressComponent: { city }
                        }
                    }
                } = data;
                reslove({ location, city });
            }
        });
    });
};
/**
 * 查看用户授权
 * @returns
 */
getSetting({
   success: function (res) {
        if (!res.authSetting['scope.userLocation']) {
            authorize({
                scope: 'scope.userLocation',
                success: async () => {
                    console.log('授权成功');
                    const { location, city } = await getMap();
                    console.log(location, city)
                },
                fail(err) {
                    //err
                }
            });
        } else {
            getMap().then(({ location, city }) => {
                console.log(location, city)
            });
        }
    }
});