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

标签 mapbox mapbox-gl-js mapbox-gl

过去几个小时我一直在用头撞 table 。

我正在尝试让 Mapbox 放大加载到我所有标记的边界区域。

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

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

Uncaught Error: Invalid LngLat object: (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);
      },
    });

  };

Console log of points

最佳答案

如果您有不止一对坐标,您应该先使用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);
  }
});

我已经用解决方案准备了这个 fiddle how to fit bounds to a list of coords具有 3 个坐标的数组,但您可以轻松地应用于您的坐标。

这是结果 enter image description here

然后点击 Zoom to bounds enter image description here

关于Mapbox fitbounds() - 无效的 LngLat 对象 : (NaN, NaN),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63056472/

相关文章:

iOS Mapbox : Map offline + Price

mapbox - 如何使用流程配置mapbox-gl-js类型?

webpack - 在 webpack 中使用 mapbox-gl 和 @mapbox/mapbox-gl-draw

Mapbox GL : Get Layer IDs

缺少 Mapbox 要素 ID 参数

ios - map 框。 layerForAnnotation 未被调用。绘图形状

javascript - Mapbox GL - 如何在悬停时更改 geojson 线的宽度?

javascript - 是否可以从 Mapbox 前端 map 创建静态 map ?

javascript - 删除 Mapbox GL JS 上的所有标签?

mapbox - 将坐标转换为屏幕上的像素(然后再转换回来)