Minimal useMap() example? #322
-
I've read the docs and a few related discussions, but I am still struggling to understand how to use Could we please have a minimal example in the docs? My particular use-case is to adjust the bounds to reveal all the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
So you can essentially use the So this will not work: const App = () => {
// the hook is being used outside of the APIProvider, so it can't
// look up any map instances etc. (this will also log an error to the console)
const map = useMap();
return (
<APIProvider>
<Map {...mapProps} />
</APIProvider>
);
}; This is why we recommend putting the const App = () => {
return (
<APIProvider>
<CustomMap />
</APIProvider>
);
};
const CustomMap = () => {
const markerLocations = [/* whatever you need to get those... */];
const map = useMap();
const fitMapToToMarkers = useCallback(() => {
if (!map) return;
const bounds = new google.maps.LatLngBounds();
for (const latLng of markerLocations) {
bounds.extend(latLng);
}
map.fitBounds(bounds);
}, [map]);
// decide how you want to trigger `fitMapToMarkers`, via a button, when data changes, ...
return (
<Map {...mapProps}>
{markerLocations.map(latLng => (<AdvancedMarker location={latLng} />))}
</Map>
);
}; |
Beta Was this translation helpful? Give feedback.
-
As for the request for documentation, can you elaborate what we could do to improve the documentation here: https://visgl.github.io/react-google-maps/docs/api-reference/hooks/use-map ? |
Beta Was this translation helpful? Give feedback.
oh damn... That's a mistake that had to happen at some point.
The
<Map id='some-id'>
andmapId
are completely separate concepts, the firstid
can be used for theuseMap
hook to find your map if there's more than one map and that map isn't a parent component, and themapId
is the thing you get for the cloud-based map styling (that's the one you need when you want to use AdvancedMarkers).If you only have a single map, you don't need to set the
id
prop (it will internally use the iddefault
).