2016-10-07 49 views
0

我已經在這個實施:如何追加緯度/經度的反應,谷歌,地圖,this.state.markers

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

我想基本上更新this.state.markers(數組其中有我所有的緯度/長度的引腳將被丟棄)與arrOfAdds數組中的任何東西,但我想我不能更新this.state.markers? 似乎當我在函數中運行調試器時,它跳過了this.props.properties.map(...並直接跳到arrOfAdds.map...,它從一開始就是一個空陣列,不會追加任何內容,然後通過this.props.properties.map(...創建正確填充arrOfAdds。

對於如何做到這一點,相當困惑,會愛上援助。

回答

2

geocoder.geocode很可能是一個異步函數,所以它意味着您的附加代碼在之前運行您收到實際數據。如果您將代碼移動到地理編碼回調中,則它可能是固定的(您可以簡單地執行this.state.markers.push並完全跳過arrOfAdds集合(請注意封閉尚未綁定到此btw!因此最好使用箭頭函數或綁定)

NB 如果你的例子是從反應組件,請注意,它被認爲是不好的做法,直接修改this.state,但setState應該被使用。但是,如果你的標記是可觀察到的陣列,它其實並不重要。

+0

嗨@mweststrate!謝謝你的回答。我最初嘗試了你的建議,但是我無法讓它工作,因爲'this'在地理編碼塊內部是未定義的 - 你知道如何繞過嗎? –

+0

是的,使用'function(results,status){} .bind(this)',或者在函數的開始處創建一個變量var _this = this並在回調中使用_this。但要確保你明白這裏發生了什麼!這對初學者來說非常混亂,但對於理解javascript非常重要:https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/apC.md – mweststrate

+0

謝謝!得到它了。 –

相關問題