I am trying to add covid Data from a URL to a leaflet map. The issue is that my map is loading and drawing before the data has fully loaded. I have a file of JSON data which I call statesData. Then, I use the p5.js loadJSON() function to grab covid data from a URL and another function to format that data.
// GET THE COVID DATA
function setup(){
loadJSON("https://disease.sh/v3/covid-19/states",gotData);
}
function gotData(data){
covid = data;
statesData.features[1].properties.casesPerOneMillion = covid[1].casesPerOneMillion;
// add covid cases to states data
for (let i = 0; i < statesData.features.length; i++) {
for (let j = 0; j < statesData.features.length; j++) {
if (statesData.features[i].properties.name === covid[j].state) {
statesData.features[i].properties.casesPerOneMillion = covid[j].casesPerOneMillion;
}
}
}
};
Here's an example of what the data looks like when I inspect the page and print it to the console:
Here is how I'm adding the color layers:
// GET CHLORO COLORS BASED ON CASES PER MIL NUM
function getColor(d) {
return d > 30000 ? '#800026' :
d > 25000 ? '#BD0026' :
d > 20000 ? '#E31A1C' :
d > 15000 ? '#FC4E2A' :
d > 5000 ? '#FD8D3C' :
d > 2000 ? '#FEB24C' :
d > 1000 ? '#FED976' :
'#FFEDA0';
}
// CREATE FUNCTION TO STYLE AND APPLY GET COLOR
function style(feature) {
return {
// apply get color
fillColor: getColor(feature.properties.casesPerOneMillion),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7
}
}
// doesn't work
L.geoJson(statesData, {style: style}).addTo(map);
I know it isn't an issue with the code, because this (5000 being a random num I used just to be sure my style code was working) :
statesData.features[0].properties.casesPerOneMillion = 5000;
and it does work that way.
The problem is that my map is loading before the data has finished downloading/has gone through the gotData() function that formats it. I thought the obvious solution would be to throw the L.geoJson(statesData, {style: style}).addTo(map);
into an async function, but I guess leaflet doesn't allow you to do that? I always get the error "t.addLayer()" isn't a function when I try... Anyone know how to asynchronously add data to a leaflet map? I'm familiar with javaScript but am a novice when it comes back to async functions, callbacks, etc