mapbox-gl-js - MapboxGL : querying rendered features after multiple geocodes

标签 mapbox-gl-js

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

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

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

所以就像我说的那样,在地理编码“结果”事件上运行的所有内容在第一次通过时都有效,但似乎在第二次通过(用户搜索新地址,但不重新加载 map )queryRenderedFeatures 返回一个较小的不包括地理编码器着陆的图 block 的要素子集。

非常感谢任何建议。

最佳答案

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

所以现在的语法是:

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

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

关于mapbox-gl-js - MapboxGL : querying rendered features after multiple geocodes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44595633/

相关文章:

javascript - 如何销毁mapbox gl map 实例

reactjs - 使用 React-mapbox-gl 使用 Mapbox 渲染矢量切片

javascript - 添加额外的 onClick() 到导航控件

javascript - mapbox-gl js 对 "text-offset"使用步进斜坡

javascript - 如何包装 ui 控件(mapbox 地理定位控件)

mapbox - 如何在 Mapbox GL JS 中制作 3D 模型运动的动画

Mapbox 决定重叠顺序

Mapbox GL JS 在图层中的特定要素上设置 Paint 属性

javascript - 在create-react-app中使用react-map-gl时出错

javascript - 带有自定义标签的 Mapbox GL Popup 设置内容