【问题标题】:TypeError: Cannot read property 'maps' of undefined error in reactjs google mapTypeError:无法读取 reactjs 谷歌地图中未定义错误的属性“地图”
【发布时间】:2018-04-05 05:38:42
【问题描述】:

当我尝试包含 geoocoder api 代码时,它显示错误“TypeError: Cannot read property 'maps' of undefined”。

这是我的代码

import React from 'react';
import { compose, withProps,withHandlers } from "recompose"
import { withScriptjs, withGoogleMap, GoogleMap, Marker,InfoWindow,GeoCoder } from "react-google-maps"
import { MarkerClusterer } from 'react-google-maps/lib/components/addons/MarkerClusterer';
import { connect } from 'react-redux';

let geocoder = new google.maps.Geocoder();



const MyMapComponent = compose(
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?AIzaSyAoaDS6fIKlYvEHeTaakCxXqp-UwnggoEgv=3&sensor=true&callback=init",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
   withHandlers({
    onMarkerClustererClick: () => (markerClusterer) => {
      const clickedMarkers = markerClusterer.getMarkers()
      console.log(`Current clicked markers length: ${clickedMarkers.length}`)
      console.log(clickedMarkers)
    },
  }),
  withScriptjs,
  withGoogleMap
)((props) =>{

 return ( <GoogleMap
    zoom={props.maps.zoom}
    center={{ lat:props.maps.lat, lng:props.maps.lng }}
    heading={5}
  >
   <MarkerClusterer
      onClick={props.onMarkerClustererClick}
      averageCenter
      enableRetinaIcons
      gridSize={60}
    >
      {props.markers.map(marker => (
        <Marker
          key={marker.photo_id}
          position={{ lat: marker.latitude, lng: marker.longitude }}
        />
      ))}
    </MarkerClusterer>
     <Marker
          position={{lat:props.maps.lat, lng:props.maps.lng }}
     >
    <InfoWindow>
        <p>gdgd</p>
      </InfoWindow>
     </Marker>
  </GoogleMap>
)});

export default class DemoApp extends React.Component {
  componentWillMount() {
    this.setState({ markers: [] })
  }

  componentDidMount() {
        console.log("+mymap++++++++");
        console.log(this.props.myMap);
        this.setState({markers:[{photo_id:1,longitude:76.911270,latitude:11.032595},
                                {photo_id:2,longitude:75.806682,latitude:11.259169},
                                {photo_id:3,longitude:77.213780,latitude:28.617671},
                                {photo_id:4,longitude:78.138991,latitude:9.903245}]})
    }

  render() {
    return (
      <MyMapComponent markers={this.state.markers} maps={this.props.myMap} />
    )
  }
}

在上面的代码中,当我尝试创建地理编码器变量时,它会显示错误。这里我尝试使用地理编码器 api 从地图的纬度和经度位置获取位置名称。

【问题讨论】:

  • 在 DemoApp 中。您可能没有将 myMap 道具传递给 DemoApp 组件。
  • 当我删除它时仍然显示相同的错误
  • 这不会有帮助,maps 属性如果你删除它仍然是未定义的。您需要将它传递给MyMapComponent,因为它需要一个带有latlngzoom 键的对象。

标签: reactjs


【解决方案1】:

您可能已将google 包含在您的index.html 中,因此您的组件中无法访问google 变量,因为它是window variable

尝试使用window.google.maps.xxx,那么它必须解决你的TypeError

针对您的特殊情况

import React from 'react';
...

let geocoder = new window.google.maps.Geocoder();  // edited


const MyMapComponent = compose(
...

【讨论】:

  • react-google-maps 甚至不导出 GeoCoder... 你在哪里找到的? :c
  • @Jatimir 该死!!!都是他的代码,看起来他都乱码了
  • 哦,你是对的,对不起,没注意到他也有这个导入。
【解决方案2】:

您的代码的主要问题是这个片段:

<MyMapComponent markers={this.state.markers} maps={this.props.myMap} />

我假设DemoApp 是您安装在index.js 文件中的主要应用程序组件。您还没有将任何道具传递给DemoApp component,因此在MyMapComponent 中,maps 道具未定义。在该组件内部使用props.maps.lat 会导致出现TypeError: Cannot read property 'maps' of undefined 错误。

我注意到其他一些小问题:

  • 此代码是不必要的:

    import { ..., GeoCoder } from 'react-google-maps';
    

    react-google-maps 甚至不导出具有该名称的组件。也许它曾经是,但它不再是。您可以在文档中查看

  • 这也不是必需的:

    let geocoder = new google.maps.Geocoder();
    
  • 我将 googleMapURL 更改为文档中的那个:

    googleMapURL: 'https://maps.googleapis.com/maps/api/js?key=your_key_goes_here&v=3.exp&libraries=geometry,drawing,places'
    

    您现在可以跳过生成密钥,但控制台中会出现警告。

下面的工作代码:

import React, { Component } from 'react';
import { compose, withProps, withHandlers } from 'recompose';
import { withScriptjs, withGoogleMap, GoogleMap, Marker, InfoWindow } from 'react-google-maps';
import { MarkerClusterer } from 'react-google-maps/lib/components/addons/MarkerClusterer';

const MyMapComponent = compose(
  withProps({
    googleMapURL:
      'https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places',
    loadingElement: <div style={{ height: '100%' }} />,
    containerElement: <div style={{ height: '400px' }} />,
    mapElement: <div style={{ height: '100%' }} />
  }),
  withHandlers({
    onMarkerClustererClick: () => (markerClusterer) => {
      const clickedMarkers = markerClusterer.getMarkers();
      console.log(`Current clicked markers length: ${clickedMarkers.length}`);
      console.log(clickedMarkers);
    }
  }),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    zoom={props.maps.zoom}
    center={{ lat: props.maps.lat, lng: props.maps.lng }}
    heading={5}
  >
    <MarkerClusterer
      onClick={props.onMarkerClustererClick}
      averageCenter
      enableRetinaIcons
      gridSize={60}
    >
      {props.markers.map(marker => (
        <Marker key={marker.photo_id} position={{ lat: marker.latitude, lng: marker.longitude }} />
      ))}
    </MarkerClusterer>
    <Marker position={{ lat: props.maps.lat, lng: props.maps.lng }}>
      <InfoWindow>
        <p>test text</p>
      </InfoWindow>
    </Marker>
  </GoogleMap>
));

export default class DemoApp extends Component {
  render() {
    const markers = [
      { photo_id: 1, longitude: 76.91127, latitude: 11.032595 },
      { photo_id: 2, longitude: 75.806682, latitude: 11.259169 },
      { photo_id: 3, longitude: 77.21378, latitude: 28.617671 }
    ];

    const myMap = {
      lng: 78.138991,
      lat: 9.903245,
      zoom: 6
    };

    return <MyMapComponent markers={markers} maps={myMap} />;
  }
}

【讨论】:

  • 我仍然需要地理编码器。当我写let geocoder = new google.maps.Geocoder()时,它显示上述错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
  • 2020-04-20
  • 2020-11-18
  • 2021-07-11
  • 1970-01-01
  • 2017-04-03
  • 2021-11-17
相关资源
最近更新 更多