如何从Mapbox GL JS中的样式层获取要素? [英] How get features from a style's layer in Mapbox GL JS?
问题描述
我是一名JavaScript学习者,并且对Mapbox GL JS有疑问:我在Mapbox Studio中有一种样式,其中有我的一层-位置" .我已将其添加为图块.这一层有两个 GeoJSON 点,但我无法在 GL JS 中获取它们.我发现我应该使用方法 querySourceFeatures(sourceID,[parameters])
,但是我在正确填充其参数时遇到了问题.我写道:
I'm a learner of JavaScript and have a problem with Mapbox GL JS: I have a style in Mapbox Studio, where there is one my layer — "locations". I've added it as a tileset. There are two GeoJSON-points in this layer, but I can't get them in GL JS.
I've found that I should use method querySourceFeatures(sourceID, [parameters])
, but I have problems with correct filling its parameters. I wrote:
var allFeatures = map.querySourceFeatures('_id-of-my-tyleset_', {
'sourceLayer': 'locations'
});
..它不起作用.
更有趣的是,稍后在代码中,我将这一层与方法 queryRenderedFeatures
一起使用,没关系:
More interesting, that later in the code I use this layer with method queryRenderedFeatures
, and it's okay:
map.on('click', function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['locations']
});
if (!features.length) {
return;
}
var feature = features[0];
flyToPoint(feature);
var popup = new mapboxgl.Popup({
offset: [0, -15]
})
.setLngLat(feature.geometry.coordinates)
.setHTML('<h3>' + feature.properties.name + '</h3>' + '<p>' +
feature.properties.description + '</p>')
.addTo(map);
});
我已经阅读了很多有关在地图上添加图层的信息,并且知道答案很简单,但是我无法实现该解决方案,所以请帮忙:)
I have read a lot about adding layers on a map and know that the answer is easy, but I can't realise the solution, so help, please :)
这是 GitHub上的项目.
Here is the project on GitHub.
推荐答案
您的问题是,您的地图与默认情况下在Mapbox Studio中创建的所有地图一样,都使用自动合成.您实际上并没有一个名为 morganvolter.cj77n1jkq1ale33jw0g9haxc0-2haga
的源,而您有一个名为 composite
且包含许多子层的源.
Your problem is that your map, like all maps created in Mapbox Studio by default, uses auto-compositing. You don't actually have a source called morganvolter.cj77n1jkq1ale33jw0g9haxc0-2haga
, you have a source called composite
with many sub layers.
您可以找到这样的图层列表:
You can find the list of layers like this:
map.getSource('composite').vectorLayerIds
这表明您有一个名为 akkerman
的矢量图层.(" locations
"是您的 style 层的名称,而不是您的 source 层的名称).因此,您的查询应为:
Which reveals you have a vector layer called akkerman
. ("locations
" is the name of your style layer, not your source layer). Hence your query should be:
map.querySourceFeatures('composite', {
'sourceLayer': 'akkerman'
});
将返回4个特征.
这篇关于如何从Mapbox GL JS中的样式层获取要素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!