Skip to content

地理位置

位置授权

js
// 检查并请求地理位置权限
async function checkAndRequestLocationPermission() {
    try {
        const settingRes = await new Promise((resolve) => {
            uni.getSetting({
                success: resolve,
            });
        });

        // 如果用户未开启地理位置权限
        if (!settingRes.authSetting['scope.userLocation']) {
            const modalRes = await new Promise((resolve) => {
                uni.showModal({
                    title: '开启获取地理位置',
                    content: '请打开"位置信息"权限,找到附近的店铺',
                    success: resolve,
                });
            });

            // 用户点击确认后,打开设置页面
            if (modalRes.confirm) {
                const openSettingRes = await new Promise((resolve) => {
                    uni.openSetting({
                        success: resolve,
                    });
                });

                // 如果用户在设置中开启了地理位置权限
                if (openSettingRes.authSetting['scope.userLocation']) {
                    return true; // 权限已开启
                }
            }
        } else {
            return true; // 权限已经开启
        }
    } catch (error) {
        console.error('检查地理位置权限失败:', error);
    }

    return false; // 权限未开启
}

// 获取地理位置并加载店铺数据
async function getLocationAndLoadShops(context) {
    try {
        const hasPermission = await checkAndRequestLocationPermission();

        if (hasPermission) {
            const locationRes = await new Promise((resolve, reject) => {
                uni.getLocation({
                    type: 'gcj02',
                    success: resolve,
                    fail: reject,
                });
            });

            context.lng = locationRes.longitude;
            context.lat = locationRes.latitude;

            // 加载店铺数据
            const shopData = await new Promise((resolve, reject) => {
                context.getShop({
                    page: 1,
                    lng: context.lng,
                    lat: context.lat,
                    success: (pageNum) => resolve(pageNum),
                    fail: reject,
                });
            });

            context.maxPage = shopData;
        }
    } catch (error) {
        console.error('获取地理位置或加载店铺数据失败:', error);
    }
}

// 调用入口
getLocationAndLoadShops(this);

获取位置

js
uni.getLocation({
    type: 'gcj02',
    success:  (res)=> {
        this.lng=res.longitude;
        this.lat=res.latitude;
        this.getShop({page:1,lng:this.lng,lat:this.lat,success:(pageNum)=>{
                this.maxPage=pageNum;
            }
        });
    }
});