【问题标题】:Mapbox queryRenderedFeatures on loadMapbox queryRenderedFeatures on load
【发布时间】:2018-11-15 05:41:50
【问题描述】:

我想在页面加载后使用 queryRenderedFeatures 来填充列表,但它似乎在加载图层之前一直触发。我在下面的控制台中收到错误消息:

The layer 'Points' does not exist in the map's style and cannot be queried for features.

特征加载后如何查询图层?我尝试按照这些答案中的建议进行操作,但它一直返回空

JavaScript that executes after page load

call a function after complete page load

这就是我现在拥有的

map.on('load', function() {
  map.addLayer({
      'id': 'Points',
      'type': 'circle',
      'source': 'Points-45d56v',
      'source-layer': 'Points-45d56v',
      'layout': {
          'visibility': 'visible',
      },
      'paint': {
        'circle-radius': 6,
        'circle-color': 'red'
      }
  });
});

$(document).ready(function(){
  var features = map.queryRenderedFeatures({layers:['Points']});
  console.log(features);
});

【问题讨论】:

    标签: javascript mapbox mapbox-gl-js


    【解决方案1】:

    我从上一个答案中的 Github 链接中获得了以下代码,这对我有用:

    map.addLayer(...) // make your change
    map.on('render', afterChangeComplete); // warning: this fires many times per second!
    
    function afterChangeComplete () {
      if (!map.loaded()) { return } // still not loaded; bail out.
    
      // now that the map is loaded, it's safe to query the features:
      map.queryRenderedFeatures(...);
    
      map.off('render', afterChangeComplete); // remove this handler now that we're done.
    }
    

    一定要和要查询的图层放在同一个map.on('load', function() {});

    【讨论】:

      【解决方案2】:

      来自https://github.com/mapbox/mapbox-gl-js/issues/4222#issuecomment-279446075

      您可以检查map.loaded() (https://www.mapbox.com/mapbox-gl-js/api/#map#loaded) 来确定地图是否已加载以及是否可以安全地查询要素。

      示例代码见 GitHub 上的链接问题评论。

      【讨论】:

        猜你喜欢
        • 2022-08-19
        • 1970-01-01
        • 2018-09-03
        • 1970-01-01
        • 2021-10-22
        • 1970-01-01
        • 1970-01-01
        • 2011-07-11
        • 2011-01-27
        相关资源
        最近更新 更多