I am using the react-google-maps
package in my app. I want to access the Map.setZoom() method but I am getting
TypeError: Object doesn't support property or method 'setZoom'
Interestingly, the Map.panTo()
method works just fine. They should both be members of the Map object.
https://developers.google.com/maps/documentation/javascript/reference/3.exp/map#Map.panTo https://developers.google.com/maps/documentation/javascript/reference/3.exp/map#Map.setZoom
withHandlers(() => {
const refs = {
map: undefined
}
return {
onMapMounted: () => ref => {
refs.map = ref
},
onClick: () => () => {
console.log("Getting location...");
navigator.geolocation.getCurrentPosition(
position => {
const coords = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log(coords);
refs.map.panTo(coords); // This line works
refs.map.setZoom(8); // This line throws a Type Error
},
error => {
console.log("Error" + error.code);
}
);
}
}
}),
...
Here is my entire component definition, loosely based on the react-google-maps
documentation https://tomchentw.github.io/react-google-maps/#googlemap
const Map = compose(
withProps({
googleMapURL: `${url}`,
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withHandlers(() => {
const refs = {
map: undefined
}
return {
onMapMounted: () => ref => {
refs.map = ref
},
onClick: () => () => {
console.log("Getting location...");
navigator.geolocation.getCurrentPosition(
position => {
const coords = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log(coords);
refs.map.panTo(coords);
refs.map.setZoom(8);
},
error => {
console.log("Error" + error.code);
}
);
}
}
}),
withScriptjs,
withGoogleMap
)((props) =>
<GoogleMap
defaultZoom={4}
defaultCenter={DefaultCoords}
ref={props.onMapMounted}
>
<OverlayView
position={DefaultCoords}
mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
getPixelPositionOffset={getPixelPositionOffset}
>
<div style={{ background: `white`, border: `1px solid #ccc`, padding: 15 }}>
<button onClick={props.onClick}>Use GPS</button>
</div>
</OverlayView>
{props.isMarkerShown && <Marker position={DefaultCoords} />}
</GoogleMap>
);
Indeed GoogleMap
class of react-google-maps
library does not expose setZoom
method yet.
One solution would be to access google.maps.Map
class directly and set zoom as demonstrated below:
1) get access to google.maps.Map
instance:
onMapMounted: () => ref => {
refs.map = ref
refs.mapObject = ref.context[MAP]; //<-access google.maps.Map instance
}
2) where MAP
is a constant from:
import {MAP} from 'react-google-maps/lib/constants'
3) set zoom:
refs.mapObject.setZoom(8);