react-google-maps-api
react-google-maps-api copied to clipboard
onZoomChanged how to access zoom value?
Issue template
If you want to ask question, ask it in Github Discussions, Spectrum.chat or Slack channel
Please do not post unformatted code into issues, and please do not ask questions. Only real issues, PR or feature requests allowed. Minimal reproduction in codesandbox.io is must have.
Please provide an explanation
The center and zoom are tied to a bit of state, but other events can trigger a map re-render. So the local to map zoom and center is lost because the state was never updated when the user drags or zooms
Your Environment
os: mac/linux/windows/android/ios
node --version v15.6.0
react version "^17.0.2"
webpack version
@babel version
@react-google-maps/api version "^2.4.0"
How is it behave?
<GoogleMap
mapContainerStyle={{
//width: '100vw',
width: mapWidth,
height: '100vh',
//height: mapHeight, // when turn bottom bar back on use this
marginLeft: '262px',
//paddingLeft: '262px',
}}
center={{ lat: mapCenterLat, lng: mapCenterLng }}
zoom={mapZoom}
onLoad={onLoad}
onUnmount={onUnmount}
//PATCH WANDERING CENTER
onZoomChanged={ (event) => {
//reCenterZoomHelper(event)
console.log("onZoomChanged", event, GoogleMap.getZoom() );
} }
onDragEnd={ (event) => {
console.log("onDragEnd", event);
}}
>
The onChange events are firing, but no values are returned so I have no values to set to setMapZoom
or the mapCenter
state
How should it behave correctly?
I am expecting to in some way be able to access or get the current zoom or center values when the events fire, so they can then be used to update the state.
basic implementation of incorrect behavior in codesandbox.com
From the onLoad you should have assigned the map as a local state variable, mapInstance. you can grab the center and zoom from the mapInstance.
center: mapInstance.center.lat()
and mapInstance.center.lng()
zoom: mapInstance.zoom
I eventually got there
const [map, setMap] = React.useState(null)
const onLoad = React.useCallback(function callback(map) {
const bounds = new window.google.maps.LatLngBounds();
map.fitBounds(bounds);
setMap(map)
}, [])
setMapZoom(map.zoom)
Aso map.mapUrl
and map.getBounds()
did have usful info