在过去几个小时里,我一直把头撞在桌子上。
我试图让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);
},
});
};

发布于 2020-07-23 15:40:46
如果有多个坐标,那么首先使用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);
}
});我已经准备好了这个小提琴与解决方案如何将边界与一串和弦相匹配与一个3弦数组,但你可以很容易地应用到你的。
这就是结果

然后点击缩放到边界

发布于 2020-07-23 15:36:04
对于fitBounds()函数,需要将越过你的界限作为LngLatBounds对象、西南、东北顺序中的LngLatLike对象数组或西、南、东、北顺序中的数字数组。Mapbox在他们的网站这里上有这样的一个例子。
如果要捕获所有标记,可以计算出坐标的最西部、南部、东部和北部值,然后将它们作为数组传递。在你的例子中:-0.54664079,51.38542169,-0.3735228,51.45368209。
mapboxgl.accessToken = 'pk.eyJ1IjoicGxtYXBib3giLCJhIjoiY2s3MHkzZ3VnMDFlbDNmbzNiajN5dm9lOCJ9.nbbtDF54HIXo0mCiekVxng';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-74.5, 40],
zoom: 9
});
document.getElementById('fit').addEventListener('click', function() {
map.fitBounds([-0.54664079, 51.38542169, -0.3735228, 51.45368209]);
}); body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
#fit {
display: block;
position: relative;
margin: 0px auto;
width: 50%;
height: 40px;
padding: 10px;
border: none;
border-radius: 3px;
font-size: 12px;
text-align: center;
color: #fff;
background: #ee8a65;
}<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Fit a map to a bounding box</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.css" rel="stylesheet" />
</head>
<body>
<div id="map"></div>
<br />
<button id="fit">Fit to Box</button>
</body>
</html>
发布于 2020-08-22 09:36:14
我不知道这与您的问题有关,但是当我在地图上的移动浏览器中发现这个错误时,我用以下代码解决了问题:
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent)) {
$('#mapContainer').css({ 'width': (($(window).width())) + 'px' });
}默认情况下,映射容器宽度为100%。
https://stackoverflow.com/questions/63056472
复制相似问题