【问题标题】:Getting map properties using react-google-maps in functional component?在功能组件中使用 react-google-maps 获取地图属性?
【发布时间】:2021-02-08 19:05:56
【问题描述】:

我正在尝试访问地图的当前缩放或中心,但我遇到了一些错误。我是 React 新手,我不确定自己在做什么,但我尝试将 ref 附加到 GoogleMap 组件

const refMap = useRef(null);

const handleZoomChanged = () => {
    const newZoom = refMap.current.getZoom();
    console.log(newZoom);
  }

...

<GoogleMap
          ref={refMap}
          {...mapProps}
          center={mapCenter}
          zoom={mapCenter.zoom}
          onZoomChanged={handleZoomChanged}
...
</GoogleMap>

我收到一条错误消息:无法读取 null 的属性“getZoom”,并警告无法为函数组件提供参考。我该如何解决这个问题?谢谢!

【问题讨论】:

  • 你使用的是什么谷歌地图的反应库?您能否在问题中提供sscce

标签: reactjs google-maps react-functional-component use-ref


【解决方案1】:

我参考了react-google-maps docs 中关于如何实现 ref 的示例。请参阅此 link 的工作示例和下面的代码 sn-p:

import React from "react";
const { compose, withProps, withState, withHandlers } = require("recompose");
const {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow
} = require("react-google-maps");

const MapWithControlledZoom = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />
  }),
  withState("zoom", "onZoomChange", 8),
  withHandlers(() => {
    const refs = {
      map: undefined
    };

    return {
      onMapMounted: () => ref => {
        refs.map = ref;
      },
      onZoomChanged: () => () => {
        console.log(refs.map.getZoom());
        console.log(refs.map.getCenter());
      }
    };
  }),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    defaultCenter={{ lat: -34.397, lng: 150.644 }}
    zoom={props.zoom}
    ref={props.onMapMounted}
    onZoomChanged={props.onZoomChanged}
  />
));

export default MapWithControlledZoom;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-03
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多