reactjsgoogle-mapsgoogle-maps-react

Google Maps fitBounds not centering and showing markers in google-maps-react


I'm using google-maps-react in my react app to use GMaps. This is the code I got:

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) => {
        const { google } = mapProps;

        markers.forEach(marker => {
            bounds.extend(new google.maps.LatLng(marker.lat, marker.lng));
        });
    
        map.fitBounds(bounds);
    }

    return (
        <>
        <div className={props.className}>
            <Map 
                google={props.google}
                style={{ borderRadius: '10px'}}
                zoom={7}
                onReady={adjustMap}
                bounds={bounds}
                initialCenter={{ lat: 47.444, lng: -122.176}}
            >
                {
                    markers.map((item) => {
                        return (
                            <Marker position={{lat: item.lat, lng: item.lng}}/>
                        )
                    })
                }       
            </Map>
        </div>
        <button onClick={(e) => { e.preventDefault(); const newMap = [...markers, {lat: 59.913, lng: 10.752}]; setMarkers(newMap)}}>Add marker</button>
        </>
    );  
}

So initially, the map is centered properly, as it shows the two markers. But when I click on the button to add another marker, it just shows a random area where none of the markers are visible.

I referred to what tidyline suggested in this thread modified it slightly to fix the errors, but that didn't work. - https://github.com/fullstackreact/google-maps-react/issues/63

How can I fix this to show all the markers when other markers are added?


Solution

  • There are two issues going on:

    1. onReady={adjustMap} will only execute once and not after adding more markers
    2. you click handler sets a hard coded location for the marker and the bounds of the map is not updated with this new marker. maybe call adjustMap from the handler?