uniAPP地图选点+导航功能

1,850 阅读3分钟

1.首先配置地图功能

配置使用的地图和对应的key(我需要打包H5和wx小程序),具体配置如下:

image.png

image.png

image.png

检测用户是否打开定位权限

我是提成一个文件,用的时候直接掉,避免很多地方要用这个方法.

/**
 * 地图授权检测
 * @returns 
 */
const siteAthor=()=>{
    return new Promise((resolve,reject)=>{
		uni.getSetting({
			success:(res)=>{
                // 表示 初始化进入,从未授权
				if( res.authSetting['scope.userLocation'] === undefined){
					return resolve(true);
                // 表示 已授权
				}else if(res.authSetting['scope.userLocation'] === true){
					return resolve(true);
                // 表示 授权拒绝
				}else if(res.authSetting['scope.userLocation'] === false){
                    uni.showModal({
                        content: '检测到您没打开获取位置权限,是否去设置打开?',
                        confirmText: "确认",
                        cancelText: '取消',
                        success: (res) => {
                            if (res.confirm) {
                                uni.openSetting({
                                    success: (res) => {
                                        // uni.showToast({
                                        //     title: '授权后将重新打开此页面',
                                        //     icon: 'none',
                                        // })
                                    },
                                    fail: (err) => {
                                        console.log(err)
                                    }
                                })
                            } else {
                                uni.showToast({
                                    title: '获取授权位置授权失败,请手动打开位置权限',
                                    icon: 'none',
                                })
                            }
                        }
                    })
					return resolve(false)
				}
			}
		})
	})
};

/**
 * 地图授权
 * @returns 
 */
const getSetting=()=>{
    console.info("调用位置授权~")
    return new Promise(async (resolve,reject) =>{
        const resoult = await siteAthor();//授权检测,是否拒绝过授权;
        console.info("resoult",resoult);
        if(!resoult) return;//跳转到设置页面
        uni.getSetting({
            success: async(res) => {
                if (!res.authSetting['scope.userLocation']) {
                    console.log(res)
                    uni.authorize({
                        scope: 'scope.userLocation',
                        success: async() => { //1.1 允许授权
                            const res = await getNowSite();
                            resolve(res);
                        },
                        fail:()=> { //1.2 拒绝授权
                            uni.showToast({
                                title: '用户拒绝位置授权,位置会发生偏差',
                                icon: 'none',
                            })
                            resolve(false);
                        }
                    })
                } else {
                    const res = await getNowSite();
                    resolve(res);
                }
            }
        })
    })
}

/**
 * 获取经纬度
 * @returns 
 */
const getNowSite=()=>{
    return new Promise(async (resolve,reject) =>{
    uni.getLocation({
        type: 'wgs84',
        altitude:true,
        isHighAccuracy:true,
        success: (res) =>{
            console.log('当前位置的经度:' + res.longitude);
            console.log('当前位置的纬度:' + res.latitude);
            const {longitude,latitude} =res||{};
            if(longitude&&latitude){
                return resolve(res);
                // this.punctuationBits(latitude,longitude,"当前位置",0);
            }else{
                uni.showToast({
                    title: '获取定位失败,请查看是否打开手机定位权限',
                    icon: 'none',
                })
                resolve({});
            }
        },
        fail:(fail)=>{
            console.info("获取定位失败",fail)
            // uni.showToast({
            //     title: '获取定位失败,请查看是否打开手机定位权限',
            //     icon: 'none',
            // })
            resolve({});
        },
    });
    })
}

export default getSetting;

获取我当前位置

//引入上面的权限方法,具体路径要根据你实际的更改
import siteAthor from '../utils/siteAthor.js'
async mounted() {
    const { latitude, longitude } = await siteAthor();
    if (latitude && longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
        this.punctuationBits(latitude, longitude, "我的位置", 0);//点位配置(不配置地图,展示不出来,代码在下面)
    }
}

引入地图标签

<template>
     <map style="width: 100%; height: 100%;" :latitude="latitude" :longitude="longitude" :markers="covers" :id="id" @markertap="openMap" @callouttap='openMap'></map>
</template>
//数据
data() {
    return {
        id: 1, // 使用 marker点击事件 需要填写id
        latitude:'',
        longitude:'',
        covers: [],
    }
}
       

/**
 * 选择点详情
 * @param {*} pointInfo 
 */
openMap(pointInfo) {
//代码在下边
},

点击导航到某个点代码



/**
 * 选择点详情
 * @param {*} pointInfo 
 */
openMap(pointInfo) {
    if (this.covers.length > 0 && pointInfo) {
        const { latitude, longitude, targetInfo, id, title } = this.covers[pointInfo.markerId];
        if (pointInfo.markerId === 0) return;
         uni.openLocation({
             latitude:Number(latitude),//要去的纬度-地址
             longitude:Number(longitude),//要去的经度-地址
             name:targetInfo.name,//地址名称
             address:targetInfo.address,//要去的具体地址
             //此处踩坑的问题.latitude 和 longitude的值一定要是number类型。所以传递的时候需要使用Number将其转换一下。
         })
    }
},

点位展示配置

多个点位可以循环数据调用这个方法,但是id要保证唯一性.

    /**
    * 地图标点
    * @param {*} latitude 维度
    * @param {*} longitude 经度
    */
    punctuationBits(latitude, longitude, labelName, id, address = "") {
        let item = {
            id,
            checkedId: id,
            markerIndex: id,
            latitude,
            longitude,
            with: 10,
            height: 30,
            title: labelName,
            iconPath: '../static/tab_site.png',//展示的图标
            // 点击获取到的标点信息
            targetInfo: {
                labelName,
                address
            },
            callout: { //自定义标记点上方的气泡窗口 点击有效  
                content: labelName, //文本
                color: '#ffffff', //文字颜色
                fontSize: 15, //文本大小
                borderRadius: 15, //边框圆角
                padding: '10',
                bgColor: '#3F59F4', //背景颜色
                display: 'ALWAYS', //常显
            }
        };
        // 重新获取当前定位后,删除原来的位置信息
        if (id === 0 && this.covers.length > 0 && this.covers[0].id === 0) {
            this.covers.shift(item);
        }
        // 当前位置放在第一个
        id === 0 ? this.covers.unshift(item) : this.covers.push(item);
        this.latitude = latitude;
        this.longitude = longitude;
        // console.info("点位列表",this.covers)
    },

具体效果展示

获取我当前位置

image.png

导航到那里呀?(吐车两百 🐶)

image.png

小结

日常工作的记录,代码写了很久了.终于有时间记录一下了~

有不妥之处,希望大佬指正.

单纯记录一下~