如何将存储在JSON feed中的地图标记添加到现有的React Google Map? [英] How to add map markers stored in a JSON feed to an existing React Google Map?

查看:99
本文介绍了如何将存储在JSON feed中的地图标记添加到现有的React Google Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个react-google-maps项​​目,它创建一个地图:

I have a react-google-maps project which creates a map:

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>)
  }
}

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

This will add a text marker to the centre of the map.

但是,我无法工作,如何从动态JSON提要中添加标记,该提要是在React中创建/加载地图后加载的.请注意,JSON提要可能会更新-此时将刷新标记.

However I can't work how to add the markers from a dynamic JSON feed that is loaded after the map is created/ loaded in React. Please note the JSON feed could be updated - at which point the markers would be refreshed.

在React中,我通常会这样调用JSON feed:

In React I normally call a JSON feed like this:

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

我已经在网上找到了很好的解决方案,但是在创建/加载地图后无法确定如何添加动态标记.

I've had a good look around online for a solution but have not being able to work out how to add dynamic markers after the map has been created/ loaded.

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

Any ideas or example code would be appreciated.

推荐答案

我最近遇到了相同的问题.希望这种解释可以帮助您找出问题所在.

I have encountered the same issue recently. Hope this explanation will help you to figure out what went wrong.

当我们使用外部资源时.重要的是要注意,没有什么可以保证您要执行的任务的顺序.就像您的情况一样,获取JSON提要是异步获取的.

When we are working with external sources. It's important to note that nothing guarantees you the order of tasks to be executed. As in your case, fetching a JSON feed is fetched asynchronously.

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

Fetching the feed inside componentDidMount() should be fine. However, you still need to wait for the data to available. Hence, you should tell others components to listen for that event, and update their properties thereafter.

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

By using the componentDidMount() we can wait for the map to load, and properties to propagate into the components. Then, with componentDidUpdate() we can operate on the 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并检查其是否有效,以及是否可以从字符串等中解析它.

Please note: you should carefully examine your JSON and check that it is valid, as well as if it subject to be parsed from string etc.

如果需要更多详细信息,请浏览React的 docs

Take a tour at React's docs of React's component lifecycle if you need more details.

GL& HF

GL & HF

这篇关于如何将存储在JSON feed中的地图标记添加到现有的React Google Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆