Skip to content

Commit d3bb834

Browse files
committed
Add map traffic provider and incident support
Expand the maps bridge to support pluggable traffic flow and incident layers, including new HERE and Azure Maps flow providers plus TomTom incidents. Wire the new incidents metadata and tile endpoint through the .NET and TypeScript clients, Blazor map component, JS renderer, tests, and README/skill docs. The sample app now lets traffic providers and API keys be selected at runtime, and the TypeScript generator now emits types referenced only through dictionary values.
1 parent 74a203f commit d3bb834

25 files changed

Lines changed: 1186 additions & 109 deletions

File tree

‎clients/typescript/src/maps.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@ export interface MapsInfo {
111111
attribution: string;
112112
/** The live traffic layer, when the app configured a traffic provider. Null otherwise. */
113113
traffic: TrafficInfo | null;
114+
/** Live traffic incidents — accidents, roadworks, closures — when the app configured an incident provider. Null otherwise. */
115+
incidents: TrafficIncidentInfo | null;
114116
}
115117

116118
export interface RouteAvoid {
@@ -149,6 +151,37 @@ export interface RouteStop {
149151
name?: string | null;
150152
}
151153

154+
/** A live layer of traffic incidents, whatever provider is behind it: vector tiles holding the stretch of road an incident affects as lines, where it is as points, or both. Tiles come through the bridge, which holds the provider's key, and only while online. */
155+
export interface TrafficIncidentInfo {
156+
/** The incident tiles: `…/maps/incidents/{z}/{x}/{y}`. */
157+
tilesUrl: string;
158+
/** Below this the layer draws nothing, and no tiles are asked for. */
159+
minZoom: number;
160+
/** The highest zoom the provider has. The renderer scales past it. */
161+
maxZoom: number;
162+
/** How often the page should fetch the tiles again. */
163+
refreshSeconds: number;
164+
/** The layer inside each tile holding the affected stretches of road. Null when the provider has none. */
165+
lineSourceLayer: string | null;
166+
/** The layer inside each tile holding incident locations. Null when the provider has none. */
167+
pointSourceLayer: string | null;
168+
/** The property holding the provider's incident type. */
169+
kindProperty: string;
170+
/** The provider's values of `kindProperty`, as text, and what each is. Anything not listed is `Other`. */
171+
kinds: Record<string, TrafficIncidentKind>;
172+
/** The property holding a description to show for an incident. Null when there is none. */
173+
descriptionProperty: string | null;
174+
/** The property holding the delay the incident causes, in seconds. Null when there is none. */
175+
delayProperty: string | null;
176+
/** The property holding how many incidents a point stands for, where the provider groups them. Null when it does not. */
177+
clusterSizeProperty: string | null;
178+
/** The credit the provider's terms require, as HTML. */
179+
attribution: string;
180+
}
181+
182+
/** What a traffic incident is, whatever each provider calls it. The map colours incidents by it. */
183+
export type TrafficIncidentKind = "Other" | "Accident" | "Congestion" | "RoadWorks" | "RoadClosed" | "LaneClosed" | "Weather" | "Hazard" | "BrokenDownVehicle";
184+
152185
/** A live traffic layer, whatever provider is behind it. Tiles come through the bridge, which holds the provider's key, and only while online: offline the layer is simply empty. */
153186
export interface TrafficInfo {
154187
/** The traffic tiles: `…/maps/traffic/{z}/{x}/{y}`. */
@@ -236,6 +269,11 @@ export class MapsBridge {
236269
return callBlob(this.transport, "GET", `maps/traffic/${segment(z)}/${segment(x)}/${segment(y)}`, { signal: options?.signal });
237270
}
238271

272+
/** One live traffic incident tile, as the renderer asks for it through `tilesUrl`. 204 when the provider has nothing there or cannot be reached; 501 when the app configured no incident provider. */
273+
getIncidentTile(z: number, x: number, y: number, options?: { signal?: AbortSignal }): Promise<Blob> {
274+
return callBlob(this.transport, "GET", `maps/incidents/${segment(z)}/${segment(x)}/${segment(y)}`, { signal: options?.signal });
275+
}
276+
239277
/** A range of label glyphs, as MapLibre asks for it through `glyphsUrl`: `0-255.pbf`. */
240278
getGlyphs(fontstack: string, range: string, options?: { signal?: AbortSignal }): Promise<Blob> {
241279
return callBlob(this.transport, "GET", `maps/glyphs/${segment(fontstack)}/${segment(range)}`, { signal: options?.signal });

‎readme.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ app, served from the device itself, updated from your own server, and able to ca
5656
| `Shiny.AppDeviceBridge.Jobs` | the app | `AddWebAppJob(name, configure)`: background jobs handled by the page or `background.js` |
5757
| `Shiny.AppDeviceBridge.Push` | the app | `AddPushBridge()`: register, unregister, token, tags, and optionally push payloads for the web app |
5858
| `Shiny.AppDeviceBridge.Wearables` | the app | `AddWearablesBridge()`: the companion Apple Watch or Wear OS app, through Shiny.Wearables — status, live messages the page or `background.js` answers, shared context, queued transfers and files through the file roots (iOS and Android; `501` elsewhere) |
59-
| `Shiny.AppDeviceBridge.Maps` | the app | `AddMapsBridge()`: vector map tiles online or from regions the user downloads (verified against a signed catalog), live traffic from a pluggable provider (TomTom built in), and turn-by-turn directions from an online Valhalla router (all platforms) |
59+
| `Shiny.AppDeviceBridge.Maps` | the app | `AddMapsBridge()`: vector map tiles online or from regions the user downloads (verified against a signed catalog), live traffic flow and incidents from pluggable providers (TomTom, HERE and Azure Maps built in), and turn-by-turn directions from an online Valhalla router (all platforms) |
6060
| `Shiny.AppDeviceBridge.Maps.Valhalla` | the app | `AddOnDeviceDirections()`: directions computed on the phone over a downloaded region's road network (Android and iOS; online elsewhere) |
6161
| `Shiny.AppDeviceBridge.Maps.Blazor` | the web app | `<BridgeMap>`: MapLibre GL JS bundled for offline use, with pins, lines, areas, circles, click-to-draw, routes and live traffic |
6262
| `Shiny.AppDeviceBridge.MapPacks` | a tool | `shiny-map-packs`: builds downloadable regions — the map cut from a PMTiles planet, the road network built with Valhalla |
@@ -644,7 +644,7 @@ WebView's session that's a `403`, so a caller outside the page can't probe which
644644
| Notifications | `GET notifications`, `POST notifications/access`, `POST notifications/send`, `GET notifications/pending`, `DELETE notifications[?scope=]`, `DELETE notifications/{id}`, `GET/PUT notifications/badge`, `GET/POST notifications/channels`, `DELETE notifications/channels/{id}` | `notification.entry`, `notification.received` |
645645
| HTTP transfers | `GET/POST/DELETE transfers`, `GET/DELETE transfers/{id}`, `POST transfers/{id}/pause`, `POST transfers/{id}/resume` | `transfer.progress`, `transfer.completed`, `transfer.failed`, `transfer.cancelled` |
646646
| Wearables | `GET wearables`, `POST wearables/messages`, `GET/PUT wearables/context`, `GET/POST wearables/transfers`, `DELETE wearables/transfers/{id}`, `POST wearables/files` | `wearables.status`, `wearables.message`, `wearables.context`, `wearables.transfer`, `wearables.file`, `wearables.completed` |
647-
| Maps | `GET maps`, `GET maps/regions`, `POST/DELETE maps/regions/{id}`, `DELETE maps/regions/{id}/directions`, `DELETE maps/regions/{id}/download`, `GET maps/tiles/{z}/{x}/{y}`, `GET maps/traffic/{z}/{x}/{y}`, `GET maps/glyphs/{fontstack}/{range}.pbf`, `GET maps/sprites/{name}` | `maps.download` |
647+
| Maps | `GET maps`, `GET maps/regions`, `POST/DELETE maps/regions/{id}`, `DELETE maps/regions/{id}/directions`, `DELETE maps/regions/{id}/download`, `GET maps/tiles/{z}/{x}/{y}`, `GET maps/traffic/{z}/{x}/{y}`, `GET maps/incidents/{z}/{x}/{y}`, `GET maps/glyphs/{fontstack}/{range}.pbf`, `GET maps/sprites/{name}` | `maps.download` |
648648
| Directions | `GET directions`, `POST directions/route` | |
649649
| App links | `GET/DELETE links/pending` | `app.link` |
650650
| Health | `GET health`, `POST health/access`, `GET/POST health/samples/{type}`, `POST/DELETE health/listeners/{type}` | `health.reading`, `health.stopped` |
@@ -980,15 +980,18 @@ downloaded a region. Every platform; on-device directions on Android and iOS wit
980980
- **Tiles:** `GET maps` gives the tile, glyph and sprite URL templates a renderer uses. A tile comes from an installed
981981
region, then tiles already seen online, then the online source (a PMTiles archive read by Range, or a tile service) —
982982
and `204` when none has it. Keys for the online source stay in the app.
983-
- **Traffic:** `o.Traffic = new TomTomTrafficProvider(key)`, or an `ITrafficProvider` of your own, adds a live layer.
984-
`GET maps` describes it under `traffic` (null without a provider), and `GET maps/traffic/{z}/{x}/{y}` serves its tiles,
985-
each kept for the provider's refresh interval. `204` when there's no data or no connection; `501` with no provider.
983+
- **Traffic:** `o.Traffic` takes a flow provider (`TomTomTrafficProvider`, `HereTrafficProvider`,
984+
`AzureMapsTrafficProvider`, or an `ITrafficProvider` of your own), and `o.TrafficIncidents` an incident provider
985+
(`TomTomIncidentProvider`, or an `ITrafficIncidentProvider`). `GET maps` describes them under `traffic` and
986+
`incidents` (null without a provider), and `GET maps/traffic/{z}/{x}/{y}` and `GET maps/incidents/{z}/{x}/{y}` serve
987+
their tiles, each kept for its layer's refresh interval. `204` when there's no data or no connection; `501` with no
988+
provider.
986989
- **Regions:** from a catalog the release server signs (`MapMapPacks()`). `POST maps/regions/{id}` with
987990
`{ "directions": true }` downloads the map and, optionally, the road network; `maps.download` reports progress. Every
988991
part is checked against its signed hash; downloads resume after an interruption.
989992
- **Directions:** `POST directions/route` with `{ stops, mode, units, language, source, avoid }`. `source: "Auto"` routes
990993
on the device inside a downloaded road network and online otherwise. `404 no_route`, `503 offline_unavailable`.
991-
- **The map in Blazor:** `<BridgeMap>` from `Shiny.AppDeviceBridge.Maps.Blazor` — pins, shapes, drawing, routes and live traffic (`ShowTraffic`).
994+
- **The map in Blazor:** `<BridgeMap>` from `Shiny.AppDeviceBridge.Maps.Blazor` — pins, shapes, drawing, routes and live traffic (`ShowTraffic`, `ShowIncidents`).
992995

993996
**Folders:**
994997
- **Picking:** `POST folders/pick` with `{ "root": "documents" }` shows the platform's folder picker. The folder

‎samples/Sample.App/Sample.App.csproj‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,6 @@
5252
<AssemblyMetadata Include="WebAppDevServer" Value="$(WebAppDevServer)" />
5353
</ItemGroup>
5454

55-
<!-- Live traffic on the Map page. Pass -p:TomTomApiKey=… or set TOMTOM_API_KEY in the environment you build from; the
56-
key never goes in the repository. Without one the Traffic button is disabled. -->
57-
<PropertyGroup>
58-
<TomTomApiKey Condition="'$(TomTomApiKey)' == ''">$(TOMTOM_API_KEY)</TomTomApiKey>
59-
</PropertyGroup>
60-
<ItemGroup Condition="'$(TomTomApiKey)' != ''">
61-
<AssemblyMetadata Include="TomTomApiKey" Value="$(TomTomApiKey)" />
62-
</ItemGroup>
63-
6455
<!--
6556
Sample.Blazor is published, zipped and embedded as the baseline, so the app runs offline on first launch.
6657
It is deliberately not a ProjectReference: referencing a Blazor WebAssembly app from a library drags its

‎samples/Sample.App/SampleConfiguration.cs‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -104,12 +104,11 @@ public static MauiAppBuilder ConfigureSample(this MauiAppBuilder builder, Action
104104
o.Catalog = new Uri($"http://{HostMachine}:5199/maps/catalog");
105105
o.CatalogPublicKey = ReadResource("Sample.dev-public.pem");
106106
o.Directions.OnlineRouteUrl = new Uri("https://valhalla1.openstreetmap.de/route");
107-
108-
// Live traffic, when the build was given a TomTom key (see Sample.App.csproj).
109-
if (Metadata("TomTomApiKey") is { Length: > 0 } tomTom)
110-
o.Traffic = new TomTomTrafficProvider(tomTom);
111107
})
112108

109+
// Traffic providers and their keys, picked on the Map page while the app runs; see the bridge.
110+
.AddBridge<TrafficProvidersBridge>()
111+
113112
// Routes on the phone inside a region whose road network was downloaded. Android and iOS; elsewhere
114113
// this registers nothing and directions stay online.
115114
.AddOnDeviceDirections()
@@ -152,14 +151,12 @@ public static MauiAppBuilder ConfigureSample(this MauiAppBuilder builder, Action
152151
.AllowWebPermissions(WebAppWebPermissions.Camera | WebAppWebPermissions.Microphone | WebAppWebPermissions.Geolocation);
153152
}
154153

155-
static string? Metadata(string key) => typeof(App).Assembly
156-
.GetCustomAttributes<AssemblyMetadataAttribute>()
157-
.FirstOrDefault(x => x.Key == key)?.Value;
158-
159154
#if DEBUG
160155
static Uri? DevServer()
161156
{
162-
var configured = Metadata("WebAppDevServer");
157+
var configured = typeof(App).Assembly
158+
.GetCustomAttributes<AssemblyMetadataAttribute>()
159+
.FirstOrDefault(x => x.Key == "WebAppDevServer")?.Value;
163160

164161
if (String.Equals(configured, "off", StringComparison.OrdinalIgnoreCase))
165162
return null;
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
using System.Text.Json.Serialization;
2+
using Microsoft.Extensions.DependencyInjection;
3+
using Shiny.AppDeviceBridge;
4+
using Shiny.AppDeviceBridge.Maps;
5+
using Shiny.Extensions.Stores;
6+
using Shiny.Net.HttpServer;
7+
8+
namespace Sample;
9+
10+
/// <summary>
11+
/// <c>/_bridge/sample-traffic</c>: lets the Map page pick the traffic providers and enter their API keys while the sample runs,
12+
/// so each provider can be tried without a key in the repository or a rebuild.
13+
/// <code>
14+
/// GET /_bridge/sample-traffic { flow, incidents, keys: ["tomtom", …] } which keys are set, never the keys
15+
/// PUT /_bridge/sample-traffic/keys/{provider} { "key": "…" } tomtom, here, azure-maps
16+
/// DELETE /_bridge/sample-traffic/keys/{provider}
17+
/// PUT /_bridge/sample-traffic/selection { "flow": "here", "incidents": true } flow: none, tomtom, here, azure-maps
18+
/// </code>
19+
/// <para>
20+
/// Keys go into the device's secure store (Keychain, Android KeyStore, DPAPI; a plain file on Linux) and are write-only: the
21+
/// page can set or clear one, but no route returns it. The selection is applied to <see cref="MapsOptions"/> at once and kept
22+
/// for the next launch. A bridge like any other, so it is behind the bridge policy — this is a sample's convenience, not a
23+
/// pattern for shipping third-party keys to users.
24+
/// </para>
25+
/// </summary>
26+
sealed class TrafficProvidersBridge : IWebAppBridge
27+
{
28+
const string TomTom = "tomtom";
29+
const string Here = "here";
30+
const string AzureMaps = "azure-maps";
31+
const string None = "none";
32+
static readonly string[] Providers = [TomTom, Here, AzureMaps];
33+
34+
readonly MapsOptions maps;
35+
readonly Lazy<IKeyValueStore> secure;
36+
readonly Lazy<IKeyValueStore> local;
37+
readonly Lock gate = new();
38+
39+
public TrafficProvidersBridge(MapsOptions maps, IServiceProvider services)
40+
{
41+
this.maps = maps;
42+
this.secure = new(() => services.GetKeyedService<IKeyValueStore>(StoreKeys.Secure) ?? Stores.Secure);
43+
this.local = new(() => services.GetKeyedService<IKeyValueStore>(StoreKeys.Default) ?? Stores.Default);
44+
45+
// What the user picked last time, so traffic is back on at the next launch without visiting the page.
46+
this.Apply();
47+
}
48+
49+
public string Name => "sample-traffic";
50+
51+
public bool IsSupported => true;
52+
53+
public void Map(WebAppBridgeRoutes routes) => routes
54+
.MapGet("", this.GetAsync)
55+
.MapPut("/keys/{provider}", this.SetKeyAsync)
56+
.MapDelete("/keys/{provider}", this.ClearKeyAsync)
57+
.MapPut("/selection", this.SelectAsync);
58+
59+
ValueTask GetAsync(HttpContext context)
60+
=> WebAppBridgeResults.Json(context, this.Settings(), TrafficProvidersJsonContext.Default.TrafficProviderSettings);
61+
62+
async ValueTask SetKeyAsync(HttpContext context)
63+
{
64+
if (Provider(context) is not { } provider)
65+
{
66+
await WebAppBridgeResults.NotFound(context, "No such traffic provider.");
67+
return;
68+
}
69+
70+
var body = await WebAppBridgeResults.ReadBodyAsync(context, TrafficProvidersJsonContext.Default.TrafficProviderKey);
71+
if (String.IsNullOrWhiteSpace(body?.Key))
72+
{
73+
await WebAppBridgeResults.BadRequest(context, "A key is required.");
74+
return;
75+
}
76+
77+
lock (this.gate)
78+
{
79+
this.secure.Value.Set(KeyName(provider), body.Key.Trim());
80+
this.Apply();
81+
}
82+
83+
await this.GetAsync(context);
84+
}
85+
86+
async ValueTask ClearKeyAsync(HttpContext context)
87+
{
88+
if (Provider(context) is not { } provider)
89+
{
90+
await WebAppBridgeResults.NotFound(context, "No such traffic provider.");
91+
return;
92+
}
93+
94+
lock (this.gate)
95+
{
96+
this.secure.Value.Remove(KeyName(provider));
97+
this.Apply();
98+
}
99+
100+
await this.GetAsync(context);
101+
}
102+
103+
async ValueTask SelectAsync(HttpContext context)
104+
{
105+
var body = await WebAppBridgeResults.ReadBodyAsync(context, TrafficProvidersJsonContext.Default.TrafficProviderSelection);
106+
var flow = body?.Flow ?? None;
107+
108+
if (flow != None && !Providers.Contains(flow))
109+
{
110+
await WebAppBridgeResults.BadRequest(context, $"'{flow}' is not a traffic provider.");
111+
return;
112+
}
113+
114+
lock (this.gate)
115+
{
116+
this.local.Value.Set("sample.traffic.flow", flow);
117+
this.local.Value.Set("sample.traffic.incidents", body?.Incidents == true ? "true" : "false");
118+
this.Apply();
119+
}
120+
121+
await this.GetAsync(context);
122+
}
123+
124+
/// <summary>Builds the providers from the stored selection and keys. A selection whose key is missing draws nothing.</summary>
125+
void Apply()
126+
{
127+
var flow = this.Flow;
128+
var key = flow == None ? null : this.Key(flow);
129+
130+
this.maps.Traffic = key is null ? null : flow switch
131+
{
132+
TomTom => new TomTomTrafficProvider(key),
133+
Here => new HereTrafficProvider(key),
134+
AzureMaps => new AzureMapsTrafficProvider(key),
135+
_ => null
136+
};
137+
138+
this.maps.TrafficIncidents = this.Incidents && this.Key(TomTom) is { } tomTom ? new TomTomIncidentProvider(tomTom) : null;
139+
}
140+
141+
TrafficProviderSettings Settings() => new(
142+
this.Flow,
143+
this.Incidents,
144+
[.. Providers.Where(x => this.Key(x) is not null)],
145+
this.maps.Traffic is not null,
146+
this.maps.TrafficIncidents is not null
147+
);
148+
149+
string Flow => this.local.Value.Get<string>("sample.traffic.flow") is { } flow && (flow == None || Providers.Contains(flow)) ? flow : None;
150+
151+
bool Incidents => this.local.Value.Get<string>("sample.traffic.incidents") == "true";
152+
153+
string? Key(string provider) => this.secure.Value.Get<string>(KeyName(provider)) is { Length: > 0 } key ? key : null;
154+
155+
static string KeyName(string provider) => $"sample.traffic.key.{provider}";
156+
157+
static string? Provider(HttpContext context)
158+
=> context.Request.RouteValues["provider"] is { } provider && Providers.Contains(provider) ? provider : null;
159+
}
160+
161+
/// <param name="Flow"><c>none</c>, <c>tomtom</c>, <c>here</c> or <c>azure-maps</c>.</param>
162+
/// <param name="Keys">The providers whose key is set. The keys themselves never leave the device's secure store.</param>
163+
/// <param name="FlowActive">Whether a flow provider is running: the selection has its key.</param>
164+
/// <param name="IncidentsActive">Whether TomTom incidents are running: selected, with the TomTom key set.</param>
165+
sealed record TrafficProviderSettings(string Flow, bool Incidents, IReadOnlyList<string> Keys, bool FlowActive, bool IncidentsActive);
166+
167+
sealed record TrafficProviderKey(string? Key);
168+
169+
sealed record TrafficProviderSelection(string? Flow, bool Incidents);
170+
171+
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true)]
172+
[JsonSerializable(typeof(TrafficProviderSettings))]
173+
[JsonSerializable(typeof(TrafficProviderKey))]
174+
[JsonSerializable(typeof(TrafficProviderSelection))]
175+
partial class TrafficProvidersJsonContext : JsonSerializerContext;

0 commit comments

Comments
 (0)