Skip to content

04. Graphs, Dijkstra, and Path Animation - Part 1/2

In this lesson, we transform the map from a simple graphical representation into a real travel network:

  • buildings become nodes in a graph,
  • pedestrian paths become weighted edges, and
  • the browser automatically calculates the shortest route between two points using Dijkstra’s algorithm.
flowchart TD Utente(["🚶 User"]) subgraph Sistema ["Interactive Campus Map"] U1(["Select Starting Point"]) U2(["Select Destination"]) U3(["Calculate Shortest Path"]) U4(["Display Animated Route"]) end Utente --> U1 Utente --> U2 U1 -.->|"<<include>>"| U3 U2 -.->|"<<include>>"| U3 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

At the end of this lesson, the project folder will contain these files in its root directory:

  • Directoryinteractive campus map project/
    • dijkstra.js JavaScript module containing Dijkstra’s algorithm for calculating the shortest path[cite: 2]
    • grafo.json Graph data structure containing the nodes and weighted path edges[cite: 2]
    • index.html Main HTML page containing the map and selection controls[cite: 2]
    • locali.json List of buildings, used to dynamically populate the selection menus[cite: 2]
    • mappa.svg Vector map graphic loaded into the page[cite: 2]
    • script.js Main logic that loads files with fetch(), handles events, and draws the path in the DOM[cite: 2]
    • style.css Stylesheet for the page layout, building highlights, and path animation[cite: 2]
sequenceDiagram actor Utente as User participant DOM as Interface (HTML/SVG) participant JS as script.js participant JSON as grafo.json participant Algoritmo as dijkstra.js Utente->>DOM: Select starting point and destination DOM->>JS: Trigger aggiornaEvidenziazione() JS->>JSON: fetch("grafo.json") JSON-->>JS: Return graph object JS->>Algoritmo: calcolaDijkstra(grafo, inizio, fine) Algoritmo-->>JS: Return shortest-path node array JS->>DOM: ottieniCoordinateNodo() & insert <polyline> DOM-->>Utente: Display animated route

Diagram created with Mermaid

flowchart TD Browser[Web Browser] HTML[index.html] CSS[style.css] JS[script.js] DIJKSTRA[dijkstra.js] SVG[mappa.svg] LOCALI[locali.json] GRAFO[grafo.json] Mappa[Map SVG in the DOM] Menu[Starting Point and Destination Menus] Browser -->|loads the page| HTML HTML -->|links the stylesheet| CSS HTML -->|starts the code| JS JS -->|imports module| DIJKSTRA JS -->|"fetch()"| SVG JS -->|"fetch()"| LOCALI JS -->|"fetch()"| GRAFO SVG -->|inserts the markup| Mappa LOCALI -->|populates the options| Menu Menu -->|starting point/destination selection| JS GRAFO -->|provides nodes and edges| DIJKSTRA DIJKSTRA -->|returns shortest path| JS JS -->|draws path and highlights| 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,DIJKSTRA app; class SVG,LOCALI,GRAFO data; class Mappa,Menu html;

Diagram created with Mermaid

Before integrating the graph structure and Dijkstra’s algorithm for calculating shortest paths, 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 in the lower-left corner (or at the top of the panel) and select Create new branch....
  3. Enter the new branch name: lezione-4, then press Enter.

To make routes follow the roads and avoid cutting across lawns “as the crow flies,” we need to define points (junctions) along the pedestrian paths, at:

Path APath B90°Intersection Junction
Main pathBuilding ABuilding B90°90°Road Junction 1Road Junction 2CenterCenter

To make it easier to position junctions, add meaningful id values to the paths in mappa.svg:

mappa.svg
<!-- LAYER 2: PEDESTRIAN PATHS -->
<g id="layer-percorsi">
<rect x="50" y="270" width="700" height="60" fill="#d1d5db" rx="4" />
<rect id="percorso-orizzontale" x="50" y="270" width="700" height="60" fill="#d1d5db" rx="4" />
<rect x="180" y="80" width="50" height="440" fill="#d1d5db" rx="4" />
<rect id="percorso-est" x="570" y="80" width="50" height="440" fill="#d1d5db" rx="4" />
<rect x="180" y="80" width="50" height="440" fill="#d1d5db" rx="4" />
<rect id="percorso-ovest" x="180" y="80" width="50" height="440" fill="#d1d5db" rx="4" />
</g>

Now add the junction layer at the end of mappa.svg, positioning the first access points orthogonal to the buildings and the main intersections:

mappa.svg
<!-- EXISTING LAYERS -->
<!-- NEW ROAD AND ACCESS JUNCTION LAYER -->
<g id="layer-snodi">
<!-- Access junctions orthogonal to the buildings -->
<circle id="snodo-uffici" cx="205" cy="150" r="4" fill="#dc2626" />
<circle id="snodo-aule" cx="205" cy="430" r="4" fill="#dc2626" />
<circle id="snodo-mensa" cx="310" cy="300" r="4" fill="#dc2626" />
<!-- Junctions at the main road intersections -->
<circle id="snodo-incrocio-ovest" cx="205" cy="300" r="4" fill="#0284c7" />
<circle id="snodo-incrocio-est" cx="595" cy="300" r="4" fill="#0284c7" />
</g>
</svg>

To make positioning and visual calibration easier, add this rule to style.css:

style.css
/* In style.css: comment out or uncomment display to show/hide junctions */
#layer-snodi {
/* display: none; */
}

Define the Graph with Junctions (grafo.json)

Section titled “Define the Graph with Junctions (grafo.json)”

Now that we have positioned the road junctions in mappa.svg, we need to update grafo.json. Connections will no longer link buildings directly; they will pass through junction nodes.

Here is a valid grafo.json snippet modeling the route from the offices to the intersections via junctions:

grafo.json
{
"edificio-uffici": {
"snodo-uffici": 30
},
"snodo-uffici": {
"edificio-uffici": 30,
"snodo-incrocio-ovest": 100
},
"snodo-incrocio-ovest": {
"snodo-uffici": 100,
"snodo-aule": 100,
"snodo-mensa": 100
}
}

This file represents the campus road and connection graph using a nested JSON object (an adjacency map or table):

  • Top-level keys (nodes): Each top-level key (such as "edificio-uffici" or "snodo-incrocio-ovest") represents a reference point on the map, whether a building or a strategic intersection.

  • Nested objects (edges and weights): Each node contains another object listing its directly reachable neighbors and their numerical weights (the distance in meters or travel cost) required to move from one point to another.

  • Bidirectionality: Notice that connections are mirrored (e.g. from edificio-uffici to snodo-uffici and back), reflecting the undirected graph structure in which roads can be traveled in either direction.

  1. Check the files: Open the Source Control panel in VS Code and make sure all modified and created files (grafo.json, mappa.svg, locali.json, style.css, script.js, and index.html) are in the staging area.
  2. Create the commit: Enter the commit message "Completed Lesson 4: Graphs, Dijkstra, and Path Animation Part 1/2" and confirm.
  3. Sync: Use Publish Branch or Sync Changes to push everything to GitHub.