javascript - 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: '© <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();
}
});
我的问题是,如果我停止事件侦听器,代码的哪一部分正在执行,如何删除跟踪?
解决方案
我做了一些挖掘,这就是我发现的。如果您检查realtime
对象,标记和轨迹都是该对象的属性,在_featureLayers
属性下。您需要将id
这些层定义为properties
GeoJSON 的一部分:
var trail = {
type: 'Feature',
properties: {
id: 'trail'
},
geometry: {
type: 'LineString',
coordinates: []
}
}
你可以看到我1
把trail
. 现在您可以通过调用来获取您的踪迹并将其删除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,并假设没有其他具有undefined
id的层。可能有一些方法可以id
为默认制造商定义它,但我会把它留给你。
工作代码框
推荐阅读
- swift - 如何根据最近添加和单击的最受欢迎按钮在 ios 的集合视图中显示 2 组单独的图像
- java - 错误 java.lang.UnsatisfiedLinkError: 无法加载库 'gsdll64'
- postgresql - 我的 postgresql 备份是否正确可以再次使用它
- javascript - io.to 不发送到特定客户端
- git - Git 压缩了一些提交
- python - 有没有办法区分服务器关闭和 urllib 不存在的 URL?
- reactjs - netlify deploy failed..ENOENT:没有这样的文件或目录
- elasticsearch - ES 中的聚合是否适用于 es 索引中的所有文档(查询全部匹配)
- arrays - 寻求有效的算法在数值数组中找到公共序列
- python-3.x - 使用python从网站的图表中获取数据