Reputation: 395
Whenever I use map.fitbound I get a Uncaught TypeError: map.fitBounds is not a function.
The important code snippet:
var bounds = new google.maps.LatLngBounds();
const map = useRef(null);
const getMarkers = (inPins) => {
return inPins.map((pin, pinInd) => {
bounds.extend(pin.position);
map.fitBounds(bounds);
return <Marker {...pin} key={pinInd} />
})
}
return (
<GoogleMap
ref={map}
mapContainerStyle={mapStyles}
defaultZoom={zoom}
center={center}
>
{getMarkers(pins)}
</GoogleMap>
)
I'm not sure what I did wrong. The bounds variable seems to be working fine with the positions, it's just that the map somehow does not have the fitbound function even though google map should should have it and it's been referenced in a lot of tutorials. Any help is appreciated, thank you!
Upvotes: 0
Views: 1346
Reputation: 3454
When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its
current
. docs
map
isn't an instance of a google.maps.Map
. It is actually, a React ref and needs to be accessed via .current
. You probably also want to check if map.current
is defined before usage.
if (map.current) {
map.current.fitBounds(bounds);
Since this is confusing, it might make sense to rename the ref from map
to mapRef
or similar.
Upvotes: 1