简体   繁体   English

从数据层中删除所有功能

[英]Remove all features from data layer

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. 将geojson形状文件加载到我的地图的map.data图层。 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. 直到这里我没有问题。

Later on though, I want to load another geojson file over the other one (replacing the drawn 'features' on the map). 稍后,我想在另一个上加载另一个geojson文件(替换地图上绘制的'features')。 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形状文件之前,如何清除所有要素的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层获得所有功能。

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: Explanation Map 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/

Seems that the map.data is a collection of 'feature' classes. 似乎map.data是'feature'类的集合。

So you can use the map.data to iterate through and remove each feature in the collection 因此,您可以使用map.data迭代并删除集合中的每个功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM