0

我已经实现了:

 populateLocations() {
    var arrOfAdds = [],
        geocoder = new google.maps.Geocoder()

    this.props.properties.map(function(property, i) {
      if (geocoder) {
        geocoder.geocode({
          'address': property.street
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
             // debugger
             arrOfAdds.push({
               position: {
                 lat: results[0].geometry.location.lat(),
                 lng: results[0].geometry.location.lng(),
               },
               key: i,
               defaultAnimation: 2,
             })
            }
        });
      }
    }, this)

   arrOfAdds.map(function(add, i) {
     this.state.markers.push(add)
   })

    console.log('arrOfAdds', arrOfAdds)
    console.log('this.state.markers', this.state.markers)
  }

我正在尝试使用 arrOfAdds 数组中的任何内容来更新 this.state.markers (一个包含我所有的纬度/经度的数组,其中引脚将被丢弃),但我想我无法更新 this.state.markers ? 似乎当我在函数中运行调试器时,它跳过this.props.properties.map(...并直接进入arrOfAdds.map...,它从一开始就是一个空数组,不附加任何东西,然后通过this.props.properties.map(...创建正确填充的 arrOfAdds。

对如何做到这一点感到相当困惑,希望得到帮助。

4

1 回答 1

2

geocoder.geocode 很可能是一个异步函数,因此这意味着您的添加代码在您收到实际数据之前运行。如果您在地理编码回调中移动该代码,它可能是固定的(您可以简单地完全this.state.markers.push跳过arrOfAdds集合。(请注意,闭包尚未绑定到这个顺便说一句!所以最好使用箭头函数或绑定)

注意如果您的示例来自反应组件,请注意直接修改被认为是一种不好的做法this.state,但setState应该使用。但是如果你的标记是一个可观察的数组,那并不重要。

于 2016-10-07T08:04:50.263 回答