MapboxGL:在多次地理编码后查询呈现的特征

MapboxGL: querying rendered features after multiple geocodes

情况:我有一个工作站点,输入地址后,MapboxGL 会在地图上标记一个点并查询多边形图层 (queryRenderedFeatures) 并显示包含该点的多边形要素。

这行得通;但是,如果我随后想对更改地图视图的第二个地址进行地理编码,则会第二次失败,因为 map.queryRenderedFeatures returns 一个空数组。

var userDistrictsGeoJson;

map.on('load', function() {
  //add layers from Mapbox account
  addLayers(); //details left out of example, but this works.
  // Listen for geocoding result
  // This works the first time through, but fails if the user searchs for a second address because queryRenderedFeatures is working with a smaller set of features
  geocoder.on('result', function(e) {
    //need to clear geojson layer and 
    userDistrictsGeoJson = {
        "type": "FeatureCollection",
        "features": []
    };

    map.getSource('single-point').setData(e.result.geometry);
    //project to use (pixel xy coordinates instead of lat/lon for WebGL)
    var point = map.project([e.result.center[0], e.result.center[1]]);  

    var features = map.queryRenderedFeatures(point, { layers: ['congress-old'] });

    var filter = featuresOld.reduce(function(memo, feature){
      // console.log(feature.properties);
      memo.push(feature.properties.GEOID);
      return memo;
    }, ['in', 'GEOID']);

    map.setFilter('user-congress-old', filter);

    var userCongressOldGeoJson = map.querySourceFeatures('congressional-districts', {
      sourceLayer: 'congress_old',
      filter: map.getFilter('user-congress-old')
    });

    userDistrictsGeoJson.features.push(userCongressOldGeoJson[0]);

    var bbox = turf.bbox(userDistrictsGeoJson);
    var bounds = [[bbox[0], bbox[1]], [bbox[2], bbox[3]]];

    map.fitBounds(bounds, {
      padding: 40
    });

  }); //geocoder result
}); //map load

就像我说的,在地理编码 'result' 事件上运行的所有内容在第一次通过时都有效,但似乎在第二次通过时(用户搜索新地址,但不重新加载地图) queryRenderedFeatures returns 较小的要素子集,不包括地理编码器着陆的图块。

非常感谢任何建议。

我最终通过在 'moveend' 事件上触发一次查询代码解决了这个问题。

所以现在的语法是:

geocoder.on('result', function(e){
    map.once('moveend', function(){
        .... rest of code
    }
}

我以为我在发布问题之前已经尝试过了,但现在似乎对我有用。