我是网络开发的初学者,正在开发一个程序,我使用传单通过ajax调用更新 map ,它工作正常。现在我每10秒更新一次 map ,所以我更新 map 的函数如下:
function update_the_map(){
$.ajax({
type: "GET",
async : false,
url: 'http://backendserver:port/update,
success: function(data) {
var n=0;
for (j = 0; j<3000; j++) {
if(linestring['features'][j]['properties']['color']!=data[j].color){
linestring['features'][j]['properties']['color']=data[j].color;
}
}
if (vectorGrid) {
vectorGrid.remove();
console.log("removed the previous layer");
}
var vectorGrid = L.vectorGrid.slicer(linestring, {
rendererFactory: L.svg.tile,
vectorTileLayerStyles: {
sliced: function(properties, zoom) {
return {
weight: 2,
opacity: 1,
color: getColor(properties.color),
fillOpacity: 0.7
}
}
},
interactive: true,
getFeatureId: function(f) {
return f.properties.id;
}
})
.addTo(map);
console.log("updated the new layer");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
complete: function() {
if(time){
clearTimeout(time);
}
time= setTimeout(update_the_map, 10000);
}
});
}
然后我调用
中的函数<script type="text/javascript">
window.onload = mapupdatecolor();
</script>
但是这工作正常一段时间,然后错误表明浏览器没有内存。所以当我研究同样的错误时,我认为应该是超时函数有问题。但无法准确找到错误发生的位置。感谢任何帮助。
最佳答案
阅读您的代码后。浏览器内存不足的唯一原因似乎是 L.vectorGrid.slicer
的实例化。
在创建新实例之前,您应该尝试释放所删除的实例所使用的内存。
这可能还不够,但您可以在 vectorGrid.remove();
之后执行此操作:
delete vectorGrid;
如果它不能解决您的问题。寻找一种方法来清理由矢量网格创建的所有内容。
更新:
我刚刚注意到您的 vectorGrid
变量在每个 ajax 成功函数调用中都被重新声明,并且对于一个调用来说是本地的。这也可能是内存泄漏的原因。垃圾收集器可能认为这个局部变量永远没有用处,因此它不会“释放”内存。
您可以尝试以下方法:
// HERE IS A CHANGE
var vectorGrid;
function update_the_map(){
$.ajax({
type: "GET",
async : false,
url: 'http://backendserver:port/update',
success: function(data) {
var n=0;
for (j = 0; j<3000; j++) {
if(linestring['features'][j]['properties']['color']!=data[j].color){
linestring['features'][j]['properties']['color']=data[j].color;
}
}
if (vectorGrid) {
vectorGrid.remove();
// HERE IS A CHANGE
vectorGrid = undefined;
console.log("removed the previous layer");
}
// HERE IS A CHANGE
vectorGrid = L.vectorGrid.slicer(linestring, {
rendererFactory: L.svg.tile,
vectorTileLayerStyles: {
sliced: function(properties, zoom) {
return {
weight: 2,
opacity: 1,
color: getColor(properties.color),
fillOpacity: 0.7
}
}
},
interactive: true,
getFeatureId: function(f) {
return f.properties.id;
}
})
.addTo(map);
console.log("updated the new layer");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
complete: function() {
if(time){
clearTimeout(time);
}
time= setTimeout(update_the_map, 10000);
}
});
}
这样一来,就只有一个 vectorGrid
变量,该变量的内容可能会在每次 update_the_map
调用时释放。
关于javascript - map 更新后程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43670218/