如何将存储在 JSON 提要中的地图标记添加到现有的 React Google 地图?

IT技术 json reactjs google-maps react-google-maps
2021-05-22 11:58:15

我有一个创建地图的 react-google-maps 项目:

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

export default class NavMap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      markers: []
    }
  }

  static defaultProps = {
    center: {lat: -41.25,lng: 173.2},
    zoom: 11
  }
  render() {
    return (<div id="nav-map" className='google-map'>
    <GoogleMapReact 
      name={map} 
      apiKey={'MYAPIKEY'} 
      defaultCenter={this.props.center} 
      defaultZoom={this.props.zoom}>
      <MarkerComponent lat={-41.25} lng={173.2} text={'Centre'}/>
    </GoogleMapReact>
    </div>)
  }
}

这将在地图的中心添加一个文本标记。

但是,我无法从在 React 中创建/加载地图后加载的动态 JSON 提要中添加标记。请注意 JSON 提要可能会更新 - 届时标记将被刷新。

在 React 中,我通常像这样调用 JSON 提要:

componentDidMount() {
  fetch('/myJSONfeed').then(response => response.json()).then(data => {
    this.setState({data});
  });
 }

我在网上很好地浏览了一个解决方案,但无法弄清楚如何在创建/加载地图后添加动态标记。

任何想法或示例代码将不胜感激。

1个回答

我最近遇到了同样的问题。希望这个解释能帮助你找出问题所在。

概述

当我们与外部资源合作时。重要的是要注意,没有什么能保证您要执行的任务的顺序。与您的情况一样,获取 JSON 提要是异步获取的。

问题

在 componentDidMount() 中获取提要应该没问题。但是,您仍然需要等待数据可用。因此,您应该告诉其他组件侦听该事件,然后更新它们的属性。

解决方案

通过使用 componentDidMount(),我们可以等待地图加载,并将属性传播到组件中。然后,通过 componentDidUpdate() 我们可以对 DOM 进行操作。

它是这样的:

在 App.js 中:

    componentDidMount(){
        fetch(THE_SOURCE_TO_BE_FETCHED)
        .then(function(response) {
            return response.json();
        }).then(data => {
            this.setState({markers: data});
        });
    }

在地图组件中

    componentDidUpdate(){
        const google = window.google;

        this.map = new google.maps.Map(this.refs.map, {
            center: this.props.center,
            zoom: 4
        });

        this.createMarkers(this.props.markers)
    }

    createMarkers(users){
        const google = window.google;

        users.map(user => {
            this.marker = new google.maps.Marker({
                position: {
                    lat: user.location.latitude,
                    lng: user.location.longitude
                },
                map: this.map,
            });
            this.state.markers.push(this.marker);
        })
    }

请注意:您应该仔细检查您的 JSON 并检查它是否有效,以及它是否可以从字符串等中解析。

如果您需要更多详细信息,请浏览 React 的React 组件生命周期文档

GL & 高频