Auto center coordinate and zoom for multiple markers #2877
-
Hello, I want to show dynamic multiple markers on the map. What I mean by dynamic markers is the markers are determined by the user selection (which markers do the user want to show). I found an algorithm to count the center coordinate of multiple markers here https://stackoverflow.com/questions/10634199/find-center-of-multiple-locations-in-google-maps but only for the center coordinate (not with the best zoom level) and it's written with the original google maps api How could I do search for the center coordinate and zoom for multiple markers with this |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Finally, I can use auto zoom and center with this library. It's called After reading the It worked. |
Beta Was this translation helpful? Give feedback.
-
@jaballogian Could you please more simplify answer, because currently i am facing same problem... |
Beta Was this translation helpful? Give feedback.
-
https://www.npmjs.com/package/@react-google-maps/api Here in the example, they have used the onLoad function with a useCallback hook. From there, I got the understanding of use of the onLoad function to load all the markers and use the fitBounds function on markers to get the centre of all markers, and the zoom level for markers Note: The fitBounds function is from the Google Maps library. Here's an example: ` const HomePageMap = () => { const { isLoaded } = useLoadScript({ googleMapsApiKey: "your-api-key-here" }); // store api key in env file for better security Loading... } else { return ( <> <div className='box-shadow' style={{margin:"20px",padding:"1px"}}> <GoogleMap options={{streetViewControl:false,zoomControl:true}} mapContainerClassName="main-map-image" onLoad={(map) => { const bounds = new window.google.maps.LatLngBounds(); approvedDocs.forEach((location) => { bounds.extend({lat:parseFloat(location.lat),lng:parseFloat(location.lng)}); }) map.fitBounds(bounds); }} > {approvedDocs.map((location) => { return <MarkerF key={location.docid} position={{lat: parseFloat(location.lat),lng: parseFloat(location.lng)}}/> })} </> ) } } export default HomePageMap ` |
Beta Was this translation helpful? Give feedback.
Finally, I can use auto zoom and center with this library.
It's called
bound
animation.After reading the
Migration from [email protected]
section from the documentation from the npm registry page here https://www.npmjs.com/package/@react-google-maps/api, I tried to combine the new way of calling theGoogle Map
component for showing the map and initialize thebound
then update thebound
using theuseEffect
hook.It worked.