如何从Mapbox GL JS中的样式层获取要素?

nik*_*zza 4 javascript mapbox mapbox-gl-js

我是JavaScript的学习者,对Mapbox GL JS有疑问:我在Mapbox Studio中有一种样式,其中一层我的图层-“位置”。我已将其添加为图块。这一层有两个GeoJSON点,但是我无法在GL JS中获得它们。我发现我应该使用method querySourceFeatures(sourceID, [parameters]),但是在正确填充其参数方面存在问题。我写:

var allFeatures = map.querySourceFeatures('_id-of-my-tyleset_', {
  'sourceLayer': 'locations'
});
Run Code Online (Sandbox Code Playgroud)

..并且不起作用。

更有趣的是,稍后在代码中我将这一层与method一起使用queryRenderedFeatures,这没关系:

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);
    });
Run Code Online (Sandbox Code Playgroud)

我已经阅读了很多有关在地图上添加图层的信息,并且知道答案很简单,但是我无法实现该解决方案,请提供帮助:)

这是 GitHub上的项目。

Ste*_*ett 5

您的问题是您的地图与默认情况下在Mapbox Studio中创建的所有地图一样,都使用自动合成。实际上morganvolter.cj77n1jkq1ale33jw0g9haxc0-2haga,您没有名为的源,而composite有许多子层的源。

您可以找到这样的图层列表:

map.getSource('composite').vectorLayerIds

这表明您有一个称为的矢量层akkerman。(“ locations”是样式层的名称,而不是层的名称)。因此,您的查询应为:

map.querySourceFeatures('composite', {
  'sourceLayer': 'akkerman'
});
Run Code Online (Sandbox Code Playgroud)

返回4个功能。