Search code examples
javascriptnode.jsreactjsgoogle-maps-api-3react-google-maps

How to fit multipe circle when using react-google-map?


Below is the way I use to fit multiple markers when I do react-google-map projects. The map.props is marker objects:

    zoomToMarkers: map => {
      if (!map) { return }
      const bounds = new window.google.maps.LatLngBounds()
      if (map.props.children[0].length !== 0) {
        map.props.children[0].forEach((child) => {
          bounds.extend(new window.google.maps.LatLng(child.props.position.lat, child.props.position.lng))
        })
        map.fitBounds(bounds)
      }
    }

Now I want to fit multiple circle and I tried the below code modification. The map.props now is circle objects:

    zoomToMarkers: map => {
      if (!map) { return }
      const bounds = new window.google.maps.LatLngBounds()
      if (map.props.children.length !== 0) {
        map.props.children.forEach((child) => {
          bounds.extend(new window.google.maps.LatLng(child.props.center.lat, child.props.center.lng))
        })
        map.fitBounds(bounds)
      }
    }

I changed position to center.

But it didn't work. It only fit then center coordinate like it fit the markers.

What should I do to fit the circle?


Solution

  • Below is my answer:

        zoomToMarkers: map => {
          if (!map) { return }
          const bounds = new window.google.maps.LatLngBounds()
          if (map.props.children.length !== 0) {
            map.props.children.forEach((child) => {
              var centerCircle = new window.google.maps.Circle(child.props)
              bounds.union(centerCircle.getBounds())
            })
            map.fitBounds(bounds)
          }
        }