【问题标题】:React + Google Maps JS API, dynamically render markers from stateReact + Google Maps JS API,从状态动态渲染标记
【发布时间】:2017-01-31 17:33:06
【问题描述】:

在 React 中,我试图用标记填充我的谷歌地图,其中每个标记由我所在州的一组对象确定。现在,如果我有一个包含 22 个对象的 reduceSites 数组,那么其中只有 1-3 个将呈现为标记。无论有多少对象处于状态,这似乎都是这种情况。

更新

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

【问题讨论】:

  • 您返回 new google.maps.Marker 的地方,MarkerOptions 属性应该是 map 而不是 setMap 即。 map: map。这将已经在地图上绘制标记。那么marker.setMap(map) 应该在你的代码中做什么呢?
  • 我这样做了,尽管状态包含超过 20 个标记,但仍然不会显示超过 1-3 个标记。

标签: javascript google-maps reactjs google-maps-api-3


【解决方案1】:

parseInt 更改为parseFloat

【讨论】:

    【解决方案2】:

    <Marker></Marker> 组件作为 Map 的子组件,并使用您的数组来设置位置属性。

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

    确保在更改位置数组的值时调用 setState(),以便 React 在每次更改值时自动呈现 DOM。这就是让它动态呈现的方式。

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

    【讨论】:

    • 我不确定如何整合它,因为我没有使用这个反应组件,只是原始的谷歌 api。
    • 它可能会让你的生活更轻松,只需 npm install --save google-maps-react 然后在文件顶部从“google-maps-react”导入地图。但是你现有的代码到底有什么问题?
    • 它没有渲染任何标记。如果我调用setMap: map,我会在使用forEach 读取InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama 的标记进行迭代时出错。但是,如果我删除了 forEach 迭代,则没有错误,但仍然没有渲染标记。
    • 我更愿意学习如何在没有预配置组件的情况下集成谷歌地图。
    • 哦!这是因为您执行 setMap(map) 并且 map 指的是元素。我认为您的意思是 setMap(this.map)。以及您返回 google.maps.Marker({ setMap:this.map}) 的位置
    猜你喜欢
    • 2016-10-21
    • 2022-08-22
    • 1970-01-01
    • 2012-01-29
    • 2018-07-16
    • 2021-02-20
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    相关资源
    最近更新 更多