lee*_*um1 6 javascript mapbox mapbox-gl-js
我想在页面加载后使用 queryRenderedFeatures 来填充列表,但它似乎在加载图层之前不断触发。我在下面的控制台中收到错误消息:
The layer 'Points' does not exist in the map's style and cannot be queried for features.
Run Code Online (Sandbox Code Playgroud)
要素加载后如何查询图层?我尝试遵循这些答案中的建议,但它一直返回空
这就是我现在所拥有的
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);
});
Run Code Online (Sandbox Code Playgroud)
我从上一个答案中的 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.
}
Run Code Online (Sandbox Code Playgroud)
map.on('load', function() {});一定要和要查询的图层放在同一层。
来自https://github.com/mapbox/mapbox-gl-js/issues/4222#issuecomment-279446075:
您可以检查map.loaded()(https://www.mapbox.com/mapbox-gl-js/api/#map#loaded)以确定地图是否已加载以及查询要素是否安全。
有关示例代码,请参阅 GitHub 上链接的问题评论。