惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
J
Java Code Geeks
有赞技术团队
有赞技术团队
GbyAI
GbyAI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
Microsoft Security Blog
Microsoft Security Blog
IT之家
IT之家
G
Google Developers Blog
月光博客
月光博客
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
S
SegmentFault 最新的问题
博客园 - 三生石上(FineUI控件)
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - Franky
腾讯CDC
V
Visual Studio Blog
博客园 - 【当耐特】
D
Docker
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Engineering at Meta
Engineering at Meta
L
LangChain Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Build a Traffic Dashboard with Road511 + Leaflet
Roman Kotenk · 2026-05-14 · via DEV Community

Roman Kotenko

Let's build a real-time traffic dashboard from scratch. By the end, you'll have a map showing live incidents, camera popups with images, and road condition overlays — all powered by Road511's GeoJSON API.

Setup

Create an index.html with Leaflet:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9/dist/leaflet.css">
  <style>
    body { margin: 0; }
    #map { height: 100vh; }
  </style>
</head>
<body>
  <div id="map"></div>
  <script src="https://unpkg.com/leaflet@1.9/dist/leaflet.js"></script>
  <script src="app.js"></script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Initialize the Map

// app.js
const API_KEY = 'your_api_key';
const BASE = 'https://api.road511.com/api/v1';

const map = L.map('map').setView([39.8, -98.5], 5); // center of US
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; OpenStreetMap'
}).addTo(map);

Enter fullscreen mode Exit fullscreen mode

Layer 1: Traffic Events

async function loadEvents() {
  const bounds = map.getBounds();
  const bbox = [
    bounds.getWest(), bounds.getSouth(),
    bounds.getEast(), bounds.getNorth()
  ].join(',');

  const res = await fetch(
    `${BASE}/events/geojson?bbox=${bbox}&status=active&limit=500`,
    { headers: { 'X-API-Key': API_KEY } }
  );
  const data = await res.json();

  const severityColors = {
    critical: '#991b1b', major: '#ef4444',
    moderate: '#f59e0b', minor: '#22c55e'
  };

  return L.geoJSON(data, {
    pointToLayer: (f, latlng) => L.circleMarker(latlng, {
      radius: 6,
      fillColor: severityColors[f.properties.severity] || '#6b7280',
      fillOpacity: 0.8,
      stroke: false
    }),
    onEachFeature: (f, layer) => {
      const p = f.properties;
      layer.bindPopup(`
        <strong>${p.title}</strong><br>
        <span style="color:${severityColors[p.severity]}">${p.severity}</span>
        &middot; ${p.type}<br>
        ${p.affected_roads?.join(', ') || ''} ${p.direction || ''}
      `);
    }
  });
}

Enter fullscreen mode Exit fullscreen mode

Layer 2: Cameras with Image Popups

async function loadCameras(jurisdiction) {
  const res = await fetch(
    `${BASE}/features/geojson?type=cameras&jurisdiction=${jurisdiction}`,
    { headers: { 'X-API-Key': API_KEY } }
  );
  const data = await res.json();

  const camIcon = L.divIcon({
    html: '📷', className: 'camera-icon', iconSize: [20, 20]
  });

  return L.geoJSON(data, {
    pointToLayer: (f, latlng) => L.marker(latlng, { icon: camIcon }),
    onEachFeature: (f, layer) => {
      const p = f.properties;
      layer.bindPopup(`
        <strong>${p.name || f.properties.id}</strong><br>
        <img src="${p.image_url}" width="320" loading="lazy"
             onerror="this.src='data:image/svg+xml,<svg/>'">
      `, { maxWidth: 350 });
    }
  });
}

Enter fullscreen mode Exit fullscreen mode

Layer 3: Road Conditions

async function loadRoadConditions(jurisdiction) {
  const res = await fetch(
    `${BASE}/features/geojson?type=road_conditions&jurisdiction=${jurisdiction}`,
    { headers: { 'X-API-Key': API_KEY } }
  );
  const data = await res.json();

  const conditionColors = {
    dry: '#22c55e', wet: '#3b82f6', icy: '#ef4444',
    'snow-covered': '#8b5cf6', flooded: '#f97316'
  };

  return L.geoJSON(data, {
    style: (f) => ({
      color: conditionColors[f.properties.condition] || '#6b7280',
      weight: 4, opacity: 0.7
    }),
    onEachFeature: (f, layer) => {
      layer.bindPopup(`
        <strong>${f.properties.name}</strong><br>
        Condition: ${f.properties.condition}
      `);
    }
  });
}

Enter fullscreen mode Exit fullscreen mode

Put It Together

const layers = L.control.layers(null, {}).addTo(map);

loadEvents().then(layer => {
  layer.addTo(map);
  layers.addOverlay(layer, 'Events');
});

loadCameras('CA').then(layer => {
  layers.addOverlay(layer, 'Cameras (CA)');
});

loadRoadConditions('CA').then(layer => {
  layers.addOverlay(layer, 'Road Conditions (CA)');
});

// Refresh events when the map moves
map.on('moveend', async () => {
  // Remove old events layer, load new one for current viewport
});

Enter fullscreen mode Exit fullscreen mode

Auto-Refresh

Events change frequently. Add a 60-second refresh:

setInterval(async () => {
  eventsLayer.clearLayers();
  const newLayer = await loadEvents();
  newLayer.eachLayer(l => eventsLayer.addLayer(l));
}, 60000);

Enter fullscreen mode Exit fullscreen mode

Next Steps

  • Add sign messages as a layer
  • Add weather stations with condition badges
  • Show truck restrictions along a corridor
  • Use the analytics endpoints to show a sidebar with incident trends

Try It