如何根据状态变化重新渲染Google地图?

时间:2018-07-08 03:11:11

标签: javascript reactjs google-maps

我正在按照此指南将JavaScript Maps API与React.js集成:

http://cuneyt.aliustaoglu.biz/en/using-google-maps-in-react-without-custom-libraries/

我可以使地图加载良好,并且一切正常。我遇到的问题是状态更改时无法重新渲染地图。

基本上,我正在使用以下代码: https://stackblitz.com/edit/react-67pggp?file=index.js

除了,我试图通过状态更改来动态更改标记的位置。因此,在传递给Map组件的onMapLoad()函数中,我替换了

position: { lat: 41.0082, lng: 28.9784 }

相似

position: { lat: this.state.lat, lng: this.state.lng }

,并且我希望每当状态中存储的位置更改时,标记的位置就更改。我知道问题源于仅在组件首次安装时才调用onMapLoad()的事实,但是我不确定如何使地图重新渲染并显示更新的标记位置。任何帮助表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用getInitialState方法初始化默认状态,并在render中使用此变量。

import React, { Component } from 'react';
import { render } from 'react-dom';
import Map from './map'

class App extends Component {
  constructor() {
    super();
  }
   getInitialState() {
    return {
       lat = '41.0082',
       lng = '28.9784'
     };
  }

  render() {
    return (
      <Map
        id="myMap"
        options={{
          center: { lat : this.state.lat ,lng : this.state.lng },
          zoom: 8
        }}
        onMapLoad={map => {
          var marker = new window.google.maps.Marker({
            position: { lat :this.state.lat, lng: this.state.lng },
            map: map,
            title: 'Hello Istanbul!'
          });
        }}
      />
    );
  }
}

render(<App />, document.getElementById('root'));