简体   繁体   English

React + Google Maps JS API,根据状态动态渲染标记

[英]React + Google Maps JS API, dynamically render markers from state

In React, I'm trying to populate my google map with markers where each marker is determined by an array of objects in my state. 在React中,我试图用标记填充Google地图,其中每个标记都由处于我状态的对象数组确定。 Right now, if I have a reducedSites array of say 22 objects, only 1-3 of them will render as markers. 现在,如果我有一个由22个对象组成的reduceSites数组,则只有1-3个对象将作为标记呈现。 This seems to be the case no matter how many objects are in state. 无论有多少个对象处于状态,似乎都是这种情况。

Updated 更新

renderMap() {
    const map = document.querySelector('#map')
    this.map = new google.maps.Map(map, {
      center: { lat: this.state.lat, lng: this.state.lng },
      zoom: 8
    });
    const _this = this
    let markers = this.state.reducedSites.map(function(site) {
      return new google.maps.Marker({
        position: {lat: parseInt(site.latitude), lng: parseInt(site.longitude)},
        map: _this.map
      });
    });
  }

parseInt更改为parseFloat

Put <Marker></Marker> component as a child of Map and use your array to set the position property. <Marker></Marker>组件作为Map的子项,并使用您的数组设置position属性。

  <Map google={this.props.google}
        style={{width: '100%', height: '100%', position: 'relative'}}
        className={'map'}
        zoom={14}>
      <Marker
        name={'SOMA'}
        position={{lat: this.state.markersArray[0].lat, lng: this.state.markersArray[0].lng}} />
     </Marker> 
    </Map>

Make sure to call setState() when changing the values of your positions array so that React automatically renders the DOM each time a value is changed. 确保在更改positions数组的值时调用setState(),以便每次更改值时React自动呈现DOM。 This is how you get it to render dynamically. 这就是您如何使其动态渲染。

https://github.com/fullstackreact/google-maps-react https://github.com/fullstackreact/google-maps-react

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM