【问题标题】:How to add map markers stored in a JSON feed to an existing React Google Map?如何将存储在 JSON 提要中的地图标记添加到现有的 React Google 地图?
【发布时间】:2018-09-28 03:42:52
【问题描述】:

我有一个创建地图的 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});
  });
 }

我在网上仔细查看了解决方案,但无法弄清楚如何在地图创建/加载后添加动态标记。

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

【问题讨论】:

    标签: json reactjs google-maps react-google-maps


    【解决方案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 的 docs 了解 React 的组件生命周期。

    总账和高频

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 2017-05-15
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 2018-10-21
      • 2011-04-14
      • 2013-12-12
      • 2015-04-20
      相关资源
      最近更新 更多