首页 > 解决方案 > Leaflet - 即使在删除事件侦听器后,标记也不会停止移动

问题描述

我正在使用传单实时插件来可视化轨迹。我复制了跟踪代码并尝试通过添加删除跟踪和标记realtime.removeEventListener(); 但是,标记仍在移动。我知道我可以通过添加来删除标记,realtime.removeLayer(marker);但是轨迹呢?

我试图通过添加来删除它,trailCoords = [];但它也不起作用。这是稍微修改的代码trail.js

    var trailCoords;
    var map = L.map('map'),
        trail = {
            type: 'Feature',
            properties: {
                id: 1
            },
            geometry: {
                type: 'LineString',
                coordinates: []
            }
        },
        realtime = L.realtime(function(success, error) {
            fetch('https://wanderdrone.appspot.com/')
            .then(function(response) { return response.json(); })
            .then(function(data) {
                trailCoords = trail.geometry.coordinates;
                trailCoords.push(data.geometry.coordinates);
                trailCoords.splice(0, Math.max(0, trailCoords.length - 5));
                success({
                    type: 'FeatureCollection',
                    features: [data, trail]
                });
            })
            .catch(error);
        }, {
            interval: 250
        }).addTo(map);

    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    var i = 0;
    realtime.on('update', function() {
        console.log(i)
        i++
        map.fitBounds(realtime.getBounds(), {maxZoom: 3});
        if (i === 3)
        {
            trailCoords = [];
            realtime.removeEventListener();
        }

    });

我的问题是,如果我停止事件侦听器,代码的哪一部分正在执行,如何删除跟踪?

标签: javascriptleaflet

解决方案


我做了一些挖掘,这就是我发现的。如果您检查realtime对象,标记和轨迹都是该对象的属性,在_featureLayers属性下。您需要将id这些层定义为propertiesGeoJSON 的一部分:

var trail = {
  type: 'Feature',
  properties: {
      id: 'trail'
  },
  geometry: {
      type: 'LineString',
      coordinates: []
  }
}

你可以看到我1trail. 现在您可以通过调用来获取您的踪迹并将其删除realtime.getLayer('trail').remove()。我上班时运气不佳removeEventListener,但实时附带了一个stop似乎正在工作的功能。它看起来像这样:

var i = 0;
realtime.on('update', function() {

    console.log('i', i)
    i++
    map.fitBounds(realtime.getBounds(), {maxZoom: 3});
    if (i === 3) {
        trailCoords = [];
        realtime.stop();
        realtime.getLayer('trail').remove()
    }

});

由于某种原因,标记本身的默认id名称是未定义的。您可能会调用realtime.getLayer('undefined').remove()以删除它,但这非常hacky,并假设没有其他具有undefinedid的层。可能有一些方法可以id为默认制造商定义它,但我会把它留给你。

工作代码框


推荐阅读