the problem with leaflet and leaflet draw vue leaflet.draw.js?20d6:8 Uncaught TypeError: Cannot read properties of undefined (reading 'length')

the problem with leaflet and leaflet draw vue leaflet.draw.js?20d6:8 Uncaught TypeError: Cannot read properties of undefined (reading 'length')

mounted() {
 this.initMap();
},
methods: {
initMap() {
  this.map = L.map('mapContainer').setView([48.856663, 2.351556], 12);
  this.tileLayer = L.tileLayer(
      "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}",
      {
        attribution: '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery (c) <a href="https://www.mapbox.com/">Mapbox</a>',
        maxZoom: 18,
        id: "mapbox/satellite-streets-v11",
        accessToken: "token",
      }
  );
  this.tileLayer.addTo(this.map);
  var drawnItems = new L.FeatureGroup();
  this.map.addLayer(drawnItems);
  var drawControl = new L.Control.Draw({
    edit: {
      featureGroup: drawnItems
    }
  });
  this.map.addControl(drawControl);

  this.map.on(L.Draw.Event.CREATED, function(event){
    let layer = event.layer;
    console.log(`start ${layer}`);
    drawnItems.addLayer((layer))
  })
 },
},
}

leaflet.draw.js?20d6:8 未捕获类型错误:无法读取未定义的属性(读取 'length')

第一次与地图交互后,控制台出现错误,无法再绘制形状

UPD:切换到 mapbox draw

我使用类似的代码在底图上绘制多边形,并且在将 Vue3 与 leaflet 和 leaflet-draw 一起使用时遇到类似的问题。绘制多边形后,控制台出现一堆错误,可能是鼠标悬停事件触发的。

Uncaught TypeError: this._markers is undefined
in leaflet-draw.js:162:18

还没有找到问题的根本原因,但原因可能是leaflet-draw不再符合Leaflet Base Library(只是猜测)。最后一次提交在 Github is from 2018 and there is a long list of issues and open pull requests,而 Leaflet 本身不断更新。

该库与 Vue 结合使用时也可能出现该问题。

您是否尝试过使用 Vanilla JS 创建上述功能?

我是这样解决这个问题的。 使用 MapBox 而不是 Leaflet,并且 MapBox 在 Vue 3 中绘制作品