过去几个小时我一直在用头撞 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);
},
});
};
最佳答案
如果您有不止一对坐标,您应该先使用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 个坐标的数组,但您可以轻松地应用于您的坐标。
关于Mapbox fitbounds() - 无效的 LngLat 对象 : (NaN, NaN),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63056472/