Reputation: 109
I've implemented in this:
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)
}
I'm trying to basically update this.state.markers (an array which has all my lat/lngs where the pins will be dropped) with whatever is in the arrOfAdds array, but I suppose I can't update this.state.markers?
It seems like when i run a debugger in the function, it skips over the this.props.properties.map(...
and goes straight to the arrOfAdds.map...
, which from the beginning is an empty array, doesn't append anything and then goes through the this.props.properties.map(...
to create a properly populated arrOfAdds.
Fairly confused as to how to do this, would love assistance.
Upvotes: 0
Views: 704
Reputation: 4978
geocoder.geocode is most probably an async function, so it means your addition code is run before you received the actual data. If you move that code inside the geocode callback it is probably fixed (you could simply do this.state.markers.push
and skip the arrOfAdds
collection completely. (note that the closure is not yet bound to this btw! so best use an arrow function or bind)
N.B.
If your example is from a react component, note that it is considered a bad practice to modify this.state
directly, but setState
should be used. But if your markers are an observable array, it doesn't really matter.
Upvotes: 2