You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Leaflet MarkerClusterGroup使用报错:TypeError: L.markerClusterGroup不是构造函数

解决Leaflet MarkerClusterGroup构造函数错误的方案

你遇到的这个TypeError: L.markerClusterGroup is not a constructor问题我太熟悉了,大概率是两个小细节没做好,咱们一步步来排查解决:

核心问题分析

这个错误的根源主要有两个:

  • 没引入MarkerCluster插件资源:Leaflet核心库本身不带标记聚合的功能,MarkerCluster是官方推荐的第三方插件,必须单独引入它的样式和脚本文件才行。
  • 构造函数大小写写错了:插件的正确构造函数是**L.MarkerClusterGroup()**(驼峰命名,首字母大写),如果你写成了小写开头的L.markerClusterGroup(),浏览器肯定找不到这个构造函数。

具体解决方案

1. 补全资源引入(顺序不能乱)

你现在只引入了Leaflet的核心文件,得把MarkerCluster的样式和脚本加上,而且要严格按照以下顺序加载(先样式后脚本,先核心库后插件):

<!-- Leaflet核心样式 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
<!-- MarkerCluster的两个样式文件,缺一不可 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.5.1/MarkerCluster.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.5.1/MarkerCluster.Default.css">

<!-- Leaflet核心脚本 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js"></script>
<!-- MarkerCluster插件脚本 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.5.1/leaflet.markercluster.js"></script>

提示:我选的MarkerCluster 1.5.1版本和你用的Leaflet 0.7.7完全兼容,别随便换更高版本的插件,容易出现兼容性问题。

2. 修正代码中的构造函数写法

确保你创建聚合组的代码用了正确的构造函数,然后把标记添加进去:

// 先初始化地图
var map = L.map('map').setView([51.505, -0.09], 13);

// 添加基础底图
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap contributors'
}).addTo(map);

// 创建MarkerClusterGroup实例(注意首字母大写的驼峰命名!)
var markerClusterGroup = L.MarkerClusterGroup();

// 示例:添加几个标记到聚合组
var marker1 = L.marker([51.5, -0.09]);
var marker2 = L.marker([51.51, -0.1]);
markerClusterGroup.addLayer(marker1);
markerClusterGroup.addLayer(marker2);

// 最后把聚合组添加到地图上
map.addLayer(markerClusterGroup);

验证小技巧

  1. 打开浏览器的开发者工具(F12),切换到「网络」面板,刷新页面看看所有引入的文件是不是都加载成功了(没有404错误)。
  2. 再检查一遍代码里的构造函数拼写,确保是L.MarkerClusterGroup(),不是小写开头的版本。

按照上面的步骤操作,应该就能顺利解决这个错误啦!

内容的提问来源于stack exchange,提问作者Gopal Badariya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:21:53