03. Dynamic Map and Data Loading with fetch()
In this lesson, we will transform our application’s architecture: we will separate
the vector graphics and structured data into dedicated external files (mappa.svg and locali.json),
then load them dynamically in the browser using JavaScript’s asynchronous APIs
(fetch, async, and await).
Introduction
Section titled “Introduction”Use Case Diagram
Section titled “Use Case Diagram”Diagram created with Mermaid
Project File Structure
Section titled “Project File Structure”By the end of this lesson, the project folder will contain these files in the root directory:
Directorycampus-map/
- index.html Main HTML page containing the SVG structure and selection menus
- style.css Stylesheet for the page layout, graphics, and building highlighting
- script.js JavaScript file that loads the map and data with
fetch()and updates the DOM - mappa.svg Vector map graphic loaded into the page
- locali.json List of buildings used to populate the selection menus
Sequence Diagram
Section titled “Sequence Diagram”Diagram created with Mermaid
Component Diagram
Section titled “Component Diagram”Diagram created with Mermaid
Creating the lezione-3 Working Branch
Section titled “Creating the lezione-3 Working Branch”Before adding dynamic loading with fetch(), create a dedicated branch to isolate this lesson’s changes:
- Open the Source Control panel in VS Code (
Ctrl + Shift + G). - Click the current branch name at the bottom left (or at the top of the panel) and
select
Create New Branch.... - Enter the name of the new branch:
lezione-3, then press Enter.
Externalizing the Graphics: mappa.svg
Section titled “Externalizing the Graphics: mappa.svg”Separate the graphic code from the main HTML
by creating an mappa.svg file in the project root.
Set width="100%" and height="100%"
to make it fully responsive within its container:
<svg viewBox="0 0 800 600" width="800" height="600" xmlns="http://www.w3.org/2000/svg"> <svg viewBox="0 0 800 600" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"> <g id="layer-terreno"> <rect x="0" y="0" width="800" height="600" fill="#7ec850" /> </g>
// copia il resto della tuo codice svg <!-- Insert the route and building layers developed previously below --> <g id="layer-percorsi"> <!-- ... --> </g> <g id="layer-edifici"> <!-- ... --> </g>
</svg>Data in locali.json
Section titled “Data in locali.json”Create the locali.json file to store the building identifiers (matching the IDs in the SVG) and the readable names to display in the dropdown menus:
[ { "id": "edificio-uffici", "nome": "Uffici Amministrativi" }, { "id": "edificio-aule", "nome": "Edificio Aule" }]Styles in style.css
Section titled “Styles in style.css”Next, update style.css with responsive rules for the map container and CSS classes for symmetrical starting-point and destination highlighting.
/* delete all previous CSS code *//* --- previous CSS code ... *//* replace it with the new CSS below in green */body { font-family: Verdana, sans-serif; text-align: center; margin: 20px; background-color: #f8fafc;}
.controls { margin-bottom: 20px; display: flex; justify-content: center; gap: 15px;}
select { padding: 8px 12px; font-size: 14px; border-radius: 6px; border: 1px solid #cbd5e1;}
#mappa-container { width: 100%; max-width: 900px; margin: 0 auto; aspect-ratio: 4 / 3;}
#mappa-container svg { width: 100%; height: 100%; display: block; background: #fff; border: 2px solid #334155; border-radius: 8px;}
#layer-edifici g { cursor: pointer; transition: opacity 0.2s;}
#layer-edifici g:hover { opacity: 0.85;}
.label { fill: white; font-size: 16px; font-weight: bold; text-anchor: middle; dominant-baseline: middle; pointer-events: none;}
/* Symmetrical highlighting */.selezionato-da rect { fill: #16a34a !important; /* Green for starting point */ stroke: #052e16; stroke-width: 4px;}
.selezionato-a rect { fill: #dc2626 !important; /* Red for destination */ stroke: #450a0a; stroke-width: 4px;}Asynchronous Logic in script.js
Section titled “Asynchronous Logic in script.js”We handle loading the SVG and JSON through fetch()
and async/await, connecting both the <select> menus
and direct clicks on the buildings in the map
document.addEventListener("DOMContentLoaded", () => { caricaMappaSVG(); caricaLocaliJSON();});
async function caricaMappaSVG() { const risposta = await fetch("mappa.svg"); document.getElementById("mappa-container").innerHTML = await risposta.text();}
async function caricaLocaliJSON() { const risposta = await fetch("locali.json"); const locali = await risposta.json();
const selectDa = document.getElementById("select-da"); const selectA = document.getElementById("select-a");
locali.forEach(l => { selectDa.innerHTML += `<option value="${l.id}">${l.nome}</option>`; selectA.innerHTML += `<option value="${l.id}">${l.nome}</option>`; });}
function aggiornaEvidenziazione() { const idDa = document.getElementById("select-da").value; const idA = document.getElementById("select-a").value;
// Remove any previous highlighting document.querySelectorAll("#layer-edifici g").forEach(edificio => { edificio.classList.remove("selezionato-da", "selezionato-a"); });
// Apply the new symmetrical classes if (idDa) { document.getElementById(idDa)?.classList.add("selezionato-da"); } if (idA) { document.getElementById(idA)?.classList.add("selezionato-a"); }}
function selezionaDaMappa(idEdificio) { const selectDa = document.getElementById("select-da"); const selectA = document.getElementById("select-a");
if (!selectDa.value) { selectDa.value = idEdificio; } else if (!selectA.value && selectDa.value !== idEdificio) { selectA.value = idEdificio; } else { selectDa.value = idEdificio; selectA.value = ""; }
aggiornaEvidenziazione();}HTML Structure in index.html
Section titled “HTML Structure in index.html”The main HTML file becomes much simpler, containing only the two dropdown menus and the empty container where mappa.svg will be injected:
<!DOCTYPE html><html lang="en">
<head> <!-- unchanged head --></head>
<body> <h1>🗺️ Calcolo Percorso Campus</h1>
<!-- delete the CONTROL PANEL WITH DROPDOWN MENUS --> <div style="margin-bottom: 15px; background: white; padding: 10px; border-radius: 8px; border: 1px solid #cbd5e1;"> <!-- contenuto del div del menu a tendina --> </div>
<!-- inserisci nuovo div "controls" --> <div class="controls"> <select id="select-da" onchange="aggiornaEvidenziazione()"> <option value="">-- Partenza --</option> </select>
<select id="select-a" onchange="aggiornaEvidenziazione()"> <option value="">-- Destinazione --</option> </select> </div>
<!-- delete the embedded SVG map structure --> <!-- Embedded SVG Map Structure --> <svg> <!-- codice svg --> </svg>
<!-- insert new mappa-container div --> <div id="mappa-container"></div>
<script src="script.js"></script></body></html>Testing
Section titled “Testing”Run the project and verify that venue selections work correctly.
Commit and Final Synchronization (Git / GitHub)
Section titled “Commit and Final Synchronization (Git / GitHub)”- Check the files: Open the Source Control panel in VS Code and verify that all modified and created files (
mappa.svg,locali.json,style.css,script.js, andindex.html) are present in the staging area. - Create the commit: Enter the commit message:
"Lesson 3 complete: asynchronous Fetch and responsive SVG"and confirm. - Synchronize: Select Publish Branch or Sync Changes to send everything to GitHub.
Summary
Section titled “Summary”Learning Check
Section titled “Learning Check”Your answers to the quizzes on this page are saved in local storage in your browser and remain stored between visits
What is the purpose of the caricaMappaSVG() function?
- Convert JSON data into
<option>elements. - Retrieve
mappa.svgwithfetch()and insert its text into the HTML container.Correct: the content returned by
fetch()is assigned to themappa-container’sinnerHTML. - Automatically highlight the buildings on the map.
What does await risposta.json() produce in the script?
- A string containing all the SVG code.
- A CSS class to add to the buildings.
- A JavaScript data structure corresponding to the contents of
locali.json.Correct: in this case, JSON is converted into an array of objects with
idandnomeproperties.
How are buildings dynamically added to the two <select> menus?
- By manually copying
optionelements intoindex.html. - By iterating through the
localiarray withforEach()and addingoptionelements toselect-daandselect-a.Correct: an option is created for each venue with
l.idas its value andl.nomeas its visible text. - By retrieving names from the
<rect>elements in the SVG.
Why do async functions use the await operator with fetch()?
- To stop the entire page from running permanently.
- To wait for the asynchronous response before reading the text or JSON.
Correct:
awaittemporarily suspends the function until the corresponding asynchronous operation is complete. - To prevent the browser from loading
mappa.svgandlocali.json.
Which CSS classes does aggiornaEvidenziazione() use to distinguish the starting point and destination?
-
attivoandselezionato. -
selezionato-daandselezionato-a.Correct: the first indicates the starting point in green, and the second indicates the destination in red.
-
hover-daandhover-a.
How does selezionaDaMappa(idEdificio) handle clicks on the map?
- It always sets the destination and leaves the starting point empty.
- It removes all buildings from the DOM.
- It sets the starting point first, then the destination, and finally restarts selection if both are already set.
Correct: the function synchronizes the two menus and calls
aggiornaEvidenziazione()to update the map.
Why is it recommended to use Live Server when making fetch() requests?
- To automatically enlarge the SVG and JSON files.
- To serve the files over HTTP and avoid CORS issues associated with opening them directly via
file://.Correct: in a local environment, Live Server allows the browser to load
mappa.svgandlocali.jsoncorrectly. - To automatically convert JSON into HTML.
Quiz Progress
0 / 0 questions answered (0%)
0 correct answers
Your Score
0%
0 / 0 correct answers
Answered: 0 / 0 (0%)
STICS © 2026 by Carlo Scocco is licensed under CC BY-NC 4.0