react-google-maps-api icon indicating copy to clipboard operation
react-google-maps-api copied to clipboard

How to re-center when clicking on a marker?

Open stesvis opened this issue 3 years ago • 1 comments

Hello, I am unable to do this, it's probably simple but I can't figure it out.

After the map is loaded, with markers, when I click on a marker I would like to re-center the map to the position of that marker. How can I do that?

Thanks.

stesvis avatar Jun 03 '22 23:06 stesvis

You want to have a state to store your map reference:

const [map, setMap] = useState()

Then on your onLoad in the map:

<GoogleMap
 .....
onLoad={(map) => setMap(map)} />

Then in your marker:

<Marker
position={position}
onClick={() => map.setCenter(position)} />

Here's a quick example of how to do it:

https://codesandbox.io/s/example-pin-click-to-center-74fpe9

Dastari avatar Jun 11 '22 06:06 Dastari