I have a list of properties in a propertyArray, and I send each address into mapBox Geocoding so it will return coordinates. The issue is I'm only accessing the last i variable inside of the .then loop.
Ex: I want to access property[3].city but it will all return property[77].city 77 times. How can I access the correct i variable?
I've tried setting the response to another variable outside the .then function. I've tried setting another function for the geocoding. Any recommendations? Thanks!
var markers = [];
for (var i in propertyArray) {
const mapboxClient = mapboxSdk({ accessToken: mapboxgl.accessToken });
var response = null;
mapboxClient.geocoding
.forwardGeocode({
query: propertyArray[i].address + ' '+ propertyArray[i].city + ', NV',
autocomplete: false,
limit: 1
})
.send()
.then((response) => {
if (
!response ||
!response.body ||
!response.body.features ||
!response.body.features.length
) {
console.error('Invalid response:');
console.error(response);
return;
}
const feature = response.body.features[0];
response = feature;
markers[i] = document.createElement('div');
markers[i].className = 'marker';
markers[i].innerHTML = propertyArray[i].price;
markers[i].style.backgroundColor = `white`;
markers[i].style.width = `50px`;
markers[i].style.height = `50x`;
markers[i].style.backgroundSize = '100%';
// Create a marker and add it to the map.
new mapboxgl.Marker(markers[i])
.setLngLat(feature.center)
//.setPopup(popup) // sets a popup on this marker
.setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
.setHTML(propertyArray[i].address))
.addTo(map);
});
}
});