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

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
罗磊的独立博客
T
The Blog of Author Tim Ferriss
The GitHub Blog
The GitHub Blog
Apple Machine Learning Research
Apple Machine Learning Research
The Register - Security
The Register - Security
J
Java Code Geeks
V2EX - 技术
V2EX - 技术
Vercel News
Vercel News
N
News and Events Feed by Topic
腾讯CDC
P
Proofpoint News Feed
N
News | PayPal Newsroom
www.infosecurity-magazine.com
www.infosecurity-magazine.com
爱范儿
爱范儿
O
OpenAI News
酷 壳 – CoolShell
酷 壳 – CoolShell
月光博客
月光博客
Martin Fowler
Martin Fowler
Engineering at Meta
Engineering at Meta
D
Docker
Y
Y Combinator Blog
博客园 - 聂微东
G
Google Developers Blog
S
Security @ Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
阮一峰的网络日志
阮一峰的网络日志
C
CXSECURITY Database RSS Feed - CXSecurity.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
CERT Recently Published Vulnerability Notes
I
Intezer
G
GRAHAM CLULEY
有赞技术团队
有赞技术团队
Attack and Defense Labs
Attack and Defense Labs
V
Visual Studio Blog
博客园 - Franky
博客园 - 三生石上(FineUI控件)
W
WeLiveSecurity
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hugging Face - Blog
Hugging Face - Blog
Scott Helme
Scott Helme
T
Troy Hunt's Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
LINUX DO - 最新话题
C
Cybersecurity and Infrastructure Security Agency CISA

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
I built Norway's EV charging map with Next.js and MapLibre GL JS — and hit a race condition that took me three sessions to fix
Ayyad Anwar · 2026-05-20 · via DEV Community

I recently shipped StrømVei — an
interactive EV charging map and route planner for Norway, built with Next.js 16,
TypeScript, MapLibre GL JS, and the free Nobil API.

It plots 10,000+ charging stations across Norway, lets you filter by connector
type and speed, and runs a greedy algorithm to calculate optimal charging stops
for long-distance routes.

This post covers the four things that actually taught me something while building
it: the library choice, the clustering solution, a nasty MapLibre race condition
I did not see coming, and the geospatial algorithm. The live demo and source are
at the bottom.


1. Why MapLibre GL JS instead of Mapbox

My original plan was Mapbox GL JS. It is the industry standard for interactive
maps, the documentation is excellent, and every tutorial uses it.

Then I tried to create a free account.

Mapbox requires a credit card even on the free tier. For a portfolio project
deployed publicly, that felt like unnecessary risk — what if demo traffic spiked?
What if I forgot to set a spending cap?

I switched to MapLibre GL JS, the open-source fork of Mapbox GL JS. It was
created in 2021 when Mapbox changed its licence. The API is nearly identical —
same sources, same layers, same events, same clustering. No account required. No
credit card. No API key at all.

For map tiles I used OpenFreeMap (tiles.openfreemap.org/styles/liberty),
which serves free OSM-based vector tiles with no rate limits for reasonable usage.

For routing I used the OSRM public API (router.project-osrm.org) — free,
no key, covers all of Norway.

For geocoding I used Nominatim (nominatim.openstreetmap.org) — free, no
key, with Norway filtering via countrycodes=no.

Total API cost: $0.00. All the map capability of a paid stack, none of the
billing anxiety.


2. Rendering 10,000 markers without crashing the browser

Norway has over 10,000 EV charging stations. My first instinct was to render each
one as a React component on the map. This is the approach most tutorials use for
small datasets.

For 10,000 markers it is catastrophically slow. React re-renders all of them on
any state change. The browser grinds to a halt.

The correct approach for large datasets is MapLibre's built-in GeoJSON cluster
source
. You add a single source with cluster: true, and MapLibre handles
grouping, rendering and unclustering entirely in WebGL — no React involved.


typescript
map.addSource('stations', {
  type: 'geojson',
  data: stationsGeoJSON,
  cluster: true,
  clusterMaxZoom: 13,
  clusterRadius: 50,
});


Then you add three layers on top of that source: one for cluster circles, one
for the cluster count labels, and one for individual dots at high zoom. Each
layer uses MapLibre expressions to style by data properties — connector speed in
my case:

map.addLayer({
  id: 'unclustered-point',
  type: 'circle',
  source: 'stations',
  filter: ['!', ['has', 'point_count']],
  paint: {
    'circle-color': [
      'case',
      ['>', ['get', 'maxSpeedKw'], 50], '#0066FF', // rapid — blue
      ['>=', ['get', 'maxSpeedKw'], 22], '#1A7A4A', // fast — green
      '#6B7280',                                    // slow — grey
    ],
    'circle-radius': 7,
    'circle-stroke-width': 2,
    'circle-stroke-color': '#ffffff',
  },
});
The result: 10,000 stations render instantly, zoom and pan at 60fps, and
cluster/uncluster smoothly. The difference versus React markers is not subtle —
it is the difference between a working app and a broken one.

3. The race condition that took three sessions to fix
This one hurt.

After the user enters a route and clicks "Finn rute", the app fetches geometry
from OSRM and tries to draw a blue line on the map. For two full sessions I could
not get the route line to appear. No errors. The fetch succeeded. The GeoJSON was
valid. But the map showed nothing.

Here is the simplified version of what I had:

useEffect(() => {
  const map = mapRef.current;
  if (!map) return;

  const update = () => {
    // remove old layers, add new source + layers with route data
  };

  if (map.isStyleLoaded()) {
    update();
  } else {
    map.once('load', update); // ← this was the bug
  }
}, [route]);
The logic looks reasonable. If the style is loaded, run immediately. Otherwise
wait for the load event.

The problem is that map.once('load') only fires once — at initial startup.
If the user pans or zooms the map before clicking "Finn rute", MapLibre starts
fetching new tiles. During tile fetching, isStyleLoaded() returns false. But
load has already fired and will never fire again. So update() is never called.
The route is silently dropped.

The fix is one word: replace 'load' with 'idle'.

if (map.isStyleLoaded()) {
  update();
} else {
  map.once('idle', update); // ← fires whenever rendering completes
}

return () => {
  map.off('idle', update); // clean up if route changes before idle fires
};
The idle event fires whenever MapLibre finishes rendering — after tiles load,
after panning stops, after anything. It always fires eventually. Once I understood
this, I applied the same fix to the stations effect too, since it had the same
latent bug.

The cleanup map.off('idle', update) in the effect return is also important: if
the route changes before idle fires, you want to cancel the pending callback
and let the next effect run instead.

The lesson: isStyleLoaded() is not a simple boolean. It also checks whether
source data is done loading. 'load' is a one-time startup event. For any
deferred map update, 'idle' is the correct fallback.

4. Layer ordering in OpenFreeMap
A second issue with the route line: even when it did appear, it was sometimes
invisible because it rendered underneath the base map's fill layers.

In MapLibre you can insert a layer before an existing one using the beforeId
parameter. Many tutorials suggest finding the first symbol layer in the style and
inserting before that:

const firstSymbolId = map.getStyle().layers
  .find(l => l.type === 'symbol')?.id;

map.addLayer({ id: 'route-line', ... }, firstSymbolId);
In OpenFreeMap's liberty style, the first symbol layer is positioned quite low in
the stack — below fill layers. The route line appeared to insert correctly but was
hidden under polygons.

The fix was to use a known layer I added myself as the anchor instead:

const beforeId = map.getLayer('clusters') ? 'clusters' : undefined;
map.addLayer({ id: 'route-line', ... }, beforeId);
This inserts the route below the station cluster circles but above all base map
layers. Reliable regardless of how the tile style orders its own layers.

5. The greedy charging stop algorithm
The route planner takes an origin, destination, car range (km) and minimum charge
percentage, then calculates where you need to stop to charge.

The algorithm runs on the OSRM route geometry — a GeoJSON LineString with
hundreds of coordinate points tracing the actual road. The core of it uses
Turf.js:

import { nearestPointOnLine, length, point } from '@turf/turf';

// Project each station onto the route line
const projected = stations.map(station => {
  const pt = point([station.position.lng, station.position.lat]);
  const snapped = nearestPointOnLine(routeLine, pt, { units: 'kilometers' });
  return {
    station,
    kmAlongRoute: snapped.properties.location, // distance in km from route start
    distanceFromLine: snapped.properties.dist,
  };
});

// Keep only stations within 5km of the route
const corridor = projected.filter(s => s.distanceFromLine <= 5);
corridor.sort((a, b) => a.kmAlongRoute - b.kmAlongRoute);
One non-obvious detail: when you call nearestPointOnLine with
{ units: 'kilometers' }, the returned feature's properties.location is the
distance in kilometres from the start of the line — not a 0–1 fraction. This
is not clearly documented. Getting it wrong produces completely nonsensical stop
ordering.

The greedy algorithm itself:

const effectiveRange = carRangeKm * (1 - minChargePct / 100);
let currentKm = 0;
const stops: ChargingStop[] = [];

while (currentKm + effectiveRange < totalRouteKm) {
  // Find all stations reachable from current position
  const reachable = corridor.filter(s =>
    s.kmAlongRoute > currentKm &&
    s.kmAlongRoute <= currentKm + effectiveRange
  );

  if (reachable.length === 0) {
    return { ok: false, error: 'no_station_in_range' };
  }

  // Pick the one furthest along the route
  const best = reachable.reduce((a, b) =>
    a.kmAlongRoute > b.kmAlongRoute ? a : b
  );

  stops.push({ station: best.station, distanceFromStartKm: best.kmAlongRoute });
  currentKm = best.kmAlongRoute;
}

return { ok: true, stops };
"Furthest reachable" is the greedy choice — it minimises the number of stops by
always jumping as far forward as possible. For the Oslo–Bergen route (about 480
km) with a 400 km range and 20% minimum charge, the algorithm correctly picks one
stop at Fortum Eidfjord around km 309.

The Norwegian-specific parts
The data source is Nobil — Norway's national EV charging station database,
operated by the Norwegian Electric Vehicle Association. It is free for
non-commercial use and contains live availability data for ~10,000 stations. I
proxy the API server-side to hide the key and add a 15-minute cache:

// src/app/api/nobil/stations/route.ts
let cache: { data: NobilStation[]; cachedAt: number } | null = null;
const CACHE_TTL = 15 * 60 * 1000;

export async function GET() {
  if (cache && Date.now() - cache.cachedAt < CACHE_TTL) {
    return Response.json({ stations: cache.data, cached: true });
  }
  // fetch from Nobil, parse, store in cache
}
Norway has the highest EV adoption rate in the world — around 90% of new car
sales in 2024. Long-distance route planning with charging stops is a real,
everyday problem for Norwegian drivers, which is what made this worth building.

What I would do differently
Move Turf.js to a Web Worker. With the current 18 mock stations it runs in
under 5ms. With the real 10,000-station dataset, projecting each station onto the
route line becomes a meaningful computation. It should not run on the main thread.

Add streaming to the route result. Right now the panel waits for the full
OSRM response before showing anything. A streaming approach would show the route
drawing progressively, which feels faster even if it isn't.

Real-time availability. The Nobil API includes live connector status but I
used the static snapshot. A polling interval or WebSocket connection would make
the availability dots actually meaningful.

Links
Live demo: stromvei-project.vercel.app
Source code: github.com/adyelmoro/stromvei-project
If you hit the MapLibre idle vs load issue and this helped, or if you're
building something with Norwegian APIs and want to compare notes — drop a comment.

Next up: DokumentAI — a Norwegian business document Q&A app using RAG,
pgvector, and the Claude API. Same stack, very different problem.

---
That's the full article — paste it directly into dev.to, preview it, and publish. A few quick notes:
- The **cover image** line at the top uses your og-image.svg — dev.to will pull it automatically
- The **code blocks** will syntax-highlight automatically on dev.to
- Estimated read time: about **8 minutes** — that's the sweet spot for technical articles that rank well
- The `idle` vs `load` section is the strongest part — that specific problem has almost no good documentation online, so this article will genuinely show up in Google searches

Enter fullscreen mode Exit fullscreen mode