gpt4 book ai didi

reactjs - 如何在添加标记时重新居中 react-google-maps

转载 作者:行者123 更新时间:2023-12-01 23:05:44 26 4
gpt4 key购买 nike

我正在使用 @react-google-maps/api 在 map 中显示一些标记。

我想在单击按钮时添加另一个标记,添加标记后,我希望 map 居中显示所有标记。据此,我是这样写的:

const center = {
lat: 55.378,
lng: 3.436
};

const containerStyle = {
borderRadius: '10px',
width: '100%',
height: '100%'
}

function Map(props) {
const [map, setMap] = useState();
const [markers, setMarkers] = useState([
{
lat: 51.378,
lng: 3.436
},
{
lat: 47.0902,
lng: -125.712
}
]);

useEffect(() => {
var bounds = new window.google.maps.LatLngBounds();
for(var i = 0; i < markers.length; i++) {
bounds.extend( new window.google.maps.LatLng(markers[i].lat, markers[i].lng));
}

map.fitBounds(bounds)
}, [markers])

const onLoad = React.useCallback(function callback(map) {
const bound = new window.google.maps.LatLngBounds();
setBounds(bound)
map.fitBounds(bound);
setMap(map)
}, [])

return (
<>
<div className={props.className}>
<LoadScript
googleMapsApiKey="API_KEY"
>
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={10}
onLoad={onLoad}
>
{
markers.map((item) => {
return (
<Marker animation="DROP" position={{lat: item.lat, lng: item.lng}}/>
)
})
}
</GoogleMap>
</LoadScript>
</div>
<button onClick={(e) => { e.preventDefault(); console.log("hehe"); const hoho = [...markers, {lat: 59.913, lng: 10.752}]; setMarkers(hoho)}}>Add marker</button>
</>
)
}

但是当我运行代码时,这是我得到的错误:

TypeError: Cannot read properties of undefined (reading 'maps').

正是 useEffect 中的这一行给我错误:

var bounds = new window.google.maps.LatLngBounds();

如何获得正确的边界值?我尝试创建一个状态变量并在 onLoad() 中获取它后更新该值,但这也不起作用。我该如何解决这个问题?

最佳答案

你的 useEffect<LoadScript> 之前执行已加载 API。我会做类似的事情:

useEffect(() => {
if (map) {
var bounds = new window.google.maps.LatLngBounds();
for(var i = 0; i < markers.length; i++) {
bounds.extend( new window.google.maps.LatLng(markers[i].lat, markers[i].lng));
}
map.fitBounds(bounds)
}
}, [markers, map])

map将仅在 API window.google.maps.*** 时被定义已加载。

关于reactjs - 如何在添加标记时重新居中 react-google-maps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70931285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com