小编典典

用React实现谷歌地图

reactjs

在这里反应新手,请忍受我:)希望这将很容易解决

目前,我只是想让地图显示在屏幕上,但是当我运行代码时,页面完全空白,甚至其他div也没有出现。这是我的代码,摘录如下:https
:
//gist.github.com/JoeyBodnar/f76c5d434d57c6cc6108513ad79d4cb7

需要注意的几件事:1)从项目目录中,我已经运行了npm install –save react-google-maps
2)使地图出现的代码是从这里获取的:https :
//github.com/tomchentw/react -谷歌地图

那我到底在做什么错呢?我的“ const GettingStartedGoogleMap”声明在错误的地方?还是我在div中做错了什么?

还请注意,如果我从该文件中删除了所有与Google Maps相关的代码,则一切正常。

任何帮助表示赞赏,谢谢

编辑,这是我的代码,即使硬编码高度也仍然显示空白屏幕:

 return (
     <GettingStartedGoogleMap
 containerElement={
    <div style={{ height: `400px` }} />
 }
 mapElement={
 <div style={{ height: `400px` }} />
 }
 onMapLoad={_.noop}
 onMapClick={_.noop}
 markers={markers}
 onMarkerRightClick={_.noop}
/>
  );

阅读 1221

收藏
2020-07-22

共1个答案

小编典典

这是我先前回答的改进版本

我刚刚测试了您的代码,其中包含许多错误,未定义和未使用的变量!因此,您可以改用以下代码,这很简单(这将使您解决当前问题并显示地图!)

首先,安装必要的库:

npm install --save google-map-react
npm install --save prop-types

然后,您可以复制下面的全部内容:

import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';

const AnyReactComponent = ({ text }) => <div>{text}</div>;

class MyClass extends Component {
  constructor(props){
    super(props);

  }

  render() {
    return (
      <GoogleMapReact
        defaultCenter={this.props.center}
        defaultZoom={this.props.zoom}
        style={{height: '300px'}}
      >
        <AnyReactComponent
          lat={59.955413}
          lng={30.337844}
          text={'Google Map'}
        />
      </GoogleMapReact>
    );
  }
}
MyClass.defaultProps = {
  center: {lat: 59.95, lng: 30.33},
  zoom: 11
};

export default MyClass;
2020-07-22