reactjscoordinatesgoogle-maps-markersreact-google-maps

How to auto center coordinates and zoom for multiple markers in react-google-maps/api


I want to show multiple dynamic markers on the map. What I mean by dynamic markers is that the markers are determined by the user's past activity. I want to determine the appropriate zoom level and center coordinates so that the user does not have to scroll through the map.  I have checked this documentation https://react-google-maps-api-docs.netlify.app/ but can't find any example related to the specification I need.

I found an algorithm to count the center coordinate of multiple markers here 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 @googlemaps/js-api-loader.

How could I do search for the center coordinate and zoom for multiple markers with this @react-google-maps/api library?


Solution

  • 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:

    import React from 'react';
    import {GoogleMap, useLoadScript, MarkerF } from "@react-google-maps/api";
    import { useSelector } from 'react-redux';
    
    
    const HomePageMap = () => {
    
      const { isLoaded } = useLoadScript({ googleMapsApiKey: "your-api-key-here" }); // store api key in env file for better security
      let approvedDocs = useSelector(state => state.approvedSightingLocation.approvedSightings) 
      // here redux is used to store data, you can use api also to fetch data
      if(!isLoaded) {
        return <div>Loading...</div>
      } 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)}}/>
                    })}
                </GoogleMap>
            </div>
          </>
        )
      }
    }
    
    
    
    export default HomePageMap