vue3使用高德地图,自定义点标记、默认点聚合样式、点击点标记获取信息
作者:心若向阳(* ̄︶ ̄)
vue3使用高德地图,自定义点标记、默认点聚合样式、点击点标记获取信息
1、需求:根据不用的类型和经纬度展示不同的自定义点标记,点标记太多,使用点聚合优化,参考:见文末补充介绍。
2、在index.html使用CDN引入高德
<script type="module" charset="UTF-8" src="https://webapi.amap.com/loader.js"></script>
3、组件中获取地图实例
父组件: <template> <div class=""> <div class=""> <div class="home-map"> <div class="map-box"> <div id="map-container"></div> </div> <site-info /> </div> </div> </div> <a-modal title="Title" v-model:visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" > <p>{{ modalText }}</p> </a-modal> </template> <script setup> import { onMounted, reactive, ref, toRaw, getCurrentInstance, watchEffect } from 'vue'; import { request } from '../../utils/request'; import { initMap, clickSite } from "../../utils/newMap"; import siteInfo from "./components/siteInfo.vue"; const globalProperties = getCurrentInstance().appContext.config.globalProperties; // 获取全局挂载 const http = globalProperties.$http; const toast = globalProperties.$toast; const visible = ref(false); const confirmLoading = ref(false); const modalText = ref(''); const conObj = reactive({ mapObj: {}, map: {}, markers: [], }) // 监听地图站点信息变量的值 watchEffect(() => { if(!toRaw(clickSite.siteInfo)) { } else { console.log(toRaw(clickSite.siteInfo)); visible.value = true; modalText.value = `你打开了id为${toRaw(clickSite.siteInfo).id}的点标记`; } }) // 弹窗确定按钮 const handleOk = () => { confirmLoading.value = true; setTimeout(() => { confirmLoading.value = false; visible.value = false; }, 1000); } const getMap = async(data) => { let map = await initMap(data) if(map) { conObj.map = toRaw(map).map; // 获取地图map实例 } } // 获取地图所有站点 const getSite = async () => { request(http.GET_HOME_HOME_ALL_SITE, 'get', { ownerUnit: 1 }) .then((res) => { toast("成功获取所有站点!"); conObj.markers = res.station; getMap(toRaw(conObj.markers)) }) .catch(() => { }) .finally(() => { }) } onMounted(async() => { await getSite(); }) </script> <style lang="less" scoped> .home-map { position: relative; height: calc(100vh - 52px); width: calc(100vw - 64px); .map-box { height: 100%; width: 100%; #map-container { width: 100%; height: 100%; } } } </style>
子组件: <template> <div class="site-info"> <div class="site-info-title" @click="$emit('bySonVal', 4692)"> 测站信息区域 </div> </div> </template> <script setup> defineEmits(['bySonVal']); // 使用defineEmits和defineProps不需要导入 </script> <style lang="less" scoped> .site-info { position: absolute; top: 0px; left: 0px; padding: .84rem; background: aquamarine; opacity: .8; .site-info-title { } } </style>
4、实例化地图
newMap.js // 新窨井 import inspInline from "@/assets/imgs/maps/insp_inline.png"; import inspOffline from "@/assets/imgs/maps/insp_offline.png"; import inspAlarm from "@/assets/imgs/maps/insp_alarm.png"; import inspWarn from "@/assets/imgs/maps/insp_warn.png"; // 新内涝 import waterLogInline from "@/assets/imgs/maps/waterLog_inline.png"; import waterLogOffline from "@/assets/imgs/maps/waterLog_offline.png"; import waterLogAlarm from "@/assets/imgs/maps/waterLog_alarm.png"; import waterLogWarn from "@/assets/imgs/maps/waterLog_warn.png"; // 新管网 import networkInline from "@/assets/imgs/maps/network_inline.png"; import networkOffline from "@/assets/imgs/maps/network_offline.png"; import networkAlarm from "@/assets/imgs/maps/network_alarm.png"; import networkWarn from "@/assets/imgs/maps/network_warn.png"; // 新闸门 import gateInline from "@/assets/imgs/maps/gate_inline.png"; import gateOffline from "@/assets/imgs/maps/gate_offline.png"; import gateAlarm from "@/assets/imgs/maps/gate_alarm.png"; import gateWarn from "@/assets/imgs/maps/gate_warn.png"; // 新泵站 import pumpInline from "@/assets/imgs/maps/pump_inline.png"; import pumpOffline from "@/assets/imgs/maps/pump_offline.png"; import pumpAlarm from "@/assets/imgs/maps/pump_alarm.png"; import pumpWarn from "@/assets/imgs/maps/pump_warn.png"; // 新河道水体水位 import waterInline from "@/assets/imgs/maps/water_inline.png"; import waterOffline from "@/assets/imgs/maps/water_offline.png"; import waterAlarm from "@/assets/imgs/maps/water_alarm.png"; import waterWarn from "@/assets/imgs/maps/water_warn.png"; // 新视频站 import videoInline from "@/assets/imgs/maps/video_inline.png"; import videoOffline from "@/assets/imgs/maps/video_offline.png"; import videoAlarm from "@/assets/imgs/maps/video_alarm.png"; import videoWarn from "@/assets/imgs/maps/video_warn.png"; import { reactive } from 'vue'; import { wgs_gcj_encrypts } from "./transformLonLat" window._AMapSecurityConfig = { securityJsCode: '39800a1cd4581dbcc97dcfac34bc074e', // 安全秘钥 } let obj = reactive({ cluster: undefined }) // 获取地图上站点的信息 export let clickSite = reactive({ siteInfo: null }) // 地图初始化 export const initMap = (markersList) => AMapLoader.load({ "key": "32bc822dd7ff40652fc9fd78c546729a", // 申请好的Web端开发者Key,首次调用 load 时必填 "version": "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15 "plugins": ["AMap.Pixel", "AMap.MarkerClusterer", "AMap.ToolBar"], // 需要使用的的插件列表,如比例尺'AMap.Scale'等 }).then((AMap) => { const map = new AMap.Map("map-container", { resizeEnable: true, viewMode: '3D', }); // 添加缩放 map.addControl(new AMap.ToolBar()); // 点聚合数据 var markers = []; for (let i = 0; i < markersList.length; i++) { // 标准转高德 let oldLat, oldLon // 防止有多个点而返回了NAN if (wgs_gcj_encrypts(markersList[i].latitude, markersList[i].longitude).lat && (wgs_gcj_encrypts(markersList[i].latitude, markersList[i].longitude).lat).length >= 9) { oldLat = (wgs_gcj_encrypts(markersList[i].latitude, markersList[i].longitude).lat).substr(0, 9); } else { oldLat = "0" } if (wgs_gcj_encrypts(markersList[i].latitude, markersList[i].longitude).lon && (wgs_gcj_encrypts(markersList[i].latitude, markersList[i].longitude).lon).length >= 10) { oldLon = (wgs_gcj_encrypts(markersList[i].latitude, markersList[i].longitude).lon).substr(0, 10); } else { oldLon = "0" } // 判断最后一位是否为 "." if (oldLat.length && (oldLat.charAt(oldLat.length - 1) == ".")) { oldLat = oldLat.substr(0, oldLat.length - 1) } if (oldLon.length && (oldLon.charAt(oldLon.length - 1) == ".")) { oldLon = oldLon.substr(0, oldLon.length - 1) } let lat = parseFloat(oldLat) let lon = parseFloat(oldLon) markers.push({ lnglat: [lon, lat], // 必传参数,统一格式 code: markersList[i].hexCode, id: markersList[i].id, status: markersList[i].status }) } // 自定义点标记 var _renderMarker = function (context) { var icon // 根据hexCode与status判断赋值点标记图标 let code = context.data[0].code; let status = context.data[0].status; if (code == '62H' && status == 1) { icon = inspInline } else if (code == '62H' && status == 2) { icon = inspWarn } else if (code == '62H' && status == 3) { icon = inspOffline } else if (code == '62H' && status == 4) { icon = inspAlarm } else if (code == '60H' && status == 1) { icon = waterLogInline } else if (code == '60H' && status == 2) { icon = waterLogWarn } else if (code == '60H' && status == 3) { icon = waterLogOffline } else if (code == '60H' && status == 4) { icon = waterLogAlarm } else if (code == '61H' && status == 1) { icon = networkInline } else if (code == '61H' && status == 2) { icon = networkWarn } else if (code == '61H' && status == 3) { icon = networkOffline } else if (code == '61H' && status == 4) { icon = networkAlarm } else if (code == '5AH' && status == 1) { icon = gateInline } else if (code == '5AH' && status == 2) { icon = gateWarn } else if (code == '5AH' && status == 3) { icon = gateOffline } else if (code == '5AH' && status == 4) { icon = gateAlarm } else if (code == '44H' && status == 1) { icon = pumpInline } else if (code == '44H' && status == 2) { icon = pumpWarn } else if (code == '44H' && status == 3) { icon = pumpOffline } else if (code == '44H' && status == 4) { icon = pumpAlarm } else if (code == '48H' && status == 1) { icon = waterInline } else if (code == '48H' && status == 2) { icon = waterWarn } else if (code == '48H' && status == 3) { icon = waterOffline } else if (code == '48H' && status == 4) { icon = waterAlarm } else if (code == '70H' && status == 1) { icon = videoInline } else if (code == '70H' && status == 2) { icon = videoWarn } else if (code == '70H' && status == 3) { icon = videoOffline } else if (code == '70H' && status == 4) { icon = videoAlarm } // 点标记样式 var content = `<div style="height: 30px; width: 30px;"><img style="width: 100%; height: 100%" src="${icon}"></img></div>`; var offset = new AMap.Pixel(-9, -9); context.marker.setContent(content); context.marker.setOffset(offset); // 设置标记携带的数据,点击事件会使用 context.marker.setExtData({ id: context.data[0].id, hexCode: context.data[0].code }); // 单个标记点击事件 context.marker.on('click', ev => { // 当前标记居中, 第一个参数为缩放级别 map.setZoomAndCenter(18, ev.target.getPosition()); // 获取标记携带的数据 const extData = ev.target.getExtData(); clickSite.siteInfo = extData; // 点击获取当前站点的信息,触发监听事件 }); } if (markers && markers.length) { obj.cluster = new AMap.MarkerClusterer(map, markers, { gridSize: 80, clusterByZoomChange: true, renderMarker: _renderMarker }); // 点击点聚合 obj.cluster.on('click', (item) => { //此处是通过包含点的数量判断是否是聚合点,不是聚合点就执行上方单个点的点击方式 if (item.clusterData.length <= 1) { return; } //这里是计算所有聚合点的中心点 let alllng = 0, alllat = 0; for (const mo of item.clusterData) { alllng += mo.lnglat.lng; alllat += mo.lnglat.lat; } const lat = alllat / item.clusterData.length; const lng = alllng / item.clusterData.length; //这里是放大地图,此处写死了每次点击放大的级别,可以根据点的数量和当前大小适应放大,体验更佳 map.setZoomAndCenter(map.getZoom() + 2, [lng, lat]); }); } return { AMap, map } }).catch(e => { console.log(e); })
5、国标转高德
transformLonLat.js: //转换常数 var pi = 3.14159265358979324; var a = 6378245.0; var ee = 0.00669342162296594323; function transformLon(x, y) { var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x)); ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0; ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0; ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0; return ret; }; function transformLat(x, y) { var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x)); ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0; ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0; ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0; return ret; } function outOfChina(lat, lon) { if (lon < 72.004 || lon > 137.8347) return true; if (lat < 0.8293 || lat > 55.8271) return true; return false; } /* * WGS-84:是国际标准,GPS坐标(Google Earth使用、或者GPS模块、天地图) * GCJ-02:中国坐标偏移标准,Google Map、高德、腾讯使用 * BD-09:百度坐标偏移标准,Baidu Map使用 */ /** * wgLat 纬度 * wgLon 经度 * WGS-84 到 GCJ-02 的转换(即 GPS 加偏) * */ export const wgs_gcj_encrypts = (wgLat, wgLon) => { var point = {}; if (outOfChina(wgLat, wgLon)) { point.lat = wgLat; point.lon = wgLon; return point; } var dLat = transformLat(wgLon - 105.0, wgLat - 35.0); var dLon = transformLon(wgLon - 105.0, wgLat - 35.0); var radLat = wgLat / 180.0 * pi; var magic = Math.sin(radLat); magic = 1 - ee * magic * magic; var sqrtMagic = Math.sqrt(magic); dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi); dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi); var lat = wgLat + dLat; var lon = wgLon + dLon; point.lat = lat; point.lon = lon; return point; };
6、完成,效果:
补充:
高德地图js2.0使用MarkerCluster聚合点及添加点击事件
之前的博客中我便提过了在版本变化的趋势下,高德地图也在不断迭代,目前2.0以下版本已经在iOS15 beta版本不适用了,而且2.0以下版本由于卡顿等问题也不在符合用户的使用需要,升级迫在眉睫,但2.0对于标记的聚和与之前版本有较大区别,在此将写法记录一下,也希望能帮到大家。
2.0以前对于标记的处理是将标记全部在地图上画出来之后通过MarkerClusterer聚合,不仅对标记的修改较为复杂,还会导致严重的卡顿问题。而在升级到2.0后,标记的聚合便是通过MarkerCluster将标记的坐标打在地图上,然后直接渲染的方式了,如下所示:
this.cluster = new AMap.MarkerCluster(this.map, this.allLnglat, { styles: styles, renderMarker: this.renderMarker });
其中只列举出了最重要的几个参数:
this.map:当前渲染的地图
this.allLnglat:所有的标记坐标,例如:[{ lnglat: [117.366,36.577] }]
styles: 聚合点上显示的图标,例如:
[{ url: 'https://a.amap.com/jsapi_demos/static/images/blue.png', size: new AMap.Size(32, 32), offset: new AMap.Pixel(-16, -16) },{ url: 'https://a.amap.com/jsapi_demos/static/images/green.png', size: new AMap.Size(32, 32), offset: new AMap.Pixel(-16, -16) }]
renderMarker:非聚合点上显示的标记,也就是单个点显示的标记,和2.0版本前我们定义的marker是一个东西,可以自定义样式添加点击事件等,例如:
renderMarker(context) { //显示点的经纬度context.data[0].lnglat //此处应有逻辑,通过遍历所有点的经纬度来识别当前标记对应的数据 //此处content为设置当个标记的样式 context.marker.setContent(content); //此处为设置标记在地图上的偏移,根据标记物大小处理 context.marker.setOffset(new AMap.Pixel(-20, -20)); //此处为设置标记是否显示在最上方,一般只有选中的标记在最上方 context.marker.setTop(top); //此处为设置标记携带的数据,点击事件会使用 context.marker.setExtData({ id: id }); //此处为添加单个标记点击事件 context.marker.on('click', ev => { //当前标记居中 this.map.setZoomAndCenter(16, ev.target.getPosition()); //获取标记携带的数据 const extData = ev.target.getExtData(); const id = extData.id; }); },
由于现在聚合点和标记点都是使用的标记,因此聚合点没有提供点击散开的功能,我们可以通过一下方式实现:
this.cluster.on('click', (item) => { //此处是通过包含点的数量判断是否是聚合点,不是聚合点就执行上方单个点的点击方式 if(item.clusterData.length <= 1) { return; } //这里是计算所有聚合点的中心点 let alllng = 0, alllat = 0; for(const mo of item.clusterData) { alllng += mo.lnglat.lng; alllat += mo.lnglat.lat; } const lat = alllat / item.clusterData.length; const lng = alllng / item.clusterData.length; //这里是放大地图,此处写死了每次点击放大的级别,可以根据点的数量和当前大小适应放大,体验更佳 this.map.setZoomAndCenter(this.map.getZoom() + 2, [lng, lat]); });
renderMarker方法是通过地图缩放实时变化持续调用的,所以我们可以直接修改数据的方式实时修改点上的数据,注意修改完成后缩放一下地图,之后可以也通过this.cluster.setData方法修改要显示在地图上的点
注意:这种写法有个明显的问题,如果出现两个坐标完全相同的点,前一个坐标会被后一个顶掉,如果不能保证坐标完全不同的话,建议对坐标进行去重处理或是修改重复坐标,另外,由于float浮点数加减问题及context.data[0].lnglat方法会去除一部分小数,建议判断时统一所有数据小数精度。
到此这篇关于vue3使用高德地图,自定义点标记、默认点聚合样式、点击点标记获取信息的文章就介绍到这了,更多相关vue3高德地图点标记获取信息内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!