Charge-aware routing for personal electric vehicles
On this page 21
Overview
Flow routes personal electric vehicles (PEVs) — electric unicycles, e-scooters, e-bikes, onewheels — along the best available roads with automatically placed charging stops. This paper describes how the routing engine works: the pipeline from destination input to charge-stop chain, the energy model that determines reachability, the charger discovery and filtering approach, the stop-selection algorithm, and the road-quality scoring system that prefers scenic two-lane highways over freeways.
PEV routing differs from car navigation in two important ways. First, PEVs are restricted to certain road classes — most interstates and limited-access freeways are off-limits, with narrow exceptions where bicycles are permitted on rural freeway shoulders. Route quality is therefore a safety and legality constraint as well as a preference. Second, PEVs use AC mains charging: the same J1772 socket at a destination charger, an RV hookup at a campground, or a standard 110V outlet. Car DC fast-chargers (CCS, CHAdeMO, NACS/Supercharger) are entirely incompatible. The charger universe available to a PEV rider looks almost nothing like the one available to an EV driver.
1. Route-first pipeline
The original routing approach placed chargers first and then tried to build a road route through them. Flow now inverts this: the actual road is fetched first, and chargers are discovered along that specific polyline.
The pipeline runs in four stages:
Fetch base route. Mapbox Directions returns the road geometry for the chosen profile (driving or cycling) as a precision-6 encoded polyline. For distance mode, multiple candidates are fetched in parallel — driving with alternatives, driving with motorway exclusion, cycling profile, and OSM bicycle network routes — and ranked before the rider selects one.
Discover chargers along the polyline. The polyline is segmented into ~50 km chunks with 10 km overlap. Each segment is expanded into a bounding box padded by 8 km, and charger sources are queried in parallel. Results are deduplicated by ID across segments, then each charger is projected onto the polyline to compute its exact detour distance and route position.
Filter for compatibility. Chargers incompatible with the rider's vehicle type are removed. For all current PEV types, this means keeping only chargers that have at least one AC or RV connector (J1772, NEMA outlet, RV hookup). A station with both a DC fast unit and a J1772 pedestal is kept — the J1772 is the relevant connector.
Select optimal stops. A greedy algorithm walks the route, at each position finding all reachable chargers and scoring them on five factors: progress along the route, detour distance, connector tier, time impact, and observed reliability. It picks the best stop, advances to it, and repeats until the destination is reachable. Different modes apply different margin and spacing rules.
2. Energy and range model
SOC-distance relationship
Flow estimates energy consumption using coefficients derived from each vehicle's profile: battery capacity in Wh, practical range at a reference speed, and the charger wattage. The consumption model uses speed-adjusted Wh-per-km coefficients. At routing time, the engine uses an assumed average speed derived from the vehicle type to compute reachable distances.
Reachable distance from a given SOC is computed as:
reachableKm = maxDistanceAtSpeed(batteryCapacityWh, currentSOC, avgSpeedKmh, coefficients)
The safety margin — a configurable percentage of battery capacity — is subtracted from reachable distance before any routing decision. In cruise mode, this margin is applied at full vehicle-profile value. In distance mode (multi-stop long-distance planning), the margin is scaled down to approximately 60% of the configured value, matching real-world distance riders who push closer to the reserve than the conservative default.
Elevation energy
After Mapbox Directions returns the per-leg road geometry, elevation data is fetched for sampled points along the polyline. The elevation profile is split into per-leg statistics: cumulative gain (sum of positive deltas) and cumulative loss (sum of absolute negative deltas) are tracked separately rather than using net change.
A leg that climbs 300m then descends 300m has zero net grade but costs significantly more energy than flat — the climb energy cannot be fully recovered on descent. Energy contribution from elevation is computed separately from speed-based consumption and added to the per-leg total:
elevWh = elevationEnergyWh(gainM, lossM)
The elevation coefficients model partial regeneration on descent. This is applied during the battery recalculation pass that runs after the route is built — replacing the initial haversine-based estimates with real Mapbox leg distances and elevation-adjusted Wh figures.
Charging time model
Charge time estimation uses a simplified two-phase model:
- Below 80% SOC: linear at the station's power (capped by vehicle's maximum charge rate).
- Above 80% SOC: linear at 50% of the station's power, approximating the taper behavior of real charge curves.
This is a planning model, not a precise prediction — actual charge curves vary by vehicle, temperature, and state of charge history. The two-phase model reliably overestimates charge time for the below-80 phase (because it ignores the accelerating effect of cells accepting current freely at low SOC) while the 50% taper above 80% provides a reasonable approximation. For route planning purposes the model is conservative in the right direction: planned stops take slightly less time than estimated.
Station power is determined from connector data when available, with known defaults applied when it is not: J1772 → 7.2 kW, NEMA 14-50 → 6 kW (conservative: assumes a 120V one-leg connection; full 240V/50A is up to 12 kW), NEMA TT-30 → 3.6 kW (120V/30A), NEMA 5-15 → 1.4 kW.
3. Charger discovery and filtering
Multi-source aggregation
Four data sources are queried in parallel for each route segment (RIDB joins the set where campground data is relevant):
- NREL/NLR (National Renewable Energy Laboratory): US government database of EV charging stations. Best source for operational status in the US.
- Open Charge Map (OCM): Community-contributed global database. Richer connector detail in some regions; covers international sites.
- OpenStreetMap Overpass: Community-contributed worldwide. Best coverage of informal and rural sites — campground outlets, destination chargers at trailheads, home-sharing stations.
Community chargers added directly by riders appear on the map and in nearby-charger lookups, but are not included in the per-segment route-planning query.
Each source is fetched with timeout protection and graceful failure — a single source going down does not prevent routing. Results from all sources are flattened into a single list and passed to the deduplicator.
Deduplication
The same physical station almost always appears in multiple databases. The deduplicator resolves this using two spatial rules:
- Within 25 meters: always the same station, regardless of name.
- Between 25 and 50 meters: same station if normalized name similarity exceeds a threshold (Levenshtein distance after stripping words like "station," "charging," "EV," and level designators that vary between APIs).
Source priority for metadata follows NREL > OCM > OSM > RIDB > Community. When records merge, connector lists are combined — if NREL has a J1772 record and OCM has a DC fast unit record for the same site, the merged result holds both. The station's effective level is recomputed from the merged connector list, reflecting the highest level present across all merged records.
Connector-authoritative filtering
Flow's routing filter evaluates chargers at the connector level, not the station level. A charger is kept for routing if it has at least one connector a PEV can use — J1772, any NEMA outlet, or an RV hookup. A charger is excluded only when all of its connectors are DC-only types (CCS, CHAdeMO, NACS/Tesla Supercharger).
This matters because aggregators often classify a whole station based on its highest-power connector. A mixed DC+J1772 site appears as a "DC fast" station in most databases. A station-level filter would drop it — eliminating a perfectly usable J1772 stop from the route. Connector-level evaluation catches these cases.
The motivating example: a site near Laytonville, CA had its L2 J1772 and DC fast unit merged into a single record by the deduplicator, with the effective level set to DC fast (the highest level present). An earlier station-level filter dropped this record entirely, producing a false 47-mile gap warning on the Mendocino corridor. The connector-level check keeps the site because the J1772 is still present and usable.
4. Charger tier system
Retained chargers are assigned a tier based on their best usable connector:
| Tier | Connectors | Score | Typical power |
|---|---|---|---|
| 1 — Primary | J1772 (Level 2 AC) | 1.0 | 6–7.2 kW |
| 2 — Rural bridge | NEMA 14-50, NEMA TT-30 | 0.7 | 3.6–6 kW (conservative; 14-50 up to 12 kW at full 240V) |
| 3 — Emergency | NEMA 5-15, NEMA 5-20, Other | 0.1 | 1.4–1.9 kW |
The tier score is one of the weighted inputs to stop selection. It prevents the algorithm from preferring a Tier 3 outlet directly on the road over a Tier 1 J1772 with a small detour.
5. Stop-selection algorithm
Greedy farthest-reachable with quality scoring
The algorithm maintains current position along the route and current SOC. At each iteration:
Find all chargers ahead of current position that are reachable from current SOC with the mode's effective margin.
Remove chargers too close to the previous stop (minimum spacing: 15 km in cruise mode, 8 km in distance mode — tighter spacing allows denser coverage on long rural corridors).
Score each candidate on four weighted factors:
- Progress: distance this stop advances along the remaining route. The heaviest factor.
- Detour: inverse of perpendicular distance from the polyline (8 km = zero score).
- Tier: connector tier score.
- Time impact: inverse of total detour drive time plus estimated charge time.
- Reliability: how well the charger has actually worked for riders who went there.
The exact weights are tuned against real routes and deliberately not published — they move as the corpus grows.
Pick the highest-scoring candidate.
Compute arrival SOC using energy model.
Compute departure SOC: cruise mode charges only as much as the next hop requires (plus safety margin); distance mode charges to 90% at every stop for chain safety.
Advance position and SOC, repeat.
Charge as late as possible
In cruise mode, Flow applies a skip optimization: if the current SOC is sufficient to reach the stop after the next one, the algorithm skips the nearer stop and drives past it. This reduces total stops and charge time for short-to-medium routes where the rider has enough range to be selective. The rider arrives at each stop with more battery, spends less time charging, and doesn't stop unnecessarily.
In distance mode — multi-stop long routes — skipping is disabled. Distance riders want the full chain for safety and predictability, and the algorithm charges to 90% at each stop.
Handling gaps
If no reachable charger exists ahead of current position, the behavior depends on mode:
- Cruise mode: stops are returned with a warning. The rider sees the gap mileage and is advised to plan manually for that segment.
- Distance mode: the algorithm jumps position to the next available charger in the database and resumes the chain from there, recording the gap as a warning. The prior stop is upgraded to 90% departure to give the rider maximum range before the gap. The result is a partial chain that shows the rider where the charger coverage resumes after the gap — rather than discarding the rest of the route entirely.
6. Road quality and freeway avoidance
Candidate generation
For routes over ~30 miles, Flow generates candidates from four sources in parallel:
- Driving with alternatives (1–3 candidates)
- Driving with motorway exclusion (0–1 candidate, deduplicated if it overlaps with #1)
- Cycling profile (0–1 candidate, always included if returned — represents a different riding mode)
- OSM bicycle network (0–2 candidates for national/regional cycling routes passing through the corridor)
Routes that overlap more than 90% (sampling every 10th coordinate point) are deduplicated. Any candidate more than 1.8× the shortest candidate's distance is dropped as impractical.
Adventure scoring
Each candidate is scored before presentation to the rider:
Bicycle network (30%): Named NCN/RCN routes score 1.0 / 0.8 respectively. A cycling-profile route without a named route identity scores 0.4. A driving-profile route scores 0.
Safety (25%): Computed from the safety analyzer's output. Interstate distance is weighted at 3× in the penalty calculation, so 33% interstate distance zeroes this factor. Dangerous-highway (US highway with divided-highway characteristics) distance is weighted at 1.5×. State highways and local roads are not penalized.
Road character (20%): Computed from Mapbox step ref fields. Interstates and US highways score 0. State highways (CA-1, OR-36, WA-20) score full credit. Unnamed/local roads score 0.6 credit. The result is the ratio of adventure-weighted distance to total distance.
Through-route (15%): The dominant road (most total distance) in the candidate is checked for proximity to the destination. Within 5 km of the destination = full score; linear falloff to 0 at 15 km. This prevents adventure scoring from promoting routes that diverge from the destination.
Duration (10%): Routes within 1.3× the fastest candidate's duration score proportionally from 1.0 to 0.7. Beyond 2× = zero. This is a soft penalty — a 25% longer scenic route loses only a small amount of score.
The recommended candidate (highest total score) is presented first. The rider can inspect all candidates, see safety warnings, and choose a different one before planning begins.
Pre-baked corridor waypoints
For established long-distance PEV corridors — primarily the California coast — Flow stores pre-computed waypoint chains in a backend corridors table. These waypoints are derived from the same OSM bicycle network data an on-demand query would return, but available instantly without a live Overpass query.
When a route matches a stored corridor, the waypoints are passed to Mapbox as intermediate routing points. This forces the directions engine to follow the corridor road through segments where it would otherwise default to the faster inland highway. The result is a route that stays on CA-1 through the Mendocino coast rather than routing via US-101 from Leggett south.
As of this writing, 39 corridor segments are stored, covering the primary PEV touring corridors in Northern California. The system is designed to be extended as rider data accumulates from distance rides.
7. Routing modes
Flow exposes three routing modes:
Chill uses the Mapbox cycling profile and does not plan charge stops. Intended for short urban trips on bike-path networks.
Cruise uses the driving profile with motorway exclusion as its primary attempt. If the exclusion produces a detour greater than 1.5× the straight-line distance, it falls back to plain driving. Cruise builds a charge chain using cruise-mode stop selection (minimum stops, skip optimization enabled). Suitable for day trips where the route mostly fits within range.
Charge (labeled "Distance" internally) uses the full adventure-scored candidate pipeline, builds a complete charge chain with distance-mode stop selection (full chain, 90% departure SOC, skip disabled, gap-and-resume across coverage holes). Intended for multi-day distance rides on PEV corridor routes.
8. Limitations and design notes
Temperature derate. Battery capacity decreases with temperature — significantly below 5°C, measurably above 35°C. The current energy model does not apply a temperature correction. On cold-weather routes, riders should expect shorter practical range than the model predicts and increase their safety margin accordingly. Temperature-aware derate is a planned extension to the range model.
Elevation data latency. Elevation samples are fetched from a third-party API after the base route is built. On high-latency connections or long routes, this adds a noticeable step. The fallback is to present the route with haversine-estimated batteries and refine after elevation data arrives.
Speed assumptions. The routing model uses a single assumed average speed per vehicle type for energy computation. Real-world speed varies with terrain, headwind, and rider preference. For conservative planning, the assumed speed is set slightly below typical cruising speed for each vehicle class.
Mapbox road classification. Mapbox's "motorway" classification includes some rural 2-lane state highways based on route designation rather than road character. CA-1, US-101 through Mendocino, and similar roads sometimes appear as "motorway" in Mapbox step data. The safety analyzer does not flag state highways (pattern-matched by two-letter state prefix), so these roads are treated correctly in scoring even when Mapbox's exclude parameter would avoid them.
Charger data freshness. The multi-source aggregation fetches live data on each route request. Operational status from NREL is the most reliable signal for "is this charger working today" — but NREL data has a reporting lag of days to weeks. Community charger records (added directly by riders) are the freshest for recently added or verified stations.
See also: How Flow routes around chargers you can actually use → · How Flow avoids freeways and finds good roads →