Leaflet按需加载多个Marker和Polygon

该插件依赖turfjs 插件

用来判断两个区块是否相同
https://turfjs.fenxianglu.cn/docs/api/booleanEqual

js 复制代码
<template>
    <Map ref="mapRef" />
</template>

<script setup lang='ts'>
import { onMounted, ref, toRaw } from 'vue'
import * as L from 'leaflet'
import * as turf from "@turf/turf"

onMounted(() => {
    mapRef.value.map.on('moveend', () => {
        drawMarker()
        drawPolygon()
    })
    mapRef.value.map.fire('moveend')
})

const mapRef = ref()

// 绘制锚点
const addedMarkers: any[] = []
const drawMarker = () => {
    // 模拟后台数据
    const arr = [
        { id: 1, marker: [22.542800, 114.058000] },
        { id: 2, marker: [22.54, 114.05] }
    ]
    const markerIcon = L.icon({ iconUrl: getAssetsFile('images/qf.png'), iconSize: [40, 40] })
    const bounds = mapRef.value.map.getBounds()
    for (let item of arr) {
        const marker = L.marker(item.marker as unknown as L.LatLngExpression, { icon: markerIcon })
        const latLng = L.latLng(item.marker[0], item.marker[1])
        L.Util.extend(marker, { params: item })
        // 判断在当前可见视图并且没有绘制过的
        if (bounds.contains(marker.getLatLng()) && !addedMarkers.some(m => m.getLatLng().equals(latLng))) {
            marker.addTo(toRaw(mapRef.value.map))
            addedMarkers.push(marker)
        }
    }
}


// 绘制区块
const addedPolygons: any[] = []
const drawPolygon = () => {
    const arr = [
        {
            id: 1,
            polygon: [[22.548728, 114.061196], [22.546925, 114.059222], [22.540107, 114.064929], [22.546806, 114.068127], [22.548728, 114.061196]]
        },
        {
            id: 2,
            polygon: [[22.550096, 114.056904], [22.548986, 114.056818], [22.549937, 114.058599], [22.550096, 114.056904]]
        }
    ]
    const bounds = mapRef.value.map.getBounds()
    for (let item of arr) {
        const polygon = new L.Polygon(item.polygon as unknown as L.LatLngExpression[][], { color: greenColor })
        L.Util.extend(polygon, { params: item }) //携带自定义参数
        if (bounds.contains(polygon.getBounds()) && !addedPolygons.some(p => turf.booleanEqual(p.toGeoJSON(), polygon.toGeoJSON()))) {
            // 使用 toRaw 处理popup关闭后伸缩地图报错:Cannot read properties of null (reading '_latLngToNewLayerPoint')
            polygon.addTo(toRaw(mapRef.value.map))
            addedPolygons.push(polygon)
        }
    }
}
</script>
相关推荐
C_心欲无痕几秒前
前端实现文件下载的完整流程
前端·状态模式
Fighting_p5 分钟前
【element UI】el-select 组件下拉数据某一行文字过多时,文字换行展示,避免el-select下拉框被撑宽,导致页面过丑
前端·javascript
王家视频教程图书馆13 分钟前
vue3从本地选择一个视频 展示到视频组件中
前端·javascript·音视频
天外来鹿36 分钟前
Map/Set/WeakMap/WeakSet学习笔记
前端·javascript·笔记·学习
Luna-player1 小时前
前端中stylus是干嘛用的
前端·css·stylus
CHQIUU1 小时前
解决 npm 全局安装 EACCES 权限问题(macOS 篇)
前端·macos·npm
程序员鱼皮1 小时前
OpenClaw接入飞书保姆级教程,几分钟搞定手机养龙虾!
前端·人工智能·后端
紫_龙1 小时前
最新版vue3+TypeScript开发入门到实战教程之vue3与vue2语法优劣对比
前端·javascript·typescript
SouthRosefinch2 小时前
一、HTML简介与开发环境
开发语言·前端·html
全栈小52 小时前
【前端】Vue 组件开发中的枚举值验证:从一个Type属性错误说起
前端·javascript·vue.js