Extra Challenge: Refactoring¶
Do you think there’s a better way for us to create the feature groups instead of adding all this code in our formatData function?
Yes, we should make a function to add each of the layers!
Due to lack of time, we won’t do any refactoring, so for now we will leave the inefficient way of repeating ourselves with the various featureGroups. But we must refactor our code if we want to add our own buttons to interact with the map instead of using the default Leaflet control functions.
Remember refactoring?¶
Refactoring code is means improving code so that it is easier to understand and easier to reuse. Refactoring is important because the less we repeat ourselves or hardcode things the less mistakes our code will have when we modify it.
Steps to refactor the group layers code¶
To refactor the group layers code you want to do the following:
- Create an array of
layersby converting thevaluesin thelayersobject to an array withObject.values(layers)
// let layers = {
// "Speaks English First": englishFirst,
// "Doesn't Speak English First": nonEnglishFirst
// }
//this is the array of layers based on the layers object above
let layersArray = Object.values(layers);
- Create a new
functionthat set layers to the map
function setTheLayer(data){
if (data['Is your English your first language?'] == "Yes"){
return "Speaks English First"
}
else{
return "Doesn't Speak English First"
}
}
- Call the function to set the layer inside of the loop for each of the data:
function processData(results){
console.log(results)
results.data.forEach(data => {
console.log(data)
let layer = setTheLayer(data)
addMarker(data)
})
let allLayers = L.featureGroup([englishFrist,nonEnglishFirst]);
map.fitBounds(allLayers.getBounds());
}
- Have the
addMarker()function use thelayerset by the new function:
function processData(results){
console.log(results)
results.data.forEach(data => {
console.log(data)
let layer = setTheLayer(data)
addMarker(data,layer)
})
let allLayers = L.featureGroup([englishFrist,nonEnglishFirst]);
map.fitBounds(allLayers.getBounds());
}
-
Change the
addMarker()function to use theLayername to populate the pop-up title: -
Change
allLayersto uselayersArrayand loop through the layers with aforEach()loop on thelayersArrayand add them to the map
function processData(results){
console.log(results)
results.data.forEach(data => {
console.log(data)
let layer = setTheLayer(data)
addMarker(data,layer)
})
let allLayers = L.featureGroup(layersArray);
layersArray.forEach(layer => layer.addTo(map))
map.fitBounds(allLayers.getBounds());
}
Your refactored code should look like the following: