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

U. *_*att 2 google-maps reactjs react-google-maps-api

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

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

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>
        </>
    )
}
Run Code Online (Sandbox Code Playgroud)

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

TypeError: Cannot read properties of undefined (reading 'maps').
Run Code Online (Sandbox Code Playgroud)

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

var bounds = new window.google.maps.LatLngBounds();
Run Code Online (Sandbox Code Playgroud)

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

Jus*_*elt 6

您正在加载 APIuseEffect之前执行。<LoadScript>我会做类似的事情:

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])
Run Code Online (Sandbox Code Playgroud)

map仅当 APIwindow.google.maps.***已加载时才会被定义。