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>
相关推荐
Senar12 分钟前
Web端选择本地文件的几种方式
前端·javascript·html
烛阴29 分钟前
UV Coordinates & Uniforms -- OpenGL UV坐标和Uniform变量
前端·webgl
姑苏洛言34 分钟前
扫码小程序实现仓库进销存管理中遇到的问题 setStorageSync 存储大小限制错误解决方案
前端·后端
烛阴44 分钟前
JavaScript 的 8 大“阴间陷阱”,你绝对踩过!99% 程序员崩溃瞬间
前端·javascript·面试
lh_12541 小时前
ECharts 地图开发入门
前端·javascript·echarts
jjw_zyfx1 小时前
成熟的前端vue vite websocket,Django后端实现方案包含主动断开websocket连接的实现
前端·vue.js·websocket
Mikey_n2 小时前
前台调用接口的方式及速率对比
前端
周之鸥2 小时前
使用 Electron 打包可执行文件和资源:完整实战教程
前端·javascript·electron
我爱吃朱肉2 小时前
HTMLCSS模板实现水滴动画效果
前端·css·css3
机器视觉知识推荐、就业指导2 小时前
开源QML控件:进度条滑动控件(含源码下载链接)
前端·qt·开源·qml