我试着在地图上显示几个标记。在单击按钮时,我添加一个标记并重新输入地图以显示所有标记。
function MapContainer(props) {
var bounds = new props.google.maps.LatLngBounds();
const [markers, setMarkers] = useState([
{
lat: 55.378,
lng: 3.436
},
{
lat: 37.0902,
lng: 95.712
}
]);
const adjustMap = (mapProps, map) => {
map.fitBounds(bounds);
}
useEffect(() => {
for (var i = 0; i < markers.length; i++)
bounds.extend(new props.google.maps.LatLng(markers[i].lat, markers[i].lng))
}, [markers])
return (
<>
<div className={props.className}>
<Map
google={props.google}
style={{ borderRadius: '10px'}}
zoom={7}
bounds={bounds}
onBoundsChanged={adjustMap}
>
{
markers.map((item) => {
return (
<Marker position={{lat: item.lat, lng: item.lng}}/>
)
})
}
</Map>
</div>
<button onClick={(e) => { e.preventDefault(); console.log("hehe"); const hoho = [...markers, {lat: 59.913, lng: 10.752}]; setMarkers(hoho)}}>Add marker</button>
</>
);
}
现在的问题是,我不能拖动来移动地图,也不能放大或缩小。如果我删除onBoundsChanged属性,我可以拖动和缩放,但如果我包括它,拖动和缩放不起作用。
我怎么才能解决这个问题?
发布于 2022-02-01 01:44:13
您处于一个无限循环中,因为react并没有对您的道具造成很大的差异,而且您的道具也在不断地变化,因为它是一个新的LatLngBounds对象,一遍又一遍。尝试将原语作为道具而不是对象传递。
有关这方面的进一步讨论,请参见https://github.com/googlemaps/js-samples/issues/946。
https://stackoverflow.com/questions/70931535
复制相似问题