React-google-maps: setZoom, setCenter not working

Created on 14 Jan 2016  路  27Comments  路  Source: tomchentw/react-google-maps

It seems that setZoom and setCenter are not available on the component. Can these functions be called in a different way? If not, please consider this a request to make them available.

Most helpful comment

Don't call setZoom or setCenter. Change the props pass in to <GoogleMap> like this:

<GoogleMap
   zoom={this.state.zoom}
/>

All 27 comments

You have access to the google map instance into the props of <GoogleMap /> component.

Here's a snippet:

onGoogleMapLoad = ({ props: { map } }) => {
    // Save google map instance
    // on the parent component
    this._map = map;
  }

render() {
  return (
    <ScriptjsLoader
              hostname={ 'maps.googleapis.com' }
              pathname={ '/maps/api/js' }
              query={ { v: 3, libraries: 'drawing' } }
              loadingElement={ <div /> }
              containerElement={ <div style={ { height: '100%' } } /> }
              googleMapElement={
                <GoogleMap
                  ref={ this.onGoogleMapLoad }
                  defaultZoom={ 3 }
                  defaultCenter={ { lat: -25.363882, lng: 131.044922 } } />
              } />
  );

Don't call setZoom or setCenter. Change the props pass in to <GoogleMap> like this:

<GoogleMap
   zoom={this.state.zoom}
/>

@tomchentw Yes it's good for initialization, but for instance there's no way to call fitBounds() see this code snippet:

  moveMapCurrentPosition = () => {
    const { userLocation, corners } = this.props;
    const { mapInstance } = this.state;

    // * go to position on map
    // * fit in bounds 3 nearest corners
    if (mapInstance && userLocation) {
      // create a bound object with the user location and three nearest corners
      const bounds = new window.google.maps.LatLngBounds();
      const userPos = new window.google.maps
        .LatLng(userLocation.latitude, userLocation.longitude);

      // add user location and thre nearest stores in bounds
      bounds.extend(userPos);
      take(corners, 3).forEach(({ latitude, longitude }) => {
        const cornerPos = new window.google.maps.LatLng(latitude, longitude);
        return bounds.extend(cornerPos);
      });

      mapInstance.setCenter(userPos);
      mapInstance.fitBounds(bounds);
    }
  }

looking forward for this solution as well

We're looking into this!

We're also looking for maintainers. Involve in #266 to help strengthen our community!

+1 for setCenter

@nodegin you can just use:

<GoogleMap center={this.state.center} />

to change the center of the map. There's no need for a setCenter function.

Also, 6.0.0 is released on npm beta tag now. We also have a new demo page. Feel free to try it:
https://tomchentw.github.io/react-google-maps/

@tomchentw I'm not sure if I was using it in a correct way, I specify a center prop object which contains the initial coordinate, then I modify the center coordinate in a click event which opens a panel, but once I dismiss the panel the map should able for dragging. However, the center variable locks my map movement.

If I use mapRef.panTo then the problem is solved perfectly by just calling it when my panel is being opened, but I don't want the panning animation (since it's causing lag on mobile).

@nodegin could you try if setting a center props locks the map movement in 6.0.0?

@tomchentw I'm not using v6, let me try it later. By the way I got it working by using mapRef.props.map.setCenter hope this help anyone who having the same problem.

I'm finding that changing the center and zoom props isn't affecting the map on re-renders (v6.0.1). I have to manually call panTo() based on the updated props and I haven't figured out a way to reflect the changes to zoom level yet.

Same problem here, i can set zoom the first time, but then if user change zoom manually, the props do not effect the component anymore.

to change the center of the map. There's no need for a setCenter function.

Are you serious? That's very confusing that underlying Google Maps API is being called either by passing component property or by calling its method. Any component API must be unified!

Also having this issue with updating zoom level - anyone have any workarounds in the meantime?

@barnc Unfortunately, no, I ended up rebuilding on another Google Maps component for React.

This may or may not be relevant, but if you use Redux, this isn't a problem (in my experience). If you set center and zoom by assigning them values from props and you are changing zoom and center via action --> reducer --> new state, then the map re-renders on every change. The user can still control the map entirely.

I believe this would also work with normal react state...but have not tried.

What are the use cases for needing setState and setZoom?

I do believe there are good use cases for setZoom, etc. One glaring issue is once you call fitBounds, the map no longer responds to state/prop changes.

I've created a pull request exposing these methods: https://github.com/tomchentw/react-google-maps/pull/455

One setCenter use case

User has a google map, and threw a toggle view, he can switch his recorded map presets (with differnet centers, radius, ..)

Solution without setCenter: redux?

In my head, the only suitable solution for this use case, is to use redux:

  • we have mapCenter in the store
  • mapCenter is used to set the defaultCenter
  • onMapMove update mapCenterin the store

Questions

  • How can we depend of a center object, coming from props, if we want to let the user move the map, and change dynamically the map center when changing map preset. (withoutonMapMoveevent)
  • Is kind of onMapMoveevent does at least exist to get current center coords?
  • I guess updating the store and re-render on each move will give bad performances, does it?
  • How much work/time would it take to implement/link this feature to the google map?

Beyond my use case

In my opinion, the setCenterfunction would be very interesting if we need :

  • a defaultCenter (which can comes from props)
  • to let the user moove the map (we don't care about center -> more performant?)
  • to update programmatically this._mapRef.setCenter(userMapX.coords) 馃帀

Waiting for your lights

@nodegin, mapRef.props.map.setCenter doesn't seem to exist anymore [v6.3]

Hi - did anyone get to the bottom of how do you force change the zoom? I need for the map to zoom in on searchbox entry (handlePlacesChanged()) and
this.setState({zoom: 20}); does not appear to affect the default zoom in any way. Thanks in advance!

@scronide which one did you end up switching to?

@iamwerby set it on the map component as in the first comment. You can use redux to pass it down as props or if you have a higher order component that wraps <GoogleMap /> you can set the values there and pass it down.

@oshalygin Thanks! However I handled it via fitBounds - as you could see in my pull.

console.log(this._map.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.setZoom(15));

^^ dont do what @gabrielmicko is recommending set the zoom and center appropriately as discussed in the thread

@oshalygin that one doesn't work after zooming out. (for me)

If you came here because using both center and onDragEnd was janky on beginning of drag, as mentioned above, switch from onDragEnd to onIdle. I had to switch from defaultCenter (uncontrolled) to center (controlled) as I needed to set the center programmatically. At first, I thought it wasn't going to work but simply switching from onDragEnd to onIdle and it's working great.

TLDR:

center + onIdle = 馃憤
center + onDragEnd = 馃憥
defaultCenter + (onDragEnd || onIdle) = 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

craigcartmell picture craigcartmell  路  4Comments

madbean picture madbean  路  3Comments

timkraut picture timkraut  路  3Comments

wayofthefuture picture wayofthefuture  路  3Comments

manoj150283 picture manoj150283  路  3Comments