javascript 从数据层中删除所有特征
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24411171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all features from data layer
提问by Plendor
I used something like:
我使用了类似的东西:
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 4,
center: {lat: -28, lng: 137.883}
});
map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json');
}
google.maps.event.addDomListener(window, 'load', initialize);
to load a geojson shape file to the map.data layer of my map. In the shape file, there are a couple of 'feature' classes defining polygons to be drawn on the map. Up until here I have no problems.
将 geojson 形状文件加载到我的地图的 map.data 层。在形状文件中,有几个“要素”类定义要在地图上绘制的多边形。直到这里我没有问题。
Later on though, I want to load another geojson file over the other one (replacing the drawn 'features' on the map). When you just load another file over the other one it just redraws it over the other one. How on earth do you clear the map.data layer of all the features before loading in the new geojson shape file?
稍后,我想在另一个文件上加载另一个 geojson 文件(替换地图上绘制的“特征”)。当您只是在另一个文件上加载另一个文件时,它只会在另一个文件上重新绘制它。在加载新的 geojson 形状文件之前,您到底如何清除所有要素的 map.data 层?
I've tried using
map.data.remove(feature)
with a loop, but I can't seem to get all the features from the map.data layer.
我尝试使用
map.data.remove(feature)
循环,但我似乎无法从 map.data 层获取所有功能。
回答by Gidy
This will iterate over all the features and remove them from map.data.
这将迭代所有功能并将它们从map.data 中删除。
map.data.forEach(function(feature) {
// If you want, check here for some constraints.
map.data.remove(feature);
});
Edit 1: ExplanationMap data forEach function use callbacks, so you have to give a callback function as parameter:
编辑 1:解释每个函数使用回调的映射数据,因此您必须提供一个回调函数作为参数:
var callback = function(){ alert("Hi, I am a callback"); };
map.data.forEach(callback);
Now for each element in data it will show an alert. It's also possible to give callbacks with parameter, like in the code shown above.
现在,对于数据中的每个元素,它都会显示一个警报。也可以提供带参数的回调,就像上面显示的代码一样。
var callback = function(feature) {
// If you want, check here for some constraints.
map.data.remove(feature);
};
map.data.forEach(callback);
Further explanation and examples: http://recurial.com/programming/understanding-callback-functions-in-javascript/
进一步的解释和例子:http: //recurial.com/programming/understanding-callback-functions-in-javascript/
回答by Plendor
Seems that the map.data
is a collection of 'feature' classes.
似乎map.data
是“功能”类的集合。
So you can use the map.data to iterate through and remove each feature in the collection
所以你可以使用 map.data 迭代并删除集合中的每个特征