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

Leaflet Easy Button失效报错:L.easyButton is not a function

Leaflet Easy Button 报错及信息栏切换修复方案

核心错误:插件引入错误

你标注为「easy button plugin」的代码实际引入的是Leaflet Control Geocoder插件,而非Easy Button插件,这直接导致Uncaught TypeError: L.easyButton is not a function报错。替换为正确的Easy Button资源:

<!-- 保留原有Leaflet及定位插件 -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol@0.79.0/dist/L.Control.Locate.min.css" />
<script src="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol@0.79.0/dist/L.Control.Locate.min.js" charset="utf-8"></script>

<!-- 正确的Easy Button插件 -->
<link rel="stylesheet" href="https://unpkg.com/leaflet-easybutton@2.4.0/src/easy-button.css" />
<script src="https://unpkg.com/leaflet-easybutton@2.4.0/src/easy-button.js"></script>

JS代码修正

1. DOM元素获取语法错误

document.getElementById(info__container)缺少字符串引号,正确写法:

var informationBar = document.getElementById('info__container');

2. 修正信息栏切换逻辑

map.addLayer()/map.removeLayer()仅支持Leaflet图层,不能操作普通DOM元素。改用CSS display 属性切换显示:

var informationBar = document.getElementById('info__container');

var toggle = L.easyButton({
    states: [{
        stateName: 'show-panel',
        icon: '<span class="star">&equiv;</span>',
        title: '显示菜单',
        onClick: function(control) {
            informationBar.style.display = 'inline-flex'; // 匹配你的CSS初始display值
            control.state('hide-panel');
        }
    }, {
        icon: 'fa-undo',
        stateName: 'hide-panel',
        onClick: function(control) {
            informationBar.style.display = 'none';
            control.state('show-panel');
        },
        title: '隐藏菜单'
    }]
});
toggle.addTo(map);

3. 图标显示补充

若使用fa-undo这类Font Awesome图标,需引入Font Awesome样式:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />

CSS样式调整(可选)

如果希望信息栏默认隐藏,修改CSS:

#info__container{ 
    position: absolute;
    z-index: 800;
    margin-top: 10%;
    margin-left: 5rem;
    align-items: center;
    display: none; /* 默认隐藏 */
    flex-direction: column;
    width: 250px;
}

内容的提问来源于stack exchange,提问作者b-coffer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:40:43