Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading