【问题标题】:Google Maps "Uncaught TypeError: Cannot read property 'defaultView' of undefined"谷歌地图“未捕获的类型错误:无法读取未定义的属性‘defaultView’”
【发布时间】:2018-07-31 22:10:35
【问题描述】:

尝试在 React 中加载谷歌地图时,我不断收到此错误:

"Uncaught TypeError: Cannot read property 'defaultView' of undefined"

我有一个加载谷歌地图的组件,但它失败了,我不知道哪里出了问题。我相信错误仅限于此组件,因为应用程序成功呈现,但由于上述错误,地图没有显示在其中。

class DoctorsMap extends React.Component {
  constructor(props) {
    super(props);
    this.geocoder = new google.maps.Geocoder();
    this.mapRef = React.createRef();
    this.handleMarkerClick = this.handleMarkerClick.bind(this);
    this.setTheCenter = this.setTheCenter.bind(this);
  }

  componentDidMount () {
    this.map = new google.maps.Map(this.mapRef.current.outerHTML);
    this.setTheCenter();
    this.markerManager = new MarkerManager(this.map, this.handleMarkerClick);
    this.markerManager.updateMarkers(this.props.doctors);
  }

  componentDidUpdate () {
    return this.markerManager.updateMarkers(this.props.doctors);
  }

  setTheCenter() {
    this.geocoder.geocode({address: `${this.props.address}`}, (results, status) => {
      if (status === google.maps.GeocoderStatus.OK) {
        const coordinates = results[0].geometry.location;
        this.map.setCenter(coordinates);
        this.map.setZoom(11);
      } else {
        alert("Geocode failed: " + status);
      }
    });
  }

  handleMarkerClick(doctor) {
    return this.props.history.push(`/doctor/${doctor.id}`);
  }

  docSearchToggle() {
    if (this.props.location.pathname.includes("/doctor/")) {
      return ["map-doc-canvas", "map-doc-container"];
    } else {
      return ["map-search-canvas", "map-search-container"];
    }
  }

  render () {
    return(
      <div id={this.docSearchToggle()[1]}>
        <div id={this.docSearchToggle()[0]} ref={this.mapRef}></div>
      </div>
    );
  }
}

有什么想法吗?

【问题讨论】:

  • 没关系,找出问题所在。问题是这一行:componentDidMount () { this.map = new google.maps.Map(this.mapRef.current.outerHTML); 我需要通过它this.mapRef.current。我没有传递 html 元素,而是传递了它的字符串表示形式。

标签: javascript reactjs google-maps


【解决方案1】:

如果下面的代码对您的问题有帮助

如果您使用的是 Sapui5,请使用此代码

sap.ui.getCore().byId("Your Id").getDomRef();

this.getView().byId("Your ID").getDomRef();

如果您使用的是 HTML

document.getElementById("Your Id").getDomRef();

【讨论】:

  • 感谢您的帮助。我很久以前就发现了这个问题;我只是将错误的参数传递给函数。
【解决方案2】:

只需new google.maps.Map(this.mapRef.current)。 需要 HTMLElement 但您支持字符串(HTMLElement.outerHTML)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多