google-maps - 使用 React-google-maps v6+ 访问 map 引用

标签 google-maps reactjs

react-google-maps 的最新更改似乎删除了 mapHolderRef 属性来访问 map 实例。查看新组件的更改,看起来它们调用了内部常量上下文引用,但似乎不应该使用/容易公开这些引用。

在最新版本之前,我可以执行如下操作来向 map 添加自定义控件:

paintControl(props) {
  const { rendered } = this.state;
  const position = props.position || google.maps.ControlPosition.TOP_CENTER;
  const map = props.mapHolderRef.getMap(); // This no longer works
  const controlElement = React.createElement(props.customControl, { map, ...props });

  ReactDOM.render(controlElement, this.customControlDiv);
  this.customControlDiv.style.zIndex = this.props.zIndex || 1;

  if (!rendered) {
    this.setState({ rendered: true }, () => {
      map.controls[position].push(this.customControlDiv);
    });
  }
}

6.0 版本中有注释提到此 mapHolderRef 属性不再通过 props 访问,而是通过上下文访问。我已经尝试让它发挥作用,但似乎无法弄清楚。

我目前正在使用 onMapLoad 回调来获取 react map 实例,但似乎缺少实际的谷歌地图引用。我已经能够通过以下操作获得可用的引用:

const map = props.mapHolderRef.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

但这看起来确实很糟糕而且不正确。它还创建了多个控件而不是维护一个控件,因此出现了一些问题。不确定新文档中是否有我遗漏的内容,或者新版本中是否根本不提供此功能。

有人幸运地获得了自定义控件或组件来与新的 react-google-maps 版本一起使用吗?

感谢您的帮助!

最佳答案

为了添加 Max 的答案,这就是我最终使用 v7.2.0 让它在我的代码中工作的方法:

import { MAP } from 'react-google-maps/lib/constants';

export default class CustomControl extends Component {
  static contextTypes = { [MAP]: PropTypes.object };

  ...

  // this.context[MAP] returns the google map instance object
  if (this.context[MAP]) {
    const map = this.context[MAP];
    map.controls[position].push(this.customControlDiv);
  }

关于google-maps - 使用 React-google-maps v6+ 访问 map 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44296040/

相关文章:

google-maps - react 谷歌地图标记动画

iphone - 将街道名称和城市反向地理编码为文本

java - 向 map 添加标记

java - 如何从谷歌地图网址获取经纬度

javascript - 为什么我加载这个网站时全屏闪白?

javascript - 使用 Observable.from(<Promise>) 并在 Observable 中捕获错误时如何处理 `UnhandledPromiseRejectionWarning`

reactjs - 使用浅渲染测试 react-router

javascript - react : unable to map over state due to it being undefined/error

javascript - React-Router - 显示特定 ID 的详细信息

node.js - @typescript-eslint/eslint-plugin@2.3.2 : The engine "node" is incompatible with this module