【问题标题】:How to remove data from a Google Maps Data Layer?如何从 Google 地图数据层中删除数据?
【发布时间】:2014-05-29 02:27:40
【问题描述】:

我看到谷歌地图支持 geojson。在这里查看文档: https://developers.google.com/maps/documentation/javascript/datalayer#load_geojson

鉴于“Google”的最后一个示例,我怎样才能使我可以单击一个按钮来添加一个新的 Geojson 图层,以及另一个按钮来切换/删除“Google”甚至是一个字母?在我看来, map.data 似乎是单层,而不是多层。

【问题讨论】:

    标签: javascript google-maps-api-3


    【解决方案1】:

    您是正确的,因为数据层是单层。但是,如果您手动检索 GeoJSON 并使用 addGeoJson 函数而不是 loadGeoJson 您将获得返回的附加功能。您可以稍后将其删除。

    所以不是

    map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json');
    

    您可以这样做(本示例使用 jQuery 获取数据并假设有一个 ID 为 removeBtn 的按钮):

    // Load the GeoJSON manually (works cross-origin since google sets the required HTTP headers)
    $.getJSON('https://storage.googleapis.com/maps-devrel/google.json', function (data) {
      var features = map.data.addGeoJson(data);
    
      // Setup event handler to remove GeoJSON features
      google.maps.event.addDomListener(document.getElementById('removeBtn'), 'click', function () {
        for (var i = 0; i < features.length; i++)
          map.data.remove(features[i]);
      }); 
    }); 
    

    (See this JSbin for a working example you can play around with)

    在更复杂的情况下,您可能必须跟踪用户加载的数据源以及因此创建的功能,以便您可以在请求时删除它们。

    【讨论】:

    • 谢谢。这回答了我已经研究了几个小时的一个不同但相似的问题。
    • @mensi 谢谢!这也帮助我解决了一个问题。您能否详细说明为什么必须遍历 features var 以及为什么不能只添加 map.data.remove(features)?
    【解决方案2】:

    虽然map.data 被设计为单个数据源的常见情况的占位符,但您可以拥有多个,但仍可以使用addGeoJSon,使用如下方式:

    // load data - do the same for data2, data3 or whatever
    data1 = new google.maps.Data();
    data1.loadGeoJson(url1);
    
    // create some layer control logic for turning on data1
    data1.setMap(map) // or restyle or whatever
    
    // turn off data1 and turn on data2
    data1.setMap(null) // hides it
    data2.setMap(map) // displays data2
    

    【讨论】:

    • jlivni 解决方案不起作用:addGeoJson 方法似乎需要一个特征对象。 >InvalidValueError: 不是 Feature 或 FeatureCollection
    • 感谢您的收获;我的意思是 loadGeoJson(它接受一个 url)不是 addGeoJson;修正我的答案。
    【解决方案3】:

    这对我有用:

    map.data.forEach(function(feature) {
        // filter...
        map.data.remove(feature);
    });
    

    【讨论】:

      【解决方案4】:

      作为@mensi 回答的后续行动,跟踪从不同数据源加载的不同特征集可能很重要。您可以通过为每个功能添加一个属性来做到这一点:

      feature.setProperty('kind', 'region');
      feature.setProperty('kind', 'lake');
      

      但是,创建多个数据层可能更容易。默认情况下,Google 地图以单个数据层开始,但您不限于此。你可以这样做:

      var datalayer = new google.maps.Data({ map: mymap });
      

      (设置map 选项很重要,否则您的数据层将不会显示。)

      这样,可以更轻松地按层对要素进行分组,以及打开或关闭整个层。

      【讨论】:

        猜你喜欢
        • 2012-11-08
        • 1970-01-01
        • 1970-01-01
        • 2018-11-01
        • 1970-01-01
        • 2013-11-06
        • 2014-01-31
        • 1970-01-01
        • 2019-11-05
        相关资源
        最近更新 更多