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

Leaflet VectorGrid点击事件报错:L.DomEvent.fakeStop未定义

Leaflet 1.8+ 与 leaflet.vectorgrid 点击事件报错修复方案

问题背景

使用Vue3 + Vite框架,基于Leaflet 1.9.1和leaflet.vectorgrid 1.3.0开发地图应用:

  • 已成功通过以下代码加载并显示TopoJSON:
fetch('./mytopo.json').then(function(response){
  return response.json();
}).then(function(json){
  var vectorGrid = L.vectorGrid.slicer( json, {
    rendererFactory: L.canvas.tile,
    interactive: true,
    minZoom: 10,
    maxZoom: 12,
    vectorTileLayerStyles: {
      'reduced2': function(properties, zoom) {
        var gradient = hslToHex(percent,100,50);
        return {
          fillColor: gradient,
          fillOpacity: 0.5,
          stroke: true,
          fill: true,
          color: 'black',
          weight: 1,
        }
      }
    }
  }).addTo(map);
  • 但添加点击事件监听后触发报错:
Uncaught TypeError: L.DomEvent.fakeStop is not a function
    at NewClass._onClick (Leaflet.VectorGrid.bundled.min.js:2:15768)
    at HTMLCanvasElement.handler (DomEvent.js:108:13)

点击事件代码:

vectorGrid.on('click', function(e) {
  L.popup()
  .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  .setLatLng(e.latlng)
  .openOn(map)
});
  • 经测试,该功能在Leaflet 1.7.1中正常运行,1.8及以上版本失效,原因是Leaflet 1.8+移除了L.DomEvent.fakeStop方法,而leaflet.vectorgrid 1.3.0仍在调用该方法。

解决方案

方案1:手动添加兼容方法(推荐)

在引入Leaflet和leaflet.vectorgrid之后,手动给L.DomEvent添加fakeStop方法,模拟旧版本Leaflet的行为:

// 兼容Leaflet 1.8+,为vectorgrid添加缺失的fakeStop方法
if (!L.DomEvent.fakeStop) {
  L.DomEvent.fakeStop = function(e) {
    e.stopPropagation = L.Util.falseFn;
    e.preventDefault = L.Util.falseFn;
    return e;
  };
}

该方法会将事件的stopPropagation和preventDefault设为空函数,与旧版本fakeStop的行为一致,可直接解决报错问题。

方案2:修改leaflet.vectorgrid源码

找到leaflet.vectorgrid中调用L.DomEvent.fakeStop的位置(通常在_onClick方法里),将其替换为Leaflet标准的事件阻止API:

// 替换原代码中的 L.DomEvent.fakeStop(e);
L.DomEvent.stopPropagation(e);
L.DomEvent.preventDefault(e);

如果使用的是打包后的Leaflet.VectorGrid.bundled.min.js,可以直接在文件中搜索L.DomEvent.fakeStop并替换为上述两行代码。

方案3:降级Leaflet版本

将Leaflet降级到1.7.1版本,直接规避版本兼容问题:

npm install leaflet@1.7.1 --save

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:11:01