zcreativelabs / react-simple-maps

Beautiful React SVG maps with d3-geo and topojson using a declarative api.
https://www.react-simple-maps.io/
MIT License
3.04k stars 424 forks source link

Is it possible to re-center the map to initial position? #242

Closed mkarajohn closed 3 years ago

mkarajohn commented 3 years ago

Sorry that this is not an actual issue.

I would like to implement a button that when clicked would re-center the map after it has been dragged.

The center prop on ZoomableGroup only sets the initial center and after that it does nothing.

My current solution is to have a state with the center coords, starting with [0, 0] and when that button is clicked I run

  function handleCenter() {
    setCenterCoords([1, 1]);
    setTimeout(() => {
      setCenterCoords([0, 0]);
    }, 0);
  }

which is a hack, I force a re-render to [0, 0] by first setting the center to [1, 1]. It works though.

Is there a better way? Thanks.

zimrick commented 3 years ago

Hi @mkarajohn,

Yes, the center prop on its own cannot do that, since your center state outside of react-simple-maps doesn't know that it has been changed when the map was dragged or zoomed. There is a way of solving this quite nicely with react-simple-maps though. You can use the dedicated onMoveEnd prop, which will give you the final coordinates and zoom after panning and zooming manually on the map.

Here's a codesandbox that shows how to do this: https://codesandbox.io/s/react-simple-maps-recentering-if7nt?file=/src/MapChart.js

Note: In order to limit renders with useState I combined the center and zoom into one array of three values. You could also work with a reducer instead to make the code more legible, but I think for a small proof of concept this is ok.

Hope this helps!

mkarajohn commented 3 years ago

Ah, thanks @zimrick

That was actually my initial approach to the problem, but setting the coords on moveEnd, always had the map jump a little off by a random offset each time.

Peek 2020-12-23 01-23

Probably this was due to me still using 1.0.0 , but glad you validated my initial approach. Thanks and happy holidays