Ludo
Ludo

Reputation: 5280

How to center the viewport from the markers at the first render?

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.

Upvotes: 0

Views: 1879

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59358

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

Upvotes: 2

Related Questions