Skip to content

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).

flowchart TD Utente(["🚶 User"]) subgraph Sistema ["Interactive Campus Map"] U1(["View the Campus Map"]) U2(["Select the Starting Point"]) U3(["Select the Destination"]) U4(["View the Highlighted Buildings"]) end Utente --> U1 Utente --> U2 Utente --> U3 U2 -.->|"<<include>>"| U4 U3 -.->|"<<include>>"| U4 classDef actor fill:#1e3a8a,stroke:#3b82f6,color:#fff,stroke-width:2px; classDef usecase fill:#2563eb,stroke:#1d4ed8,color:#fff,stroke-width:2px; classDef system fill:#f8fafc,stroke:#64748b,stroke-width:2px,color:#0f172a; class Utente actor; class U1,U2,U3,U4 usecase; class Sistema system;

Diagram created with Mermaid

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
sequenceDiagram actor Utente participant HTML as index.html participant JS as script.js participant SVG as mappa.svg participant JSON as locali.json participant DOM as Browser DOM Utente->>HTML: Opens the page in the browser HTML->>JS: Runs DOMContentLoaded event par Asynchronous Loading JS->>SVG: fetch("mappa.svg") SVG-->>JS: Returns SVG text JS->>JSON: fetch("locali.json") JSON-->>JS: Returns JSON array end JS->>DOM: Injects SVG into #mappa-container and populates <select> DOM-->>Utente: Shows the responsive map and ready menus Utente->>DOM: Selects a building (click or menu) DOM->>JS: Triggers aggiornaEvidenziazione() JS->>DOM: Adds CSS classes (.selezionato-da / .selezionato-a) DOM-->>Utente: Shows the symmetrically highlighted buildings

Diagram created with Mermaid

flowchart TD Browser[Web Browser] HTML[index.html] CSS[style.css] JS[script.js] SVG[mappa.svg] JSON[locali.json] Mappa[Map SVG in the DOM] Menu[Selection Menus and Details] Browser -->|loads the page| HTML HTML -->|links the stylesheet| CSS HTML -->|starts the code| JS JS -->|"fetch()"| SVG JS -->|"fetch()"| JSON SVG -->|inserts the markup| Mappa JSON -->|populates the options| Menu Menu -->|user selection| JS JS -->|updates highlighting| Mappa classDef browser fill:#1e3a8a,stroke:#3b82f6,color:#fff,stroke-width:2px; classDef html fill:#2563eb,stroke:#1d4ed8,color:#fff,stroke-width:2px; classDef data fill:#059669,stroke:#047857,color:#fff,stroke-width:2px; classDef app fill:#7c3aed,stroke:#5b21b6,color:#fff,stroke-width:2px; class Browser browser; class HTML,CSS html; class JS app; class SVG,JSON data; class Mappa,Menu html;

Diagram created with Mermaid

Before adding dynamic loading with fetch(), create a dedicated branch to isolate this lesson’s changes:

  1. Open the Source Control panel in VS Code (Ctrl + Shift + G).
  2. Click the current branch name at the bottom left (or at the top of the panel) and select Create New Branch....
  3. Enter the name of the new branch: lezione-3, then press Enter.

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:

mappa.svg
<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>

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:

locali.json
[
{ "id": "edificio-uffici", "nome": "Uffici Amministrativi" },
{ "id": "edificio-aule", "nome": "Edificio Aule" }
]

Next, update style.css with responsive rules for the map container and CSS classes for symmetrical starting-point and destination highlighting.

style.css
/* 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;
}

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

script.js
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();
}

The main HTML file becomes much simpler, containing only the two dropdown menus and the empty container where mappa.svg will be injected:

index.html
<!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>

Run the project and verify that venue selections work correctly.

Commit and Final Synchronization (Git / GitHub)

Section titled “Commit and Final Synchronization (Git / GitHub)”
  1. 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, and index.html) are present in the staging area.
  2. Create the commit: Enter the commit message: "Lesson 3 complete: asynchronous Fetch and responsive SVG" and confirm.
  3. Synchronize: Select Publish Branch or Sync Changes to send everything to GitHub.

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.svg with fetch() and insert its text into the HTML container.

    Correct: the content returned by fetch() is assigned to the mappa-container’s innerHTML.

  • 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 id and nome properties.

How are buildings dynamically added to the two <select> menus?

  • By manually copying option elements into index.html.
  • By iterating through the locali array with forEach() and adding option elements to select-da and select-a.

    Correct: an option is created for each venue with l.id as its value and l.nome as 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: await temporarily suspends the function until the corresponding asynchronous operation is complete.

  • To prevent the browser from loading mappa.svg and locali.json.

Which CSS classes does aggiornaEvidenziazione() use to distinguish the starting point and destination?

  • attivo and selezionato.
  • selezionato-da and selezionato-a.

    Correct: the first indicates the starting point in green, and the second indicates the destination in red.

  • hover-da and hover-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.svg and locali.json correctly.

  • To automatically convert JSON into HTML.

Quiz Progress

0 / 0 questions answered (0%)

0 correct answers