【问题标题】:React Google Maps get bounds of PolylineReact Google Maps 获得折线的边界
【发布时间】:2021-12-31 18:46:35
【问题描述】:

我一直在使用 Strava 开发人员 API 并构建了一个基本的 React 应用程序来获取一些 Starva 活动并将其显示在列表中。可以在here找到repo。

我有一张地图,可以在这个组件中呈现活动路线。

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>
    );
  }),
);

源文件here.

多边形渲染得很好,但我现在正试图弄清楚如何缩放地图以使 epolyline 适合边界。

我可能会遗漏一些东西,但我不清楚如何获取折线实例以获取边界或地图以设置边界。

我知道如何根据路径缓冲多段线,但是一旦我完成了这些并有了界限,我该如何使用这个 React Google Maps 库来设置界限?

谢谢,

【问题讨论】:

    标签: react-typescript google-polyline react-google-maps strava


    【解决方案1】:

    通过更多的挖掘和研究,我找到了一个可行的解决方案,我将与他人分享:

    我在GitHub找到了这篇文章

    使用我创建了一个辅助函数来创建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;
    };
    

    然后在我的 StravaMap 组件中,我将我们必须的路径传递给该函数并获得如下边界:

    const bounds = createBounds(path);
    

    然后我可以使用 ref 将其传递给 GoogleMap 组件,例如:

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

    这会在加载 Activity 时成功设置地图绑定。

    【讨论】:

      猜你喜欢
      • 2011-03-18
      • 2017-09-28
      • 2018-05-03
      • 2012-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多