Skip to content

A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.

Merge upstream/main into pr/google-street-view

Said Turksever76db4114ffc2
diff --cc CHANGELOG.md
index 7b1cb05cc,68ab1c52d..54380bdc2
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -63,13 -95,17 +95,26 @@@
## [Unreleased]
+- Street Level: Google Street View is the second provider. On the Google 3D
+ map (Google's terms keep it off other maps), light its chip (off by
+ default: every panorama is billed to the Google Maps key, which needs the
+ Maps JavaScript API) and click a street, or press OPEN STREET VIEW, to
+ open Google's own panorama in
+ the panel, with its arrows, the address and month in the caption, a link
- to Google Maps and FOLLOW. Share links carry it as `g`.
++ to Google Maps and FOLLOW. Share links carry it in the provider switches
++ (`r.google-1`).
++
+ - Add an experimental ChatGPT/Codex OAuth option for cloud voice in Provider
+ Settings. API-key voice remains the default. Local sign-in can start from
+ the auth button and reports completion, failure, timeout, or expired
+ credentials. OAuth credentials stay on the server; local routes require
+ loopback access and same-site requests. OAuth sessions retain usage data
+ and show unknown cost; caption transcriptions are counted rather than
+ priced into the API-key cap. The auth button keeps keyboard focus after a
+ mode change, and pending sign-in does not discard text in the key fields.
+ Thanks to [Shayan Khan](https://github.com/devv-shayan) for #621 and
+ [TheSmokeDev](https://github.com/TheSmokeDev) for the credential handling
+ from #653.
- Stdio servers from one install share a panel key so a page read from one
process can make requests through another. Concurrent malformed-key repairs
diff --cc README.md
index 5f7150780,5d97dfb2f..420953f1f
--- a/README.md
+++ b/README.md
@@@ -334,13 -340,13 +340,13 @@@ _The Space Missions layer replaying a F
## πŸ“· Street Level
-> Street-level photos from any provider in one panel. This build ships **Mapillary**, which needs a free client token.
+> Street-level photos from any provider in one panel. This build ships **Mapillary** (a free client token) and **Google Street View** (your Google Maps key).
-**Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP β†’ Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it the panel reads **KEY REQUIRED**.
+**Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP β†’ Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it the panel reads **KEY REQUIRED**. **Google Street View** uses `GOOGLE_MAPS_API_KEY` with the **Maps JavaScript API** enabled for it in Google Cloud; its chip starts off, since every panorama is billed to the key.
-**Use.** Turn on **Street Level** under DATA LAYERS β†’ Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green). The **IMAGERY** (ALL / 360Β° / FLAT) and **SINCE** filters apply to every provider. Click a coverage line for its image cones and a cone to open the photo. Above the photo: **EXPAND**, **FIT / FILL**, and **FOLLOW** (the globe camera follows the photo's view; Google 3D map only). The caption links to the image on the provider's site, and the globe credits "Β© Mapillary contributors, CC BY-SA 4.0" while Mapillary is on.
+**Use.** Turn on **Street Level** under DATA LAYERS β†’ Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green). The **IMAGERY** (ALL / 360Β° / FLAT) and **SINCE** filters apply to every provider. Click a coverage line for its image cones and a cone to open the photo. On the **Google 3D** map (Google's terms keep Street View off other maps, where it does not appear), light **STREET VIEW** and click a street from below 3 km, or press **OPEN STREET VIEW** for the view centre, to open Google's panorama there; step along its arrows. Above the photo: **EXPAND**, **FIT / FILL** (Mapillary), and **FOLLOW** (the globe camera follows the photo's view; Google 3D map only). The caption links to the image on the provider's site, and the globe credits each provider that is on ("Β© Mapillary contributors, CC BY-SA 4.0", "Street View imagery Β© Google").
- Drag the panel header to float the panel, and resize it from any edge. Double-click the header or collapse it to put it back in the rail. Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.g.1` Street View on, `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`.
-Drag the panel header to float the panel, and resize it from any edge. Double-click the header or collapse it to put it back in the rail. Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`.
++Drag the panel header to float the panel, and resize it from any edge. Double-click the header or collapse it to put it back in the rail. Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.r.google-1` Street View on, `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`.
## πŸŽ–οΈ Field Missions
@@@ -428,8 -434,8 +434,8 @@@ Seven keys. Five have a free tier, and
| | Key | Why | Get it |
| --- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 🟑 | **Cesium ion** | πŸ—ΊοΈ Google Photorealistic 3D, world terrain, and additional ion-hosted imagery stacks. The free Community plan is for eligible individual, personal/non-commercial use and has quotas | [cesium.com/ion](https://cesium.com/ion) β€” use a public `assets:read` token and check current [pricing/eligibility](https://cesium.com/platform/cesium-ion/pricing/) |
-| πŸ”΄ | **Google Maps** | Direct Google Photorealistic 3D + Google place search ([Map Tiles API](https://developers.google.com/maps/documentation/tile)) | [Google Cloud Console](https://console.cloud.google.com/) β€” URL-restrict it |
+| πŸ”΄ | **Google Maps** | Direct Google Photorealistic 3D, Google place search and Street View ([Map Tiles API](https://developers.google.com/maps/documentation/tile); Street View also needs the Maps JavaScript API) | [Google Cloud Console](https://console.cloud.google.com/) β€” URL-restrict it |
- | πŸ”΄ | **OpenAI** | πŸŽ™οΈ The voice experience + AI HUD summary. The mini model works; the standard model is noticeably smarter. Want Gemini or another provider behind the mic? PRs welcome | [platform.openai.com](https://platform.openai.com) β€” metered, see costs below |
+ | πŸ”΄ | **OpenAI** | πŸŽ™οΈ Voice + AI HUD summary through an API key. Provider Settings also offers **USE CHATGPT OAUTH** for cloud voice without removing the API-key option | [platform.openai.com](https://platform.openai.com) β€” API-key usage is metered, see costs below |
| 🟑 | **AISStream** | 🚒 Live global ships | [aisstream.io](https://aisstream.io) β€” free signup |
| 🟑 | **NASA FIRMS** | πŸ”₯ Live active fires | [firms.modaps.eosdis.nasa.gov](https://firms.modaps.eosdis.nasa.gov/api/map_key/) β€” free |
| 🟑 | **TomTom** | 🚦 Live flow speeds and congestion colors for the simulated traffic layer | [my.tomtom.com](https://my.tomtom.com/keys) β€” free tier available |
diff --cc SECURITY.md
index 15ad0bc16,53437a83c..664a3e6d5
--- a/SECURITY.md
+++ b/SECURITY.md
@@@ -73,9 -74,8 +74,11 @@@ The data proxies under `server/provider
- **Coalesced OAuth refresh** and cached successful responses only (OpenSky).
- **Redacted debug logging.** The voice debug log (`.gev-logs/`, gitignored) strips API keys, bearer tokens, client secrets, and image data URLs before writing.
- **Cross-site gate on cost/log endpoints.** The cost-bearing (`/api/realtime/token`, `/api/openai/hud-summary`, `/api/google/nearby-places`, `/api/google/text-search`), quota-bearing (`/api/mapillary/*`, with a per-IP limit on tiles) and log (`/api/realtime/debug-log`) endpoints refuse cross-site browser requests: a foreign or opaque `Origin`, a `Sec-Fetch-Site` other than `same-origin`/`none` (this is what blocks an `<img>`/navigation that carries no `Origin`), or any reverse-proxy/CDN forwarding header returns `403`. Non-browser loopback tools (the repo QA harnesses POST the token endpoint with no `Origin`) and the explicit `HOST=0.0.0.0` LAN opt-in keep working β€” the gate deliberately does not require a loopback remote address; that stricter requirement belongs only to the credential panel (`admitKeySetupRequest`). The Host check (`allowedHosts`, applied by `hostCheckPlugin` ahead of every route, since Vite's own check runs only after plugin middleware) rejects a rebinding `Host` before any handler runs, in every mode, and the gate is defense in depth behind it: the LAN opt-in keeps that check and accepts only IP addresses, `localhost` and names listed in `GEV_ALLOWED_HOSTS`. **Limit:** a name you list there is trusted like the app's own address, so list only names you control.
+- **Full Content-Security-Policy.** The dev and preview servers send a real CSP (`script-src 'self' 'unsafe-eval' blob:` plus the YouTube, Facebook and X scripts the Nepal event's embedded media loads and the Maps JavaScript API that Street View runs on, with a matching `frame-src` for their players and posts: no inline script and no other script origin; `blob:` covers the object URLs Cesium's bundled workers bootstrap through in the built app), alongside the existing `X-Frame-Options: DENY` and `frame-ancestors 'none'`. `'unsafe-eval'` stays because Knockout, bundled inside Cesium's widgets package, resolves the global object with `eval` at load time and the globe does not initialize without it; styles permit `'unsafe-inline'` and Google Fonts because Vite's dev client injects `<style>` elements.
+
+Allowing `maps.googleapis.com` in `script-src` also trusts its JSONP endpoints, which can bypass the script allowlist if an HTML-injection bug exists; this is an accepted limitation of loading the Maps JavaScript API, alongside the existing `'unsafe-eval'` allowance.
+ - **Full Content-Security-Policy.** The dev and preview servers send a real CSP (`script-src 'self' 'unsafe-eval' blob:` plus the YouTube, Facebook and X scripts the Nepal event's embedded media loads, with a matching `frame-src` for their players and posts: no inline script and no other script origin; `blob:` covers the object URLs Cesium's bundled workers bootstrap through in the built app), alongside the existing `X-Frame-Options: DENY` and `frame-ancestors 'none'`. `'unsafe-eval'` stays because Knockout, bundled inside Cesium's widgets package, resolves the global object with `eval` at load time and the globe does not initialize without it; styles permit `'unsafe-inline'` and Google Fonts because Vite's dev client injects `<style>` elements.
+ - **ChatGPT OAuth voice reuses the local Codex sign-in.** `/api/realtime/oauth-status`, `/api/realtime/oauth-login` and `/api/realtime/token?auth=oauth` answer only loopback connections, behind the same cross-site gate as the token endpoint; the login route also refuses a foreign `Origin`. None of them returns the access token. The login route runs `codex login` (or the executable named by `CODEX_BIN`) with an allowlisted environment that leaves out GEV's provider keys, keeps one attempt pending at a time and cancels it after two minutes or when the server stops. **Limits:** any program on this machine that can reach the server can mint Realtime sessions on the signed-in ChatGPT account, as it can with the API key; a local reverse proxy that hides the client's address defeats the loopback check; and OpenAI has not documented this use of Codex credentials for Realtime, so it may stop working or fall outside the account's terms.
## Network exposure β€” the operator threat model
diff --cc docs/CURRENT-STATE.md
index 4aa856d3d,274294b5d..027729f3e
--- a/docs/CURRENT-STATE.md
+++ b/docs/CURRENT-STATE.md
@@@ -3033,9 -3078,8 +3078,9 @@@ shared 360Β°/flat and captured-since fi
meaning), one viewer host and one on-globe credit per active provider. Each
provider draws in one colour (`PROVIDER_COLORS` in
`src/layers/streetLevel/policy.js`); 360Β° cones are rings and the selected
- sequence is GEV cyan. Share options: `m` (Mapillary), `g` (Google Street
- View), `p` (`a`/`p`/`f` panoramas), `s` (since, days). Mapillary and Google
-sequence is GEV cyan. Share options: `m` (Mapillary), `p` (`a`/`p`/`f`
-panoramas), `s` (since, days). Only Mapillary is registered. Without
++sequence is GEV cyan. Share options: `m` (Mapillary), `r` (the other providers' switches by id,
++e.g. `google-1` for Street View), `p` (`a`/`p`/`f` panoramas), `s` (since, days). Mapillary and Google
+Street View are registered. Without
`MAPILLARY_CLIENT_TOKEN` the panel reads KEY REQUIRED and the controls are
disabled. With it, coverage draws as z0–5 overview points from orbit and z11–14
sequence lines below 60 km; the proxy strips the unused `image` layer from z14
@@@ -3088,38 -3125,8 +3133,38 @@@ manages each provider's credit and fan
add a provider: implement the definition, register it in
`src/app/layers/streetLevel.js`, add its boolean option to the `street-level`
group in `src/data/layerState.js` and its modules to
-`scripts/package-boundaries.json`. Once a keyless provider registers, the
-layer's `requiresKeyId` becomes null and the key gate moves to the chips.
+`scripts/package-boundaries.json`. With providers on different keys the
+layer's `requiresKeyId` is null and each chip reports its own key.
+
+Google Street View (`providers/google/`) runs on the Maps JavaScript API with
+the browser `GOOGLE_MAPS_API_KEY`, which needs that API enabled; it is loaded
+on first use (`mapsLoader.js`, CSP `script-src https://maps.googleapis.com`).
- Its chip starts off (`defaultOn: false`, option default `g` off) because every
++Its chip starts off (`defaultOn: false`; a link without its switch keeps it off) because every
+panorama load is billed to the key. Google's terms forbid Street View beside
+non-Google maps, so the provider declares `requiresMapStack: 'photoreal'`:
+off Google 3D it does not appear at all (no chip, legend swatch, globe
+credit, layer source or button, and Google's script is not loaded), lookups
+and opens skip it, and leaving Google 3D closes its panorama; the share
+option keeps the user's choice for when Google 3D returns. Google offers no coverage layer
+for other maps, so it draws none: with it on, a click on the map itself
+(`scenePick.isSurfacePick`: nothing picked or Google 3D tile content, so a
+Mapillary line under the pointer wins; no tool holding the pointer; camera
+below 3 km) opens its nearest Google-collected outdoor panorama within 50 m
+and leaves the camera where it is (`groundClick.js`). Higher up the hint
+says to zoom in. **OPEN STREET VIEW** beside that hint (`#sl-nearest-btn`)
+does the same at the view centre, so Street View needs no pointer; it is
+disabled until the camera is at street zoom. The viewer is Google's `StreetViewPanorama` in its own
+element in the viewer host, without Google's fullscreen, close and address
+controls (the address goes in the caption); a pose goes out at once and
+again when the panorama's month, photographer and address arrive (one
+successful lookup per panorama per session, seeded by the nearest lookup;
+failed details lookups wait five seconds before a view event can retry). A key
+Google refuses (`gm_authFailure`: the API not enabled, a referrer it does
+not allow, billing off) reads KEY REJECTED and fails a pending open at
+once; a lookup or open Google never answers fails after 10 or 20 s. In CI
+(no Google key, no Google 3D) the gate checks that nothing of Street View
+shows off Google 3D, even switched on by a share link; the click and button
+step skips as `no Google key`.
Street Level has two browser gates. `npm run qa:street-level -- --url <server>`
runs against real Mapillary and needs `MAPILLARY_CLIENT_TOKEN`. `npm run
diff --cc scripts/qa-street-level.mjs
index 58fc28a51,f8d50f85f..92428928d
--- a/scripts/qa-street-level.mjs
+++ b/scripts/qa-street-level.mjs
@@@ -628,15 -619,20 +628,21 @@@ async function main()
}
await page.setViewport(VIEWPORTS[0]);
const expandStrip = async (target = page) => {
- await target.click(
+ await clickPanelControl(
+ target,
'.panel-collapse-btn[data-collapse-target="street-level-panel"]',
);
- await settle(
- target,
- () =>
- getComputedStyle(document.getElementById('sl-body')).display ===
- 'flex',
+ assert.ok(
+ await settle(
+ target,
+ () =>
+ !document
+ .getElementById('street-level-panel')
+ .classList.contains('collapsed') &&
+ getComputedStyle(document.getElementById('sl-body')).display ===
+ 'flex',
+ ),
+ 'Street Level panel did not expand before the timeout',
);
};
await expandStrip();
@@@ -1741,275 -1721,6 +1747,276 @@@
);
},
);
+ const googleChip = '#sl-provider-chips [data-chip-id="google"]';
+ const googleKey = await page.evaluate(() =>
+ Boolean(window.__GOOGLE_MAPS_API_KEY__),
+ );
+ await step(
+ 'Street View starts off, appears only on the Google 3D map, and travels in the share link',
+ async () => {
+ const module = () =>
+ window.__godsEyeView.dataManager.layers.get('street-level').module;
+ assert.equal(
+ await page.evaluate(`(${module})().getParams().google`),
+ false,
+ 'off until lit: panoramas are billed',
+ );
+ const setStreetView = (on) =>
+ page.evaluate(
+ (value) =>
+ window.__godsEyeView.dataManager.setLayerParams(
+ 'street-level',
+ { google: value },
+ { origin: 'user' },
+ ),
+ on,
+ );
+ const shown = () =>
+ page.evaluate(() => ({
+ chip: Boolean(
+ document.querySelector(
+ '#sl-provider-chips [data-chip-id="google"]',
+ ),
+ ),
+ legend: [...document.querySelectorAll('#sl-legend li')].some(
+ (item) => /Street View/.test(item.textContent),
+ ),
+ credit: document.body.innerHTML.includes('Street View imagery'),
+ button: !document.getElementById('sl-nearest-btn').hidden,
+ }));
+ const original = await stacks.active();
+ // Off Google 3D (CI's only map) nothing of Street View shows, even
+ // switched on: Google's terms keep it off other maps.
+ if (original === 'photoreal') await stacks.set('esri-imagery');
+ await setStreetView(true);
+ await uiUntil((u) => u.providers.every((p) => p.id !== 'google'));
+ assert.ok(
+ await settle(
+ page,
+ () => !document.body.innerHTML.includes('Street View imagery'),
+ ),
+ 'no Google credit on another map',
+ );
+ assert.deepEqual(await shown(), {
+ chip: false,
+ legend: false,
+ credit: false,
+ button: false,
+ });
- const option = `${STREET_LEVEL_TOKEN}.g.1`;
++ // Street View rides the shared provider-switch field (r).
++ const option = `${STREET_LEVEL_TOKEN}.r.google-1`;
+ assert.ok(
+ await settle(
+ page,
+ (token) =>
+ (new URLSearchParams(location.hash.slice(1)).get('lo') || '')
+ .split('_')
+ .includes(token),
+ option,
+ ),
+ `the share link keeps the choice: ${option}`,
+ );
+ if (await stacks.photoreal()) {
+ await stacks.set('photoreal');
+ await uiUntil((u) => u.providers.some((p) => p.id === 'google'));
+ const chipNow = await page.$eval(googleChip, (node) => ({
+ className: node.className,
+ title: node.title,
+ color: node.style.getPropertyValue('--chip-color'),
+ }));
+ assert.equal(chipNow.color, '#4285f4');
+ if (googleKey) assert.match(chipNow.className, /chip-active/);
+ else {
+ assert.match(chipNow.className, /chip-error/);
+ assert.match(chipNow.title, /GOOGLE_MAPS_API_KEY/);
+ }
+ assert.ok(
+ await settle(page, () =>
+ document.body.innerHTML.includes('Street View imagery'),
+ ),
+ 'the Google credit shows on Google 3D',
+ );
+ }
+ // Back off, as the next steps expect.
+ await setStreetView(false);
+ await stacks.set(original);
+ await uiUntil(
+ (u) => u.providers.find((p) => p.id === 'google')?.on !== true,
+ );
+ },
+ );
+ await step(
+ 'on Google 3D a click on a street opens Google Street View where it is, captioned and linked, and its view drives the pose',
+ async ({ skip }) => {
+ if (!googleKey) return skip('no Google key');
+ // Google's terms: Street View only beside Google's own map.
+ if (!(await stacks.photoreal())) return skip('no Google 3D');
+ const original = await stacks.active();
+ const closePhoto = () =>
+ page.evaluate(() =>
+ window.__godsEyeView.dataManager.layers
+ .get('street-level')
+ .module.closeViewer(),
+ );
+ const setOn = async (selector, id, on) => {
+ const now = (await ui()).providers.find((p) => p.id === id)?.on;
+ if (now === on) return;
+ await clickPanelControl(page, selector);
+ assert.ok(
+ await uiUntil(
+ (u, want) =>
+ u.providers.find((p) => p.id === want.id)?.on === want.on,
+ { id, on },
+ ),
+ `the ${id} chip switched ${on ? 'on' : 'off'}`,
+ );
+ };
+ await closePhoto();
+ await stacks.set('photoreal');
+ // A Mapillary line under the pointer wins the click: aim at bare
+ // ground with only Street View on (lit first: the last lit chip
+ // would switch the layer off).
+ await setOn(googleChip, 'google', true);
+ await setOn(chip, 'mapillary', false);
+ try {
+ const street = STREET_VIEW_STREET;
+ await page.evaluate((at) => {
+ const v = window.__godsEyeView.viewer;
+ v.camera.cancelFlight?.();
+ const C = v.camera.positionCartographic.constructor;
+ v.camera.setView({
+ destination: v.scene.globe.ellipsoid.cartographicToCartesian(
+ C.fromDegrees(at.lon, at.lat, 300),
+ ),
+ orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
+ });
+ }, street);
+ // At street zoom the hint invites the click.
+ assert.ok(
+ await uiUntil(
+ (u) =>
+ u.providers.find((p) => p.id === 'google')?.hint ===
+ 'click a street to open Street View',
+ ),
+ 'the click hint shows at street zoom',
+ );
+ const camera = () =>
+ page.evaluate(() => {
+ const c = window.__godsEyeView.viewer.camera.positionWC;
+ return [c.x, c.y, c.z];
+ });
+ const at = await page.evaluate((point) => {
+ const v = window.__godsEyeView.viewer;
+ const C = v.camera.positionCartographic.constructor;
+ const ground = v.scene.globe.ellipsoid.cartographicToCartesian(
+ C.fromDegrees(point.lon, point.lat, 0),
+ );
+ const canvas = v.scene.cartesianToCanvasCoordinates(ground);
+ const box = v.scene.canvas.getBoundingClientRect();
+ return (
+ canvas && { x: box.left + canvas.x, y: box.top + canvas.y }
+ );
+ }, street);
+ assert.ok(at, 'the street is on screen');
+ const before = await camera();
+ await page.mouse.click(at.x, at.y);
+ await uiUntil(
+ (u) =>
+ Boolean(u.street.error) ||
+ (u.street.providerId === 'google' &&
+ Boolean(u.street.imageId) &&
+ !u.street.loading),
+ null,
+ { timeout: 30_000 },
+ );
+ const opened = (await ui()).street;
+ if (/refused GOOGLE_MAPS_API_KEY/.test(opened.error || ''))
+ return skip('Google key refused');
+ if (/did not answer/.test(opened.error || ''))
+ return skip('Google did not answer');
+ assert.equal(opened.error, null);
+ assert.equal(opened.providerId, 'google');
+ const after = await camera();
+ assert.ok(
+ Math.hypot(...after.map((v, i) => v - before[i])) < 1,
+ 'the camera stays where the user clicked',
+ );
+ const shown = await page.evaluate(() => ({
+ by: document.getElementById('sl-image-by').textContent,
+ when: document.getElementById('sl-image-when').textContent,
+ label: document.getElementById('sl-image-link').textContent,
+ href: document.getElementById('sl-image-link').href,
+ fitFillHidden:
+ document.querySelector('[data-sl-render]').parentElement.hidden,
+ panorama: Boolean(
+ document.querySelector('#sl-viewer .sl-google-panorama'),
+ ),
+ mapillaryLeft: Boolean(
+ document.querySelector('#sl-viewer .mapillary-dom'),
+ ),
+ }));
+ assert.match(shown.by, /Image by /);
+ assert.match(shown.when, /\d{4}-\d{2}$/, 'dated by month');
+ assert.equal(shown.label, 'STREET VIEW β†—');
+ assert.match(shown.href, /map_action=pano&pano=/);
+ assert.equal(shown.fitFillHidden, true, 'no FIT/FILL for Google');
+ assert.equal(shown.panorama, true);
+ assert.equal(shown.mapillaryLeft, false, 'no viewer left under it');
+ // A real drag turns Google's view, and the pose follows it.
+ const box = await page.$eval(
+ '#sl-viewer .sl-google-panorama',
+ (node) => {
+ const r = node.getBoundingClientRect();
+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
+ },
+ );
+ await page.mouse.move(box.x, box.y);
+ await page.mouse.down();
+ await page.mouse.move(box.x - 120, box.y, { steps: 12 });
+ await page.mouse.up();
+ assert.ok(
+ await uiUntil(
+ (u, start) =>
+ Number.isFinite(u.street.bearing) &&
+ Math.abs(u.street.bearing - start) > 5,
+ opened.bearing ?? 0,
+ { timeout: 10_000 },
+ ),
+ 'the pose bearing follows the drag',
+ );
+ // The keyboard path: OPEN STREET VIEW at the view centre.
+ await closePhoto();
+ await uiUntil((u) => u.street.open === false);
+ await clickPanelControl(page, '#sl-nearest-btn');
+ assert.ok(
+ await uiUntil(
+ (u) =>
+ u.street.providerId === 'google' &&
+ Boolean(u.street.imageId) &&
+ !u.street.loading,
+ null,
+ { timeout: 30_000 },
+ ),
+ 'OPEN STREET VIEW opens the panorama at the view centre',
+ );
+ // Leaving Google 3D closes the panorama (Google's terms).
+ await stacks.set('esri-imagery');
+ assert.ok(
+ await uiUntil((u) => u.street.open === false),
+ 'the panorama closes off Google 3D',
+ );
+ } finally {
+ await closePhoto();
+ // Off Google 3D the Street View chip is hidden: return to it
+ // before switching the chip, or the cleanup throws and hides
+ // the step's own result.
+ await stacks.set('photoreal');
+ await setOn(chip, 'mapillary', true);
+ await setOn(googleChip, 'google', false);
+ await stacks.set(original);
+ }
+ },
+ );
await step(
'a reload with the layer on keeps a collapsed panel collapsed, and the share link carries its ui token',
async () => {
diff --cc src/app/layers/streetLevel.js
index bf7e42354,18a3e7a3b..05dd50b4b
--- a/src/app/layers/streetLevel.js
+++ b/src/app/layers/streetLevel.js
@@@ -4,19 -3,22 +4,38 @@@ import { createGoogleProvider } from '.
import * as sprites from '../../data/spriteOrder.js';
import * as picking from '../../data/pickRegistry.js';
import * as input from '../../data/inputOwnership.js';
+import * as scenePick from '../../data/scenePick.js';
import * as render from '../../renderGovernor.js';
+/** The browser Maps key the scene was started with (src/app/scene.js). */
+const googleApiKey = () => globalThis.window?.__GOOGLE_MAPS_API_KEY__ || null;
+
- /** A new provider registers here; its chip, credit and share bit follow. */
- export function createApplicationStreetLevel({ surface, sources }) {
++/**
++ * The default providers, once the application supplies its Street Level
++ * source: Mapillary, and Google Street View, which needs only the browser
++ * Maps key (off until lit). Without that source there are none, and the
++ * layer reads as not configured.
++ */
++function defaultProviders(sources) {
++ if (sources.mapillary == null) return [];
++ return [
++ createMapillaryProvider({ source: sources.mapillary }),
++ createGoogleProvider({ getApiKey: googleApiKey }),
++ ];
++}
++
+ /**
- * Inject providers, or use Mapillary only when its source is supplied.
- * An explicit provider list replaces the default; unused sources.mapillary is
- * neither constructed nor validated, including when the list is empty.
++ * Inject providers, or use the defaults. An explicit provider list replaces
++ * them; an unused sources.mapillary is neither constructed nor validated,
++ * including when the list is empty.
+ */
+ export function createApplicationStreetLevel({
+ surface,
+ sources = {},
- providers = sources.mapillary == null
- ? []
- : [createMapillaryProvider({ source: sources.mapillary })],
++ providers = defaultProviders(sources),
+ }) {
return createStreetLevelLayer({
- providers: [
- createMapillaryProvider({ source: sources.mapillary }),
- createGoogleProvider({ getApiKey: googleApiKey }),
- ],
+ providers,
services: {
sprites,
picking,
diff --cc src/app/layers/streetLevel.test.mjs
index 7a2a95962,99f356599..8087a2c38
--- a/src/app/layers/streetLevel.test.mjs
+++ b/src/app/layers/streetLevel.test.mjs
@@@ -1,24 -1,29 +1,51 @@@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createApplicationStreetLevel } from './streetLevel.js';
- import { createDefaultLayerState } from '../../data/layerState.js';
+ import { fakeStreetLevelProvider } from '../../testSupport/streetLevelFakes.mjs';
- test('each provider starts as its share-link option does, so a fresh page and a restored one agree', () => {
+ test('explicit providers replace the default source and an empty list removes it', () => {
+ const sources = { mapillary: {} };
+ const provider = fakeStreetLevelProvider({
+ id: 'example',
+ pickPrefix: 'example:',
+ });
const layer = createApplicationStreetLevel({
- surface: null,
- sources: {
- mapillary: {
- getStatus() {},
- getTile() {},
- getSequenceImages() {},
- nearestImages() {},
- },
- },
+ sources,
+ providers: [provider],
});
- const options = createDefaultLayerState().options['street-level'];
- // Every registered provider, listed on this map or not.
- const started = layer.getParams();
- for (const id of layer.providerIds)
- assert.equal(started[id], options[id], id);
- assert.equal(options.google, false, 'Street View is billed: off');
+ assert.deepEqual(layer.providerIds, ['example']);
+ assert.deepEqual(
+ createApplicationStreetLevel({ sources, providers: [] }).providerIds,
+ [],
+ );
+ assert.throws(
+ () => createApplicationStreetLevel({ sources }),
+ /Mapillary source/,
+ );
+ assert.throws(
+ () => createApplicationStreetLevel({ providers: null }),
+ /array/,
+ );
+ });
++
++test('the defaults are Mapillary (given its source) and Street View, which starts off and travels as a provider switch', async () => {
++ const { createDefaultLayerState } = await import('../../data/layerState.js');
++ const mapillary = {
++ getStatus() {},
++ getTile() {},
++ getSequenceImages() {},
++ nearestImages() {},
++ };
++ const layer = createApplicationStreetLevel({ sources: { mapillary } });
++ assert.deepEqual(layer.providerIds, ['mapillary', 'google']);
++ // A fresh page and a restored default agree: Street View is billed, so off.
++ layer.setParams(createDefaultLayerState().options['street-level']);
++ assert.equal(layer.getParams().google, false);
++ assert.equal(layer.getParams().mapillary, true);
++ // A link that lit Street View carries it in the shared switch field.
++ layer.setParams({ providerSwitches: 'google-1' });
++ assert.equal(layer.getParams().google, true);
++ assert.equal(layer.getParams().providerSwitches, 'google-1');
++ // Without the application's Street Level source there are none.
++ assert.deepEqual(createApplicationStreetLevel({}).providerIds, []);
+});
diff --cc src/data/layerState.test.mjs
index 5b52656ec,08120a604..2b94d81d7
--- a/src/data/layerState.test.mjs
+++ b/src/data/layerState.test.mjs
@@@ -2702,15 -2703,13 +2703,19 @@@ test('Street Level: the link codec acce
assert.equal(streetLevelOptions('0.s.3652').sinceDays, 3652);
});
-test('Street Level: a link without the provider switch keeps Mapillary on', () => {
+test('Street Level: a link without the provider switches keeps Mapillary on and Street View off', () => {
assert.deepEqual(streetLevelOptions(''), {
mapillary: true,
- google: false,
+ providerSwitches: '',
pano: 'all',
sinceDays: 0,
});
- assert.equal(streetLevelOptions('0.g.1').google, true);
- assert.equal(createDefaultLayerState().options['street-level'].google, false);
++ // Street View rides the shared provider-switch field, off unless lit.
++ assert.equal(streetLevelOptions('0.r.google-1').providerSwitches, 'google-1');
++ assert.equal(
++ createDefaultLayerState().options['street-level'].providerSwitches,
++ '',
++ );
assert.equal(streetLevelOptions('0.p.f').mapillary, true);
assert.equal(streetLevelOptions('0.m.0').mapillary, false);
assert.equal(
diff --cc src/layers/streetLevel/index.js
index 0d5f5945a,60a31691e..07ea58d32
--- a/src/layers/streetLevel/index.js
+++ b/src/layers/streetLevel/index.js
@@@ -427,23 -327,22 +427,33 @@@ export function createStreetLevelLayer(
id: STREET_LEVEL_LAYER_ID,
name: 'Street Level',
icon: 'πŸ“·',
- source: definitionsFrozen.map((def) => def.name).join(' Β· '),
+ /** The sources usable on this map (Street View only on Google 3D). */
+ get source() {
+ return listedEntries()
+ .map((entry) => entry.def.name)
+ .join(' Β· ');
+ },
updateInterval: 0,
statsRefreshInterval: 1000,
- requiresKeyId: requiresKeyIdFor(definitionsFrozen),
+ /** The key the switched-on providers share (or null), for the layer row. */
+ get requiresKeyId() {
+ const on = [...state.providers.values()].filter((entry) => entry.on);
+ return requiresKeyIdFor(
+ on.length ? on.map((entry) => entry.def) : definitionsFrozen,
+ );
+ },
/** Registered providers, in chip order. */
providerIds: definitionsFrozen.map((def) => def.id),
+ getSourceAvailability() {
+ const available = definitionsFrozen.length > 0;
+ return {
+ available,
+ source: STREET_LEVEL_LAYER_ID,
+ reason: available
+ ? null
+ : 'No street-level imagery providers configured',
+ };
+ },
init(viewer) {
if (state.initialized)
diff --cc src/layers/streetLevel/index.test.mjs
index 7b7d4dbf0,41b6f917a..890a3c0ca
--- a/src/layers/streetLevel/index.test.mjs
+++ b/src/layers/streetLevel/index.test.mjs
@@@ -483,185 -483,16 +483,199 @@@ test('switching a provider on while th
assert.equal(viewer.credits.length, 1);
});
+/** The real Google provider over the Street View fakes, beside a Mapillary stand-in. */
+async function withStreetView(
+ t,
+ { mapStack = 'photoreal', nearest, mapillaryKeyless = false } = {},
+) {
+ const { createGoogleProvider } = await import('./providers/google/index.js');
+ const { fakeHost, fakeMapsLoader, fakeStreetViewLibrary } =
+ await import('../../testSupport/googleStreetViewFakes.mjs');
+ const fake = fakeStreetViewLibrary({
+ panoramas: {
+ 'pano-a': { lat: 38.5816, lng: -121.4944, imageDate: '2024-05' },
+ },
+ nearest: nearest ?? (() => 'pano-a'),
+ });
+ const mapillaryLookups = [];
+ const mapillary = fakeProvider({
+ nearestImage: async (point) => {
+ mapillaryLookups.push(point);
+ return null;
+ },
+ });
+ mapillary.requiresKeyId = 'mapillary';
+ if (mapillaryKeyless) {
+ mapillary.stats.keyRequired = true;
+ const create = mapillary.create;
+ mapillary.create = (context) => ({
+ ...create(context),
+ status: async () => ({ configured: false }),
+ });
+ }
+ const loader = fakeMapsLoader(fake.library);
+ const google = createGoogleProvider({
+ getApiKey: () => 'browser-key',
+ loader,
+ });
+ const { layer, viewer } = await enabledLayer(t, [mapillary, google]);
+ const stack = fakeMapStack(mapStack);
+ layer.attachMapStackController(stack);
+ layer.attachViewerHost(fakeHost());
+ return { layer, viewer, stack, fake, loader, mapillaryLookups };
+}
+
+test('Street View starts off, and the layer row names the key of the providers that are on', async (t) => {
+ const { layer } = await withStreetView(t);
+ const google = () =>
+ layer.getUIState().providers.find((p) => p.id === 'google');
+ assert.equal(google().on, false);
+ assert.equal(layer.requiresKeyId, 'mapillary');
+ layer.setProviderEnabled('google', true);
+ assert.equal(layer.requiresKeyId, null, 'two keys: each chip names its own');
+});
+
+test('Street View appears only on the Google 3D map: chip, legend, credit, source and images', async (t) => {
+ const { layer, viewer, stack } = await withStreetView(t, {
+ mapStack: 'esri-imagery',
+ });
+ layer.setProviderEnabled('google', true);
+ await settle();
+ const ui = () => layer.getUIState();
+ const listed = () => ui().providers.map((p) => p.id);
+ const credited = () =>
+ viewer.credits.some((credit) => /Street View imagery/.test(credit.html));
+ assert.deepEqual(listed(), ['mapillary'], 'no Street View chip');
+ assert.ok(!ui().legend.some((item) => item.key === 'google'));
+ assert.equal(credited(), false, 'no Google credit on another map');
+ assert.equal(layer.source, 'Mapillary');
+ assert.equal(layer.getStats().source, 'Mapillary');
+ assert.equal(await layer.openImage('google', 'pano-a'), false);
+ assert.match(ui().street.error, /needs the Google 3D map/);
+ assert.equal(layer.getParams().google, true, 'the choice is kept');
+
+ stack.switchTo('photoreal');
+ assert.deepEqual(listed(), ['mapillary', 'google']);
+ assert.equal(credited(), true);
+ assert.equal(layer.source, 'Mapillary Β· Google Street View');
+ assert.equal(await layer.openImage('google', 'pano-a'), true);
+ assert.equal(ui().street.providerId, 'google');
+
+ stack.switchTo('bing');
+ await settle();
+ assert.equal(ui().street.open, false, 'closed with the map');
+ assert.equal(credited(), false);
+ assert.deepEqual(listed(), ['mapillary']);
+});
+
+test('the UI state says when a click (or the button) can open Street View here', async (t) => {
+ const { layer } = await withStreetView(t);
+ assert.equal(typeof layer.getUIState().groundClickReady, 'boolean');
+});
+
+test('a lookup for the click-to-open providers asks only them and reports "that point"', async (t) => {
+ const { layer, mapillaryLookups } = await withStreetView(t, {
+ nearest: () => null,
+ });
+ layer.setProviderEnabled('google', true);
+ await settle();
+ const opened = await layer.openNearest(
+ { lat: 38.58, lon: -121.49 },
+ { providerIds: ['google'], frame: false },
+ );
+ assert.equal(opened, false);
+ assert.deepEqual(mapillaryLookups, [], 'Mapillary was not asked');
+ assert.equal(
+ layer.getUIState().street.error,
+ 'No street-level imagery within 50 m of that point',
+ );
+});
+
+test('an image opened from a ground click leaves the camera where it is', async (t) => {
+ const { layer, viewer } = await withStreetView(t);
+ layer.setProviderEnabled('google', true);
+ await settle();
+ await layer.openNearest(
+ { lat: 38.58, lon: -121.49 },
+ { providerIds: ['google'], frame: false },
+ );
+ assert.equal(layer.getUIState().street.imageId, 'pano-a');
+ assert.equal(viewer.flights.started, 0, 'no framing flight');
+});
+
+test('off Google 3D not even Google\u2019s script is loaded for Street View', async (t) => {
+ const { layer, loader } = await withStreetView(t, {
+ mapStack: 'esri-imagery',
+ });
+ layer.setProviderEnabled('google', true);
+ layer.attachViewerHost({ ownerDocument: { createElement: () => ({}) } });
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ assert.deepEqual(loader.imports, [], 'no prewarm, no lookup');
+});
+
+test('the button’s β€œcentre of the view” is the ground under the middle of the screen', async (t) => {
+ const { createStreetLevelLayer: create } = await import('./index.js');
+ const scenePick = await import('../../data/scenePick.js');
+ const lookups = [];
+ const provider = fakeProvider({
+ nearestImage: async (point) => {
+ lookups.push(point);
+ return null;
+ },
+ });
+ const saved = globalThis.document;
+ const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
+ globalThis.document = Object.assign(new EventTarget(), {
+ createElement: () => ({ getContext: () => drawing }),
+ });
+ const viewer = fakeViewer();
+ const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
+ Object.assign(viewer.scene, {
+ pickPositionSupported: true,
+ pickPosition: (at) => (at.x === 500 && at.y === 300 ? centre : undefined),
+ });
+ viewer.scene.canvas.clientWidth = 1000;
+ viewer.scene.canvas.clientHeight = 600;
+ const layer = create({ providers: [provider], services: { scenePick } });
+ layer.init(viewer);
+ layer.enable(viewer);
+ t.after(() => {
+ layer.destroy();
+ globalThis.document = saved;
+ });
+ await layer.openNearest(undefined, { aim: 'screen-centre' });
+ assert.equal(lookups.length, 1);
+ assert.ok(Math.abs(lookups[0].lat - 38.5799) < 1e-9);
+ assert.ok(Math.abs(lookups[0].lon - -121.4937) < 1e-9);
+});
+
+test('with no Mapillary token, the layer points at Street View, on Google 3D only', async (t) => {
+ const { layer, stack } = await withStreetView(t, { mapillaryKeyless: true });
+ await settle();
+ const stats = layer.getStats();
+ assert.equal(stats.keyRequired, true);
+ assert.deepEqual(stats.keyAlternatives, [
+ { id: 'google', label: 'STREET VIEW', requiresKeyId: 'google-maps' },
+ ]);
+ assert.deepEqual(layer.getUIState().keyAlternatives, stats.keyAlternatives);
+ stack.switchTo('esri-imagery');
+ assert.deepEqual(layer.getStats().keyAlternatives, [], 'not off Google 3D');
+ // Lit, Street View draws: the layer is no longer key-gated.
+ stack.switchTo('photoreal');
+ layer.setProviderEnabled('google', true);
+ assert.equal(layer.getStats().keyRequired, false);
+});
++
+ test('an empty provider composition enables and tears down without acquiring imagery', async (t) => {
+ const { layer, viewer } = await enabledLayer(t, []);
+ assert.deepEqual(layer.providerIds, []);
+ assert.deepEqual(layer.getUIState().providers, []);
+ assert.equal(layer.getUIState().keyRequired, false);
+ assert.match(
+ layer.getUIState().coverage.hint,
+ /No street-level imagery providers/,
+ );
+ layer.disable();
+ layer.enable(viewer);
+ assert.deepEqual(layer.getUIState().providers, []);
+ });
diff --cc src/layers/streetLevel/registry.js
index 7be23c54e,29ec24869..cf9ee67e5
--- a/src/layers/streetLevel/registry.js
+++ b/src/layers/streetLevel/registry.js
@@@ -9,9 -11,6 +11,9 @@@ import { encodeIdSwitches } from '../..
* @property {string} pickPrefix Every primitive id the provider creates starts with it.
* @property {{coverage: string}} colors The source's one colour, from policy.js PROVIDER_COLORS.
* @property {{html: string}} credit On-globe attribution while the provider is active.
+ * @property {boolean} [groundClick] No coverage to click: a click on the ground at street zoom opens its nearest image.
+ * @property {string} [requiresMapStack] Usable only on this map stack (Google Street View: 'photoreal', per Google's terms).
- * @property {boolean} [defaultOn] Switched on until the user says otherwise (default true); match the share-link option default.
++ * @property {boolean} [defaultOn] Switched on until the user says otherwise (default true); a share link without its switch keeps it.
* @property {(context: ProviderContext) => ProviderInstance} create
*
* @typedef {object} ProviderContext Handed to `create()` once by the core.
diff --cc src/layers/streetLevel/uiState.js
index 6c7246597,a2420314f..d4a07b5e6
--- a/src/layers/streetLevel/uiState.js
+++ b/src/layers/streetLevel/uiState.js
@@@ -27,7 -27,10 +27,10 @@@ export function summarizeCoverage(provi
return {
count: active.reduce((sum, p) => sum + (p.count || 0), 0),
loading: active.some((p) => p.loading),
- hint: [...new Set(active.map((p) => p.hint).filter(Boolean))].join(' Β· '),
+ hint:
+ providers.length === 0
+ ? 'No street-level imagery providers configured'
- : active.find((p) => p.hint)?.hint || '',
++ : [...new Set(active.map((p) => p.hint).filter(Boolean))].join(' Β· '),
error: active.find((p) => p.error)?.error || null,
keyRequired:
active.length > 0 && active.every((p) => p.keyRequired === true),
diff --cc src/ui/streetLevelPresentation.js
index d5d089404,da3140b24..527c07e97
--- a/src/ui/streetLevelPresentation.js
+++ b/src/ui/streetLevelPresentation.js
@@@ -153,41 -124,9 +153,42 @@@ function presentViewer(state)
};
}
+/**
+ * A button for the providers with no coverage to click (Street View): opens
+ * their nearest image at the view centre, so they need no pointer.
+ */
+function presentNearest(state) {
+ const targets = (state.providers || []).filter(
+ (provider) =>
+ provider.on && provider.groundClick && provider.keyRequired !== true,
+ );
+ if (state.enabled !== true || !targets.length)
+ return {
+ visible: false,
+ label: '',
+ title: '',
+ disabled: true,
+ providerIds: [],
+ };
+ const names = targets.map((provider) => provider.name).join(' or ');
+ const ready = state.groundClickReady === true;
+ return {
+ visible: true,
+ label: `OPEN ${targets.map((provider) => provider.label).join(' / ')}`,
+ title: ready
+ ? `Open ${names} at the centre of the view`
+ : `Zoom in to a street to open ${names} here`,
+ disabled: !ready || state.street.loading === true,
+ providerIds: targets.map((provider) => provider.id),
+ };
+}
+
function presentMeta(state) {
+ if (state.providers.length === 0) return state.coverage.hint || '';
if (!state.enabled) return 'Switch a provider on to draw its coverage.';
+ // Key-gated with another source ready: say how to use it.
+ if (state.keyRequired && state.keyAlternatives?.length)
+ return keyGuidance(state);
if (state.sequence.selectedId)
return state.sequence.loading
? 'Loading this sequence…'