react-typescriptgoogle-polylinereact-google-mapsstrava

React Google Maps get bounds of Polyline


I have been playing around with the Strava developer API a bit and been building a basic React app to fetch soem Starva activites and display it in a list. Repo can be found here.

I have a map that renders the activity route in this component.

const StravaMap = withScriptjs(
  withGoogleMap(({ zoom, activity }: StravaMapProps) => {
    const center = {
      lat: activity.start_latitude,
      lng: activity.start_longitude,
    };

    const path = activity.map.summary_polyline
      ? createPath(polyline.decode(activity.map.summary_polyline))
      : [];

    return (
      <GoogleMap
        defaultZoom={zoom}
        defaultCenter={center}
        defaultOptions={mapOptions}
      >
        <Marker position={center} />
        {path.length > 0 && (
          <Polyline options={polyLineOptions} path={path} visible />
        )}
      </GoogleMap>
    );
  }),
);

Source file here.

The polygon renders fine, but I am now trying to figure out how I can zoom the map to fit th epolyline into bounds.

I may be mising soemthing but I dont have a clear idea how to get hold of the polyline instance to get bounds or the map to set bounds.

I know how to buffer the poluyline based on the path but once I have done thay and have the bounds, how can I set the bound using this React Google Maps library?

Thanks,


Solution

  • With a little more digging and research I have found a workable solution I'll share for the benefit of others:

    I found this post on GitHub

    Using that I created a helper function to create the google.maps.LatLngBounds

    export const createBounds = (path: IPoint[]): google.maps.LatLngBounds => {
      const bounds = new window.google.maps.LatLngBounds();
      path.map((p: IPoint) => bounds.extend(p));
      return bounds;
    };
    

    In my StravaMap component I then pass the path we had to this function and get the bounds like this:

    const bounds = createBounds(path);
    

    I can then pass that to the GoogleMap component using the ref like:

      ref={(map) => map && map.fitBounds(bounds)}
    

    And that successfully sets the map bound when the activity is loaded.