0

I know with the native Google Map API we can do something like:

const bounds = new google.maps.LatLngBounds();

const marker = new google.maps.Marker({ // wrap that into a loop to add multiple points
  position: new google.maps.LatLng(lat, lng),
  map: map
});

bounds.extend(marker.position);

map.fitBounds(bounds);

But with react-google-maps, markers are components, so i guess there is another way. Creating the markers (as components) works fine, is there an option or something to center the viewport from it?

I hope we don't have to create it as components and re-create it as we would do with the native library.

Ludo
  • 5,060
  • 15
  • 53
  • 85

1 Answers1

2

In case react-google-maps viewport could be centered for the given markers like this:

lifecycle({
    componentDidMount() {

        this.setState({
            zoomToMarkers: map => {
                const bounds = new window.google.maps.LatLngBounds();
                map.props.children.forEach((child) => {
                    if (child.type === Marker) {
                        bounds.extend(new window.google.maps.LatLng(child.props.position.lat, child.props.position.lng));
                    }
                })
                map.fitBounds(bounds);
            }
        })
    },
})

where

<GoogleMap ref={props.zoomToMarkers} defaultZoom={5} defaultCenter={{ lat: 25.0391667, lng: 121.525 }}>
    {props.markers.map(marker => (
        <Marker
            key={marker.id}
            position={{ lat: marker.lat, lng: marker.lng }}
        />
    ))}
</GoogleMap>

Demo

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • 1
    Hello! I followed your method, it works great on the map page but if I got to other pages there will be an unmounted error. May I know that where I did wrong? Thank you. Please check my code here:https://stackoverflow.com/questions/57527858/in-react-google-maps-try-to-use-fitbounds-in-componentdidmount-lifecycle-but-get – Ying Aug 16 '19 at 18:19