React-google-maps: Change center and zoom after calling fitBounds

Created on 15 Dec 2017  路  5Comments  路  Source: tomchentw/react-google-maps

Hi

I'm trying to zoom in on the marker i select, and un-zoom on deselect.
After loading all the markers i use fitBounds on the map ref to show all the markers.
I use this.state.center and this.state.zoom to change the zoom.
After using fitBounds I can't change the zoom nor the center.
If I remove fitBounds zoom and center props works well.

Is there a way to get both working :-) ?

Most helpful comment

onZoomChange is not fired at all.

All 5 comments

Not sure, my best guess is you need to hook onZoomChange and onCenterChange to catch changes made by fitBounds.
Bad thing for imperative APIs.

onZoomChange is not fired at all.

I'm having the same problem. Any solutions?

I don't think center and zoom are reliable when using fitBounds (which is async)

My workaround was to modify my markers array and call fitBounds on componentWillReceiveProps

  • When a marker is clicked I change my markers array to only contain that marker, and fitBounds is called and will center and zoom on the single marker.
  • When the deselect button is clicked I restore all the markers and fitBounds will unzoom to fit the markers
const bounds = new window.google.maps.LatLngBounds();
const coordinates = this.props.locations.map(model => {
    const { latitude, longitude } = model.particulars.location.point;
    const latLng = new window.google.maps.LatLng(latitude, longitude);
    bounds.extend(latLng);
    return latLng;
});

return (
    <GoogleMap
        ref={map => map && map.fitBounds(bounds)}
        defaultZoom={8}
        defaultCenter={{ lat: -34.397, lng: 150.644 }}
        center={new google.maps.LatLng(props.latitude, props.longitude)}
        >

        {coordinates.map(({ lat, lng }) => {
            return <Marker key={hash(lat, lng)} position={{ lat: lat(), lng: lng() }} />;
        })}

    </GoogleMap>
);
Was this page helpful?
0 / 5 - 0 ratings