【问题标题】:Dynamic bounding box for Mapbox GeocoderMapbox Geocoder 的动态边界框
【发布时间】:2020-01-11 08:46:58
【问题描述】:

我正在尝试根据当前可见的地图边界应用 Mapbox Geocoder (Mapbox GL JS) 搜索限制。当前代码在搜索尝试时输出错误(“未捕获的异常:对象”):

   map.on('zoom', function() {
    var bounds = map.getBounds();
    geocoder.options.bbox = [bounds.getNorthEast().lng, bounds.getNorthEast().lat, bounds.getSouthWest().lng, bounds.getSouthWest().lat];
   });

这可能吗?如果是这样 - 如何更正代码?

编辑:

解决了。事实证明,bbox 参数具有从最小值到最大值而不是 LonLatBounds 顺序(NE 到 SW)的棘手顺序(特别是对于同时存在负经度和正经度的英国)。如果有人感兴趣 - 正确工作的代码将是

// notice switch from 'zoom' to 'move'
map.on('move', function() {
    var bounds = map.getBounds();

    var minLon = bounds.getNorthEast().lng;
    var maxLon = bounds.getSouthWest().lng;
    if(minLon > maxLon) {
        maxLon = minLon;
        var minLon = bounds.getSouthWest().lng;
    }
    var minLat = bounds.getNorthEast().lat;
    var maxLat = bounds.getSouthWest().lat;
    if(minLat > maxLat) {
        maxLat = minLat;
        var minLat = bounds.getSouthWest().lat;
    }
    if(minLon >= -180 && maxLon <= 180) geocoder.options.bbox = [minLon, minLat, maxLon, maxLat];
});

编辑 2:不知何故 .flat() 来自 MS Edge 中选定的回复故障。小心点。

【问题讨论】:

    标签: mapbox mapbox-gl-js mapbox-gl


    【解决方案1】:

    查看API文档https://github.com/mapbox/mapbox-gl-geocoder/blob/master/API.md#setbbox正确的方法是调用

    geocoder.setBbox([minX, minY, maxX, maxY]);
    

    map.getBounds().toArray() 返回[sw, ne] 所以你应该可以这样做:

    geocoder.setBbox(map.getBounds().toArray().flat());
    

    geocoder.options 未记录在 API 中,因此无法保证它是否会工作或是否会在新版本中继续工作。

    【讨论】:

      猜你喜欢
      • 2019-03-11
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 2018-08-27
      • 2013-05-16
      • 2021-10-02
      • 2021-02-22
      相关资源
      最近更新 更多