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>
相关推荐
znhy@1236 小时前
CSS易忘属性
前端·css
瓜瓜怪兽亚6 小时前
前端基础知识---Ajax
前端·javascript·ajax
AI智能研究院6 小时前
(四)从零学 React Props:数据传递 + 实战案例 + 避坑指南
前端·javascript·react.js
qq7798233406 小时前
React组件完全指南
前端·javascript·react.js
qq7798233407 小时前
React Hooks完全指南
前端·javascript·react.js
Moment7 小时前
性能狂飙!Next.js 16 重磅发布:Turbopack 稳定、编译提速 10 倍!🚀🚀🚀
前端·javascript·后端
DoraBigHead7 小时前
React Fiber:从“递归地狱”到“时间切片”的重生之路
前端·javascript·react.js
lecepin8 小时前
AI Coding 资讯 2025-10-22
前端·javascript·后端
BumBle9 小时前
uniapp AI聊天应用技术解析:实现流畅的Streaming聊天体验(基础版本)
前端·uni-app
搞个锤子哟9 小时前
vant4的van-pull-refresh里的列表不在顶部时下拉也会触发刷新的问题
前端