Mapbox fitbounds() - 无效的 LngLat 对象:(NaN, NaN)

Ben*_*ngy 6 mapbox mapbox-gl mapbox-gl-js

在过去的几个小时里,我一直用头撞桌子。

我试图让 Mapbox 放大所有标记的边界区域的负载。

但是,这是我在下面的代码中遇到的错误。

此错误出现在下面的控制台日志图像之后,因此 lat lng 坐标肯定存在。

未捕获的错误:无效的 LngLat 对象:(NaN,NaN)

  const onLoad = () => {

    let points = [];

    props.cats.forEach(cat => (
      points.push([ cat.lat, cat.lng ])
    ));

    points.length > 0 && ref.current.getMap().fitBounds(points, {
      padding: { top: 50, bottom: 50, left: 50, right: 50 },
      easing(t) {
          return t * (2 - t);
      },
    });

  };
Run Code Online (Sandbox Code Playgroud)

控制台点日志

San*_*mar 11

就我而言,当填充值较高时,我遇到了相同的错误。

//this did not work
map.fitBounds(fitBounds, {padding: 150});
    
//this worked
map.fitBounds(fitBounds);
Run Code Online (Sandbox Code Playgroud)


jsc*_*tro 5

如果有多于一对坐标,则应首先使用 缩小数组coordinates.reduce,然后通过 定义边界new mapboxgl.LngLatBounds。之后,您可以尽情发挥map.fitBounds,像在代码中一样定义您最喜欢的填充和缓动函数。

var coordinates = points;

var bounds = coordinates.reduce(function(bounds, coord) {
  return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

map.fitBounds(bounds, {
  padding: { top: 50, bottom: 50, left: 50, right: 50 },
  easing(t) {
      return t * (2 - t);
  }
});
Run Code Online (Sandbox Code Playgroud)

我已经准备了这个小提琴解决方案如何将边界适应具有 3 个坐标数组的坐标列表,但您可以轻松应用到您的坐标。

这就是结果 在此输入图像描述

然后点击缩放至边界 在此输入图像描述