Leaflet 综合案例-聚类图层控制

看过的知识不等于学会。唯有用心总结、系统记录,并通过温故知新反复实践,才能真正掌握一二

作为一名摸爬滚打三年的前端开发,开源社区给了我饭碗,我也将所学的知识体系回馈给大家,助你少走弯路!
OpenLayers、Leaflet 快速入门 ,每周保持更新 2 个案例
Cesium 快速入门,每周保持更新 4 个案例

Leaflet 综合案例-聚类图层控制

Vue 3 + Leaflet 实现的 WebGIS 应用提供了完整的聚类图层控制功能

主要功能

MP4效果动画链接地址

技术栈

该环境下代码即拿即用

bash 复制代码
Vue 3.5.13+
Leaflet 1.9.4
Vite 6.3.5+

插件

使用 Leaflet 插件 Leaflet.markercluster 实现聚类图层

bash 复制代码
npm install leaflet.markercluster
vue 复制代码
<template>
  <div class="map-wrapper">
    <div id="map-cluster" class="map-container"></div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from "vue";
import "leaflet/dist/leaflet.css";
import "leaflet.markercluster/dist/MarkerCluster.css"; // 聚合插件的CSS
import "leaflet.markercluster/dist/MarkerCluster.Default.css"; // 聚合插件默认主题CSS
import L from "leaflet";
import "leaflet.markercluster"; // 引入聚合插件JS

let map = null;
let markers = null;

const initialView = [39.909186, 116.397479];
const initialZoom = 10; // 初始缩放级别稍微小一点,更容易看到聚合效果

onMounted(() => {
  map = L.map("map-cluster").setView(initialView, initialZoom);

  L.tileLayer(
    "https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
    {
      maxZoom: 18,
      minZoom: 3,
      attribution: '&copy; <a href="https://www.amap.com/">高德地图</a>',
    }
  ).addTo(map);

  // 创建一个标记点聚合图层
  markers = L.markerClusterGroup();

  // 随机生成1000个标记点
  const dummyMarkers = [];
  for (let i = 0; i < 1000; i++) {
    const lat = 39.909186 + (Math.random() - 0.5) * 0.5; // 在中心点附近随机生成
    const lng = 116.397479 + (Math.random() - 0.5) * 0.5;
    const marker = L.marker([lat, lng]).bindPopup(`标记点 ${i + 1}`);
    dummyMarkers.push(marker);
  }

  // 将所有标记点添加到聚合图层
  markers.addLayers(dummyMarkers);
  map.addLayer(markers);

  // 调整地图视图以适应所有标记点(可选,如果标记点范围很大)
  // map.fitBounds(markers.getBounds());
});

onUnmounted(() => {
  if (map) {
    map.remove();
    map = null;
    markers = null;
  }
});

const resetMapView = () => {
  if (map) {
    map.setView(initialView, initialZoom);
  }
};
</script>

<style scoped>
/* 样式与上一个案例类似,确保布局一致 */
.map-wrapper {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  font-family: sans-serif;
  box-sizing: border-box;
}

@media (min-width: 768px) {
  .map-wrapper {
    flex-direction: row;
  }
}

.map-container {
  flex-grow: 1;
  height: 100%;
  min-height: 300px;
  background-color: #e0e0e0;
}
</style>
相关推荐
哥布林学者2 天前
高光谱成像(一)高光谱图像
机器学习·高光谱成像
罗西的思考2 天前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
HXhlx2 天前
CART决策树基本原理
算法·机器学习
OpenBayes贝式计算5 天前
解决视频模型痛点,TurboDiffusion 高效视频扩散生成系统;Google Streetview 涵盖多个国家的街景图像数据集
人工智能·深度学习·机器学习
OpenBayes贝式计算5 天前
OCR教程汇总丨DeepSeek/百度飞桨/华中科大等开源创新技术,实现OCR高精度、本地化部署
人工智能·深度学习·机器学习
够快云库6 天前
能源行业非结构化数据治理实战:从数据沼泽到智能资产
大数据·人工智能·机器学习·企业文件安全
西岸行者6 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky6 天前
Django入门笔记
笔记·django
勇气要爆发6 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达