Search code examples
reactjsgoogle-mapsgoogle-maps-react

can't drag to move, zoom in or out google-maps-react


I'm trying to display a couple of markers in a map. On button click, I add in a marker and recenter the map to show all the markers.

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>
        </>
    );  
}

Now the issue is, I can't drag to move the map, nor can I zoom in or out. If I remove the onBoundsChanged property, I can drag and zoom, but if I include it, dragging and zooming doesn't work.

How can I fix this?


Solution

  • You are in an infinite loop since because react is not doing a deep diff on your props and your props are continuously changing because it is a new LatLngBounds object over and over and over. Try passing primitives as props instead of an object.

    See https://github.com/googlemaps/js-samples/issues/946 for further discussion around this.