javascriptreactjsgoogle-mapsgoogle-map-react

google-map-react centering the map with multiple markers


How do I find the center of the map when I have more than 2 markers? When I have only 2 I've done it like this:

midPoint(trackingLocation, deliveryLocation) {
    if (deliveryLocation) {
      return [
        trackingLocation.lat + (deliveryLocation.lat - trackingLocation.lat) * 0.5,
        trackingLocation.lng + (deliveryLocation.lng - trackingLocation.lng) * 0.5
      ];
    } else {
      return trackingLocation;
    }
  }

But how do I calculate the center when I have 5 markers?

Thank you


Solution

  • Find the rectangle that contains all the markers, then use the midpoint of that rectangle.

    First, go through all the markers and find:

    Then you can do the same calculation you did for two markers with these two points: