首页 > 解决方案 > Mapbox queryRenderedFeatures on load

问题描述

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

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

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

页面加载后执行的 JavaScript

页面加载完成后调用函数

这就是我现在所拥有的

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);
});

标签: javascriptmapboxmapbox-gl-js

解决方案


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

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

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


推荐阅读