I've run into this problem with Leaflet Map. I am trying to loop over some addresses, make a call for each loop to get the lat-long, plot on mymap, and group the markers to bound them using fitBounds
createRequest(projectUrl, getAddresses, handleErrors, projectInit)
.then( (jsonAddresses) =>{
// jsonAddresses = [{building_num: 100, street_name: 'main', ... }, {}, ...]
let state_province = ''
let markers = []
let projectsGroup = L.featureGroup().addTo(mymap) // Creating an empty group to add markers to later on
for (let address of jsonAddresses )
{
let theAddress = address.building_num + ' ' +
address.street_direction + ' ' +
address.street_name + ' ' +
address.street_type + ' ' +
address.civic_address_city + ' '+
address.state_province + ' ' +
address.country
addressInit = {'address': theAddress ,
'buidlingNum': address.building_num,
'streetName': address.street_name,
'city': address.civic_address_city
}
// Using geoApify API to get lat-long for each address
geoCodingUrl = `${geoapifyURL}${theAddress}&apiKey=${GEOAPIFY_API_KEY}`
// createRequest makes asynchronous call and returns a json response
createRequest(geoCodingUrl, getLatLongGeoApify, handleErrors, addressInit )
.then( (response) => {
latLongAddress = response
latLongAddress.address = address // address comes from the for-loop
latLongs.push(latLongAddress) // latLongAddress is a list of objects [{<lat>,<lon>}, {},...] returned by createRequest
return latLongs
})
.then( (result)=> {
let marker = L.marker( [latitude,longitude] ).addTo(mymap)
marker.addTo(projectsGroup)
markers.push(marker)
for (let project of result) // project represents the lat-long of the project, e.g. project = [<lat>,<lon>]
{
marker.setLatLng( [project.lat, project.lon] ).bindPopup("Try!") // Setting the marker coordinates
marker.addTo(projectsGroup) // Adding the marker to the projectGroup
}
mymap.setZoom(12)
})
}
// test_marker is to create another marker that cannot fit in the
// default view, which necessitates fitBounds to work properly
const test_marker = L.marker( [48.354495, -122.0905781] ).addTo(mymap)
test_marker.addTo(projectsGroup)
mymap.fitBounds(projectsGroup.getBounds() )
return latLongs
})
});
When I look at my markers in the console, it looks like an empty list, but when I open it, there are 4 markers in it. I know this must have to do with asynchronous nature of the call and the fact that the console is live, so initially it does not have any data and then it receives the data. But, I cannot figure out how I can add markers to the featureGroup in the async-proper way so I can bound them
fitBounds
?