vue3+uniapp中使用高德地图实现撒点效果
前言:
vue3+uniapp中使用高德地图实现撒点效果
实现效果:
操作步骤:
1、引入高德插件,并生成js配置插件,详情步骤请点我
import amapFile from '../../libs/amap-wx.js'
2、页面上配置我们的map标签
<template><!-- 地图控件 --><view><map id="map" :longitude="mapObj.longitude" :latitude="mapObj.latitude" :scale="mapObj.scale" :markers="mapObj.markers"@markertap="markertap"@click="mapClick"></map></view>
</template>
3、js部分,定义我们相关变量
let mapObj = reactive({longitude:116.481028, //经度latitude:39.989643, //维度scale:17, //地图默认缩放等级markers: [], //点位数据})let locationListener = ref('')let initMap = function(){const myAmapFun = new amapFile.AMapWX({key: 'bb****', // 你的高德地图API Key});console.log('myAmapFun',myAmapFun)}onShow(()=>{initMap()initMapWZ()})
4、获取我们当前位置
// 获取当前位置信息let initMapWZ = function(){console.log('init')// uni.getLocation uniapp官网提供的获取定位的方法,调用过多会导致无法使用,需要使用监听方法uni.getLocation({type: 'gcj02', //国测局坐标 gcj02,要使用地图map必须使用这个success: res=> {getNowDWBackFun(res)},fail:err=>{//getLocation:fail 频繁调用会增加电量损耗,可考虑使用 wx.onLocationChange 监听地理位置变化console.log(err)startLocationWatch()},complete:()=>{console.log('complete')}})}
5、更新我们当前实时位置
let startLocationWatch = ()=> {// 1. 检查权限uni.authorize({scope: 'scope.userLocation',success: () => {// 2. 开启位置更新uni.startLocationUpdate({success: () => {// 3. 监听位置变化locationListener = uni.onLocationChange((res) => {// 在此更新地图或处理位置数据getNowDWBackFun(res)})},fail: (err) => {console.error('启动位置更新失败:', err)}})},fail: () => {uni.showModal({title: '权限提示',content: '需要位置权限以持续获取位置',success: (res) => {if (res.confirm) uni.openSetting()}})}})}
6、将我们当前位置,用图片展示在地图上
// 拿到当前最新位置以后的回调方法let getNowDWBackFun = res=>{console.log('当前位置的经度:' + res.longitude);console.log('当前位置的纬度:' + res.latitude);mapObj.longitude = res.longitudemapObj.latitude = res.latitudemapObj.markers = [{id: 1,longitude:res.longitude,latitude: res.latitude,iconPath: '../../static/now.png',title: '当前位置',width:25,height:25}]}
7、当我们的界面关闭时候,停止我们的实时更新位置方法
// 停止监听let stopLocationWatch = ()=>{if (locationListener.value) {uni.stopLocationUpdate() // 停止位置更新}}onHide(()=>{stopLocationWatch()})