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>
相关推荐
爱敲代码的小鱼6 分钟前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
Cobyte32 分钟前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
NEXT061 小时前
前端算法:从 O(n²) 到 O(n),列表转树的极致优化
前端·数据结构·算法
剪刀石头布啊1 小时前
生成随机数,Math.random的使用
前端
剪刀石头布啊1 小时前
css外边距重叠问题
前端
剪刀石头布啊1 小时前
chrome单页签内存分配上限问题,怎么解决
前端
剪刀石头布啊1 小时前
css实现一个宽高固定百分比的布局的一个方式
前端
剪刀石头布啊1 小时前
js数组之快速组、慢数组、密集数组、稀松数组
前端
mango_mangojuice1 小时前
Linux学习笔记(make/Makefile)1.23
java·linux·前端·笔记·学习
Days20502 小时前
简单处理接口返回400条数据本地数据分页加载
前端