diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 677201e..390fcac 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -44,13 +44,13 @@ jobs: - name: Setup Node uses: actions/setup-node@v6 with: - node-version: 22 + node-version: 24 registry-url: https://registry.npmjs.org # cache: npm # Trusted publishing needs npm 11.5.1 or later; Node 22 ships npm 10. - name: Update npm - run: npm install -g npm@^11.5.1 + run: npm install -g npm@^12.2.2 # Internal packages may not exist in the npm registry yet. Normalize # their dependency specs temporarily so npm links every dependency from @@ -119,12 +119,19 @@ jobs: echo "::group::${package}" # Skip previewing when the local version is already on the registry. - local_version="$(npm pkg get version --workspace "${package}" | node -e ' + local_version="$(npm pkg get version --workspace "${package}" --json | node -e ' let input = ""; process.stdin.on("data", chunk => input += chunk); process.stdin.on("end", () => { + // npm 11 prints {"": ""}; npm 12 needs --json and + // prints {"": {"version": ""}}. Accept both. const parsed = JSON.parse(input); - const version = typeof parsed === "string" ? parsed : Object.values(parsed)[0]; + let version = typeof parsed === "string" ? parsed : Object.values(parsed)[0]; + if (version && typeof version === "object") version = version.version; + if (typeof version !== "string" || !version) { + console.error(`Could not read the version from: ${input}`); + process.exit(1); + } process.stdout.write(version); }); ')" @@ -164,12 +171,19 @@ jobs: echo "::group::${package}" # Skip publishing when the local version is already on the registry. - local_version="$(npm pkg get version --workspace "${package}" | node -e ' + local_version="$(npm pkg get version --workspace "${package}" --json | node -e ' let input = ""; process.stdin.on("data", chunk => input += chunk); process.stdin.on("end", () => { + // npm 11 prints {"": ""}; npm 12 needs --json and + // prints {"": {"version": ""}}. Accept both. const parsed = JSON.parse(input); - const version = typeof parsed === "string" ? parsed : Object.values(parsed)[0]; + let version = typeof parsed === "string" ? parsed : Object.values(parsed)[0]; + if (version && typeof version === "object") version = version.version; + if (typeof version !== "string" || !version) { + console.error(`Could not read the version from: ${input}`); + process.exit(1); + } process.stdout.write(version); }); ')" diff --git a/.gitignore b/.gitignore index 97d3ae6..659f489 100644 --- a/.gitignore +++ b/.gitignore @@ -52,8 +52,14 @@ dist/* *.mjs # 雛形の適合テストはバージョン管理する(外部の作者がコピーする出発点なので)。 !react-for-template/test/*.mjs +# サンプルの単体テスト(node --test)。 +!examples/basic/test/*.mjs !examples/basic/server.mjs !examples/basic/scripts/generate-static.mjs +!examples/basic/scripts/check-snippets.mjs +!examples/basic/scripts/snippet-interactions.mjs +!examples/basic/scripts/vite-maplibre-registry.mjs +!examples/basic/scripts/vite-maplibre-registry.test.mjs # scripts/ はソースしか置かないので丸ごと追跡する。1 本ずつ negation を足す運用だと # 足し忘れたスクリプトが `git add -A` で無言のまま無視され、CI のチェックアウトにだけ # 存在しない状態になる(unlink-local-workspaces.mjs で実際に踏んだ)。 diff --git a/AGENTS.md b/AGENTS.md index 7ff8de4..5f3daec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,7 @@ Tiling happens in the Android core after the marker definitions reach the native For MapLibre, tiled markers have `entity.marker == null` and are rendered by `MarkerTileRenderer`. Never register their images in the MapLibre Style. `MapLibreMarkerOverlayRenderer.ensureStyleImages()` must only process native marker entities and must deduplicate by icon key; otherwise a style reload can call `style.addImage()` tens of thousands of times and delay the first tile for nearly a minute. -`MarkerTilingOptions.iconScaleCallback(state, zoom)` may depend on priority, category, or other marker state. A global zoom-stop replacement is not API-equivalent. A general RN serialization design for state-dependent callbacks is currently deferred. The React Native post-office example temporarily uses a fixed `ReactNativeImageIcon` scale of `0.4`. +`MarkerTilingOptions.iconScaleCallback(state, zoom)` may depend on priority, category, or other marker state. A global zoom-stop replacement is not API-equivalent. JS functions cannot cross the bridge, so the payload only carries `hasIconScaleCallback`; `NativeMapViewHost` registers the callback through `registerIconScaleCallback` (`js-sdk-react/src/marker/IconScaleBridge.native.ts`) and native calls back into JS for the scale. The callback only affects tiled markers (`MarkerTileRenderer`); markers below `minMarkerCount`, draggable markers, and animated markers are drawn natively and ignore it. The React Native post-office example uses `ReactNativeImageIcon` with `scale: 0.4` as the base icon size and the same zoom-stop `iconScaleCallback` as the web example. Use the `MCMarkerTrace` tag when profiling marker ingestion. Compare JS batch time, native decoding time, core diff time, provider post-processing, controller completion, first tile request, and tile response separately. A long gap after `CoreSDK ingest end` but before the first tile request is not tile-rendering time and should be traced in controller/style synchronization. GC during RN decoding and GC during tile bitmap/PNG generation are different costs; do not attribute every GC to the bridge. diff --git a/README.md b/README.md index 0c2efc3..18e7615 100644 --- a/README.md +++ b/README.md @@ -463,3 +463,19 @@ Apache License 2.0. See [`LICENSE`](./LICENSE). - [MapConductor Android SDK](https://github.com/MapConductor/android-sdk) - [Google Maps JavaScript API](https://developers.google.com/maps/documentation/javascript) - [MapLibre](https://maplibre.org/) + +## Bulk circles and raster tiles + +Use `` from `@mapconductor/js-sdk-react` to register a collection without one React effect per circle. Each collection removes only its own IDs. + +Web map providers accept `circleTilingOptions`. Use `CircleTilingOptions.Disabled` from `@mapconductor/js-sdk-core` to keep native rendering. For large web collections, `Circles` also accepts a reusable iterable, as shown by the nationwide example. + +By default, raster tiling starts above 2,000 tileable circles. Large collections keep their drawing geometry in a disk-backed cache. Circle radius remains a ground distance in metres and stroke width remains a screen distance. Clicks and `onAdded` use the original states. `onAdded` indicates that the tile layer was handed to the map. + +Circles crossing the antimeridian, reaching Mercator's latitude limit, or having invalid radii stay native. Circle tiles stack above polygons and below polylines. Web rendering also falls back to native when the service worker cannot draw tiles. + +## US antenna horizons example + +Choose **US Antenna Horizons** in the example sidebar. It bundles 723,800 OpenCellID records (MCC 310–314), with carrier filters and US and Alaska camera presets. Each estimated cell position is drawn as a 500 m geodesic circle. The radius is a display setting and does not model signal coverage. + +Cell tower data from [OpenCellID](https://opencellid.org) · [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). diff --git a/examples/basic/README.md b/examples/basic/README.md index 24d8db7..c0c364b 100644 --- a/examples/basic/README.md +++ b/examples/basic/README.md @@ -57,6 +57,17 @@ This project uses Vite's environment variable system. All environment variables - Never put sensitive secrets that should remain server-side in `VITE_` variables - For production deployment, set environment variables in your hosting platform +## Validate the displayed code examples + +From the workspace root, run `npm run check:snippets --workspace @mapconductor/example-basic`. +This checks the generated TSX for every supported page/provider pair, including imports, +and exercises data preparation and interaction handlers with real SDK state objects. +Provider rendering still requires a browser and any provider-specific credentials. + +The snippets are standalone `App.tsx` examples. They include small inline datasets; +the interactive pages may use larger datasets and additional controls. Replace `YOUR_…` +credential placeholders when using a provider that requires authentication. + ## Features - Switch between MapLibre and Google Maps providers diff --git a/examples/basic/index.html b/examples/basic/index.html index 16b083e..f2e54d5 100644 --- a/examples/basic/index.html +++ b/examples/basic/index.html @@ -6,12 +6,11 @@ MapConductor React SDK - Basic Example - - - - - - + + + + +
diff --git a/examples/basic/package.json b/examples/basic/package.json index 93fdaa2..f8e79e9 100644 --- a/examples/basic/package.json +++ b/examples/basic/package.json @@ -4,11 +4,14 @@ "private": true, "description": "Basic example app for MapConductor React SDK", "scripts": { + "test:maplibre-registry": "node --test scripts/vite-maplibre-registry.test.mjs", + "check:snippets": "node scripts/check-snippets.mjs", "dev": "vite", "dev:https": "HTTPS=true vite", "build": "NODE_OPTIONS=--max-old-space-size=6144 vite build && NODE_OPTIONS=--max-old-space-size=6144 vite build --ssr src/entry-server.tsx --outDir dist/server && node scripts/generate-static.mjs", "preview": "vite preview --port 4000", - "start": "vite preview --host 0.0.0.0 --port 4000" + "start": "vite preview --host 0.0.0.0 --port 4000", + "test": "node --test \"test/**/*.test.mjs\"" }, "dependencies": { "@mapconductor/js-sdk-core": "*", @@ -34,7 +37,7 @@ "@mapconductor/js-vectorstyle": "*", "@mapconductor/react-vectortile": "*", "@zip.js/zip.js": "^2.8.26", - "maplibre-gl": "^6.15.0", + "maplibre-gl": "^6.17.0", "prism-react-renderer": "^2.4.1", "react": "^19.2.7", "react-dom": "^19.2.7", @@ -46,6 +49,7 @@ "devDependencies": { "@types/react": "^19.2.17", "@types/react-dom": "^19.2.3", + "@types/three": "^0.185.4", "@vitejs/plugin-react": "^5.2.0", "ts-node": "^10.9.2", "typescript": "^5.9.3", diff --git a/examples/basic/public/antennas/us-antennas.bin b/examples/basic/public/antennas/us-antennas.bin new file mode 100644 index 0000000..8f2c276 Binary files /dev/null and b/examples/basic/public/antennas/us-antennas.bin differ diff --git a/examples/basic/public/antennas/us-antennas.json b/examples/basic/public/antennas/us-antennas.json new file mode 100644 index 0000000..6429bf1 --- /dev/null +++ b/examples/basic/public/antennas/us-antennas.json @@ -0,0 +1,31 @@ +{ + "source": "https://opencellid.org", + "license": "https://creativecommons.org/licenses/by-sa/4.0/", + "attribution": "Cell tower data from OpenCellID \u00b7 CC BY-SA 4.0", + "inputs": [ + "310.csv.gz", + "311.csv.gz", + "312.csv.gz", + "313.csv.gz", + "314.csv.gz" + ], + "count": 723800, + "carrier_counts": [ + 199569, + 372599, + 147164, + 4468 + ], + "mcc_counts": { + "310": 567764, + "311": 150228, + "312": 199, + "313": 5349, + "314": 260 + }, + "file_sha256": "eda2bc13c14fe4d29ee94b4e6a92d6b8be14566ef04a95cb6aaf2954b456acec", + "bytes": 11580808, + "format": "MCCE + u32 count + records (i32 latitude_e5, i32 longitude_e5, f32 range_m, u32 carrier*1000+MNC), little endian", + "classification_source": "https://imsiadmin.com/assignments/hni/", + "coverage": "Supplied MCC 310-314 files; not a complete inventory of physical towers" +} diff --git a/examples/basic/public/boston/boston-city-buildings.bin b/examples/basic/public/boston/boston-city-buildings.bin new file mode 100644 index 0000000..25bf38f Binary files /dev/null and b/examples/basic/public/boston/boston-city-buildings.bin differ diff --git a/examples/basic/public/boston/boston-city-parcels.bin b/examples/basic/public/boston/boston-city-parcels.bin new file mode 100644 index 0000000..0859c1c Binary files /dev/null and b/examples/basic/public/boston/boston-city-parcels.bin differ diff --git a/examples/basic/public/boston/boston-city-roads.bin b/examples/basic/public/boston/boston-city-roads.bin new file mode 100644 index 0000000..87cfa74 Binary files /dev/null and b/examples/basic/public/boston/boston-city-roads.bin differ diff --git a/examples/basic/public/boston/boston-city-trees.bin b/examples/basic/public/boston/boston-city-trees.bin new file mode 100644 index 0000000..481adc7 Binary files /dev/null and b/examples/basic/public/boston/boston-city-trees.bin differ diff --git a/examples/basic/public/boston/boston-downtown.bin b/examples/basic/public/boston/boston-downtown.bin new file mode 100644 index 0000000..f10719c Binary files /dev/null and b/examples/basic/public/boston/boston-downtown.bin differ diff --git a/examples/basic/scripts/check-snippets.mjs b/examples/basic/scripts/check-snippets.mjs new file mode 100644 index 0000000..d1efcef --- /dev/null +++ b/examples/basic/scripts/check-snippets.mjs @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import { build } from 'esbuild'; +import ts from 'typescript'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { checkInteractions } from './snippet-interactions.mjs'; + +const root = fileURLToPath(new URL('../../../', import.meta.url)); +const result = await build({ + stdin: { + contents: `export { getSampleDocumentation } from './examples/basic/src/samples/documentation'; +export { SAMPLE_PAGES, resolveProviderForPage } from './examples/basic/src/samples/sampleRegistry'; +export { DOCUMENTATION_PROVIDERS } from './examples/basic/src/samples/sampleDocumentationProviders';`, + resolveDir: root, + }, + bundle: true, write: false, platform: 'node', format: 'esm', +}); +const { getSampleDocumentation, SAMPLE_PAGES, DOCUMENTATION_PROVIDERS, resolveProviderForPage } = + await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`); + +// Virtual files let TypeScript check exactly the text displayed to readers, +// without producing or maintaining a second copy of every example. +const snippets = new Map(); +for (const page of SAMPLE_PAGES) { + for (const provider of DOCUMENTATION_PROVIDERS) { + if (page.unavailableProviders?.includes(provider)) continue; + const resolved = resolveProviderForPage(provider, page.id); + const doc = getSampleDocumentation(page.id, resolved, 'ja'); + assert.match(doc.code, /export default function App\(\)/); + assert.doesNotMatch(doc.code, /MapViewContainer|providerDesignOptions|example\.com/); + assert.doesNotMatch(doc.code, /MapConductor overlays/, `${page.id} needs page-specific documentation`); + snippets.set(path.join(root, 'examples/basic', `__snippet_${page.id}_${provider}.tsx`), doc.code); + } +} +assert.match(getSampleDocumentation('marker', 'google').code, /GoogleMapView2D/); +assert.match(getSampleDocumentation('marker', 'google-3d').code, /GoogleMapView\b/); +const options = { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + jsx: ts.JsxEmit.ReactJSX, + strict: true, noEmit: true, skipLibCheck: true, + noUnusedLocals: true, noUnusedParameters: true, + allowSyntheticDefaultImports: true, esModuleInterop: true, + types: ['vite/client'], +}; +const host = ts.createCompilerHost(options); +const readFile = host.readFile.bind(host); +const fileExists = host.fileExists.bind(host); +host.readFile = name => snippets.get(name) ?? readFile(name); +host.fileExists = name => snippets.has(name) || fileExists(name); +const program = ts.createProgram([...snippets.keys()], options, host); +const diagnostics = ts.getPreEmitDiagnostics(program).filter(d => !d.file || snippets.has(d.file.fileName)); +if (diagnostics.length) { + console.error(ts.formatDiagnosticsWithColorAndContext(diagnostics, { + getCanonicalFileName: name => name, getCurrentDirectory: () => root, getNewLine: () => '\n', + })); + process.exitCode = 1; +} else { + console.log(`Checked ${snippets.size} snippets (${SAMPLE_PAGES.length} pages, ${DOCUMENTATION_PROVIDERS.length} providers).`); + checkInteractions(getSampleDocumentation, SAMPLE_PAGES); +} diff --git a/examples/basic/scripts/snippet-interactions.mjs b/examples/basic/scripts/snippet-interactions.mjs new file mode 100644 index 0000000..ec9c55e --- /dev/null +++ b/examples/basic/scripts/snippet-interactions.mjs @@ -0,0 +1,166 @@ +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import ts from 'typescript'; + +const require = createRequire(import.meta.url); +const core = require('@mapconductor/js-sdk-core'); +const vectorStyle = await import('@mapconductor/js-vectorstyle'); +const extensionModules = Object.fromEntries(['geojson', 'kml', 'heatmap'].map(name => { + const source = `@mapconductor/react-${name}`; + return [source, { ...require(source), GeoJSONLayer: 'GeoJSONLayer', KMLLayer: 'KMLLayer', + HeatmapOverlay: 'HeatmapOverlay', HeatmapPoints: 'HeatmapPoints' }]; +})); + +/** Execute the displayed App with real SDK state objects and a small hook host. + * Maps remain element descriptors: these checks exercise example event handlers, + * not provider rendering (which needs a browser and, for some providers, keys). + */ +function mount(code) { + const slots = []; + let cursor = 0; + let effects = []; + const same = (a, b) => a && b && a.length === b.length && a.every((value, i) => Object.is(value, b[i])); + const hooks = { + useState(initial) { + const index = cursor++; + if (!(index in slots)) slots[index] = typeof initial === 'function' ? initial() : initial; + return [slots[index], value => { slots[index] = typeof value === 'function' ? value(slots[index]) : value; }]; + }, + useRef(initial) { return hooks.useMemo(() => ({ current: initial }), []); }, + useMemo(create, deps) { + const index = cursor++; + if (!slots[index] || !same(slots[index].deps, deps)) slots[index] = { deps, value: create() }; + return slots[index].value; + }, + useEffect(run, deps) { + const index = cursor++; + if (!slots[index] || !same(slots[index], deps)) { slots[index] = deps; effects.push(run); } + }, + }; + const jsx = (type, props, key) => ({ type, props: props ?? {}, key }); + const design = { id: 'normal' }; + const provider = new Proxy({}, { get: (_, key) => { + if (String(key).startsWith('use')) return params => hooks.useMemo(() => ({ + ...params, calls: [], + moveCameraTo(camera, duration) { this.cameraPosition = camera; this.calls.push({ camera, duration }); }, + fitBounds(bounds, padding) { this.calls.push({ bounds, padding }); }, + }), []); + if (String(key).includes('Design')) return { Normal: design, OsmBrightJa: design, OpenStreetMap: design }; + return key; + } }); + const componentNames = new Proxy({}, { get: (_, key) => key }); + const output = ts.transpileModule(code, { + compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2022 }, + }).outputText; + const exports = {}; + // Image encoding is verified in Chrome; the hook host only needs a canvas stub. + const document = { createElement(tag) { + assert.equal(tag, 'canvas'); + return { getContext: () => ({ fillRect() {}, fillText() {} }), + toDataURL: format => { assert.equal(format, 'image/png'); return 'data:image/png;base64,test'; } }; + } }; + new Function('require', 'exports', 'document', output)(source => { + if (source === 'react') return hooks; + if (source === 'react/jsx-runtime') return { jsx, jsxs: jsx }; + if (source.endsWith('.css')) return {}; + if (source === '@mapconductor/js-sdk-core') return core; + if (source === '@mapconductor/js-vectorstyle') return vectorStyle; + if (source === '@mapconductor/js-sdk-react') return componentNames; + if (extensionModules[source]) return extensionModules[source]; + if (source.startsWith('@mapconductor/react-for-')) return provider; + if (source === '@mapconductor/react-vectortile' || source === '@mapconductor/react-marker-clustering') return componentNames; + return require(source); + }, exports, document); + const render = () => { + cursor = 0; effects = []; + const tree = exports.default(); + effects.forEach(run => run()); + return tree; + }; + return { render }; +} + +function elements(tree, type) { + if (Array.isArray(tree)) return tree.flatMap(child => elements(child, type)); + if (!tree || typeof tree !== 'object') return []; + return [...(tree.type === type ? [tree] : []), ...elements(tree.props?.children, type)]; +} + +export function checkInteractions(getDocumentation, pages) { + const sample = page => mount(getDocumentation(page, 'maplibre', 'ja').code); + // Every App can prepare its own data without a surrounding example application. + for (const page of pages) assert.ok(sample(page.id).render(), page.id); + + for (const [page, shape, field] of [['polyline', 'Polyline', 'points'], ['polygon', 'Polygon', 'points'], ['polygon-hole', 'Polygon', 'holes']]) { + const app = sample(page); + let tree = app.render(); + const marker = elements(tree, 'Markers')[0].props.states[0]; + const moved = core.createGeoPoint({ latitude: 35.675, longitude: 139.775 }); + marker.position = moved; + marker.onDrag(marker); + tree = app.render(); + const geometry = elements(tree, shape)[0].props.state[field]; + assert.equal(field === 'holes' ? geometry[0][0] : geometry[0], moved, `${page} updates geometry`); + assert.equal(elements(tree, 'Markers')[0].props.states[0], marker, `${page} retains the dragged marker`); + } + + const multiple = sample('info-bubble-multiple'); + const selected = elements(multiple.render(), 'Markers')[0].props.states[0]; + selected.onClick(selected); selected.onClick(selected); + assert.equal(elements(multiple.render(), 'InfoBubble').length, 1, 'clicking twice does not duplicate a bubble'); + + const circle = sample('circle'); + const edge = elements(circle.render(), 'Marker').find(item => item.props.draggable); + edge.props.onDrag(core.createMarkerState({ position: core.Spherical.computeOffset({ + origin: edge.props.position, distance: 1000, heading: 90, + }) })); + assert.ok(elements(circle.render(), 'Circle')[0].props.state.radiusMeters > 1500, 'circle resizes'); + + for (const [page, type] of [['geojson-basic', 'GeoJSONLayer'], ['geojson-layer', 'GeoJSONLayer'], ['kml-layer', 'KMLLayer']]) { + assert.ok(elements(sample(page).render(), type)[0].props.features.length, `${page} has actual features`); + } + + const raster = sample('raster-layer'); + let tree = raster.render(); + const layer = elements(tree, 'RasterLayer')[0].props.state; + elements(tree, 'input')[0].props.onChange({ target: { value: '0.4' } }); + tree = raster.render(); + assert.equal(elements(tree, 'RasterLayer')[0].props.state, layer); + assert.equal(layer.opacity, 0.4, 'opacity updates the existing raster state'); + + const tilt = sample('tilt'); + tree = tilt.render(); + const map = elements(tree, 'MapLibreMapView2D')[0].props.state; + assert.equal(map.calls.length, 0, 'rendering does not move the camera'); + elements(tree, 'input')[0].props.onChange({ target: { value: '40' } }); + assert.equal(map.calls[0].camera.tilt, 40); + tilt.render(); + assert.equal(map.calls.length, 1, 'rerendering does not repeat camera movement'); + + const sync = sample('camera-sync'); + tree = sync.render(); + const left = elements(tree, 'MapLibreMapView2D')[0]; + const right = elements(tree, 'LeafletMapView')[0]; + const panes = elements(tree, 'div').filter(item => item.props.onWheel); + panes[0].props.onWheel(); + left.props.onCameraMove(left.props.state.cameraPosition); + right.props.onCameraMove(right.props.state.cameraPosition); + assert.equal(right.props.state.calls.length, 1); + assert.equal(left.props.state.calls.length, 0, 'mirrored camera events do not echo'); + panes[1].props.onFocusCapture(); + right.props.onCameraMove(right.props.state.cameraPosition); + assert.equal(left.props.state.calls.length, 1, 'either map can become the source'); + + const ground = sample('ground-image'); + tree = ground.render(); + const image = elements(tree, 'GroundImage')[0].props.state; + assert.match(image.imageUrl, /^data:image\/png;/, 'ground image uses a raster image that MapLibre can decode'); + const corners = elements(tree, 'Markers')[0].props.states; + corners[0].position = core.createGeoPoint({ latitude: -26.485, longitude: 31.299 }); + corners[0].onDrag(corners[0]); + corners[1].position = core.createGeoPoint({ latitude: -26.473, longitude: 31.313 }); + corners[1].onDrag(corners[1]); + assert.equal(image.bounds.southWest, corners[0].position); + assert.equal(image.bounds.northEast, corners[1].position); + console.log('Checked snippet data and interaction handlers.'); +} diff --git a/examples/basic/scripts/vite-maplibre-registry.mjs b/examples/basic/scripts/vite-maplibre-registry.mjs new file mode 100644 index 0000000..b60e791 --- /dev/null +++ b/examples/basic/scripts/vite-maplibre-registry.mjs @@ -0,0 +1,44 @@ +import { readFile } from 'node:fs/promises'; + +// Demo only: both renderers register built-in constructors (Object, Set, Error) +// under the same private property. MapLibre's Set registration makes Mapbox look +// up a class that is absent from its own registry, breaking all vector tiles. +// Keep the wire format ($name) intact; isolate each renderer's constructor key. +// Never apply this in the SDK package builds or modify installed dependencies. +// Longdo loads its own external MapLibre; isolate Mapbox too so foreign +// constructor registrations cannot bypass its built-in serialization handling. +const rendererModule = /(?:maplibre-gl|mapbox-gl).*\.[cm]?js$/; + +function rewrite(code, id) { + const renderer = id.includes('mapbox-gl') ? 'Mapbox' : 'MapLibre'; + return code.replaceAll('_classRegistryKey', `_mapconductorDemo${renderer}RegistryKey`); +} + +/** @returns {import('vite').Plugin} */ +export function isolateMapLibreRegistry() { + return { + name: 'demo-isolate-maplibre-registry', + enforce: 'pre', + config() { + return { + optimizeDeps: { + esbuildOptions: { + plugins: [{ + name: 'demo-isolate-maplibre-registry', + setup(build) { + build.onLoad({ filter: rendererModule }, async ({ path }) => ({ + contents: rewrite(await readFile(path, 'utf8'), path), + loader: 'js', + })); + }, + }], + }, + }, + }; + }, + transform(code, id) { + if (!rendererModule.test(id.split('?')[0]) || !code.includes('_classRegistryKey')) return; + return { code: rewrite(code, id), map: null }; + }, + }; +} diff --git a/examples/basic/scripts/vite-maplibre-registry.test.mjs b/examples/basic/scripts/vite-maplibre-registry.test.mjs new file mode 100644 index 0000000..5e04618 --- /dev/null +++ b/examples/basic/scripts/vite-maplibre-registry.test.mjs @@ -0,0 +1,80 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { test } from 'node:test'; +import { runInNewContext } from 'node:vm'; +import { build } from 'esbuild'; +import { isolateMapLibreRegistry } from './vite-maplibre-registry.mjs'; + +const require = createRequire(import.meta.url); +const maplibrePath = require.resolve('maplibre-gl/dist/maplibre-gl-dev.mjs'); +const maplibre = await readFile(maplibrePath, 'utf8'); +const mapbox = await readFile(require.resolve('mapbox-gl/dist/mapbox-gl-dev.js'), 'utf8'); +const plugin = isolateMapLibreRegistry(); + +function serializeWithBothRenderers(maplibreCode, order, mapboxCode = mapbox) { + // Exercise the installed libraries' actual registration/serialization code. + // Separate registries, shared built-in constructors, just like a browser page. + const registerStart = maplibreCode.indexOf('function register(name, klass, options = {})'); + assert.ok(registerStart >= 0, 'MapLibre registration code changed; review the workaround'); + const registerEnd = maplibreCode.indexOf('register("Object", Object);', registerStart); + assert.ok(registerEnd > registerStart); + const serializeStart = mapboxCode.indexOf('function serialize(input, transferables)'); + const serializeEnd = mapboxCode.indexOf('function deserialize(input)', serializeStart); + assert.ok(serializeStart >= 0 && serializeEnd > serializeStart); + const registerMaplibre = `(() => { + const registry = {}; + ${maplibreCode.slice(registerStart, registerEnd)} + register('Object', Object); register('Set', Set); register('Error', Error); + })();`; + const registerStartBox = mapboxCode.indexOf('function register(klass, name, options = {})'); + const registerEndBox = mapboxCode.indexOf('register(Object, "Object");', registerStartBox); + assert.ok(registerStartBox >= 0 && registerEndBox > registerStartBox); + const registerMapbox = `${mapboxCode.slice(registerStartBox, registerEndBox)} register(Object, 'Object');`; + return runInNewContext(` + class ImageBitmap {} class ImageData {} class Headers {} + const assert = () => {}; // Mapbox's production assertions are compiled out. + const registry = {Object: {omit: []}}; + const isArrayBuffer = value => value instanceof ArrayBuffer; + ${order === 'mapbox-first' ? registerMapbox + registerMaplibre : registerMaplibre + registerMapbox} + ${mapboxCode.slice(serializeStart, serializeEnd)} + JSON.stringify(serialize({tiles: new Set([1, 2])})); + `); +} + +test('reproduces the installed MapLibre/Mapbox registry collision', () => { + assert.throws(() => serializeWithBothRenderers(maplibre, 'maplibre-first'), /omit/); +}); + +test('production transform permits both load orders without changing the wire format', () => { + const transformed = plugin.transform(maplibre, maplibrePath).code; + for (const order of ['maplibre-first', 'mapbox-first']) { + assert.deepEqual(JSON.parse(serializeWithBothRenderers(transformed, order)), { + tiles: {$name: 'Set', 1: 1, 2: 2}, + }); + } + assert.equal(plugin.transform('const x = 1;', '/unrelated/library.js'), undefined); +}); + +test('Mapbox coexists with unmodified external MapLibre as loaded by Longdo', () => { + const transformed = plugin.transform(mapbox, require.resolve('mapbox-gl')).code; + for (const order of ['maplibre-first', 'mapbox-first']) { + assert.deepEqual(JSON.parse(serializeWithBothRenderers(maplibre, order, transformed)), { + tiles: {$name: 'Set', 1: 1, 2: 2}, + }); + } +}); + +test('Vite dependency optimization applies the same isolation to MapLibre', async () => { + const config = plugin.config(); + const result = await build({ + entryPoints: [require.resolve('maplibre-gl/dist/maplibre-gl.mjs')], + bundle: true, + write: false, + format: 'esm', + plugins: config.optimizeDeps.esbuildOptions.plugins, + }); + assert.ok(result.outputFiles[0].text.includes('_mapconductorDemoMapLibreRegistryKey')); + assert.ok(!result.outputFiles[0].text.includes('_classRegistryKey')); + assert.equal(await readFile(maplibrePath, 'utf8'), maplibre); +}); diff --git a/examples/basic/src/ClientMapRoutes.tsx b/examples/basic/src/ClientMapRoutes.tsx index be4d08e..9ecb4a1 100644 --- a/examples/basic/src/ClientMapRoutes.tsx +++ b/examples/basic/src/ClientMapRoutes.tsx @@ -34,6 +34,7 @@ const CameraRestrictionPage = lazy(() => import('./pages/map/camerarestriction/C const TiltPage = lazy(() => import('./pages/map/tilt/TiltPage').then(m => ({ default: m.TiltPage }))); const UISettingsPage = lazy(() => import('./pages/map/uisettings/UISettingsPage').then(m => ({ default: m.UISettingsPage }))); const VisibleRegionPage = lazy(() => import('./pages/map/visibleregion/VisibleRegionPage').then(m => ({ default: m.VisibleRegionPage }))); +const ProjectedCoordinatesPage = lazy(() => import('./pages/map/projected/ProjectedCoordinatesPage').then(m => ({ default: m.ProjectedCoordinatesPage }))); const CameraSyncPage = lazy(() => import('./pages/map/camerasync/CameraSyncPage').then(m => ({ default: m.CameraSyncPage }))); const MarkerLabelPositionPage = lazy(() => import('./pages/marker/labelposition/MarkerLabelPositionPage').then(m => ({ default: m.MarkerLabelPositionPage }))); const MarkerAnimationPage = lazy(() => import('./pages/marker/animation/MarkerAnimationPage').then(m => ({ default: m.MarkerAnimationPage }))); @@ -43,6 +44,11 @@ const StreetTreePage = lazy(() => import('./pages/marker/streettree/StreetTreePa const PolygonClickPage = lazy(() => import('./pages/polygon/click/PolygonClickPage').then(m => ({ default: m.PolygonClickPage }))); const PolygonGeodesicPage = lazy(() => import('./pages/polygon/geodesic/PolygonGeodesicPage').then(m => ({ default: m.PolygonGeodesicPage }))); const PolygonHolePage = lazy(() => import('./pages/polygon/hole/PolygonHolePage').then(m => ({ default: m.PolygonHolePage }))); +const PolygonsPage = lazy(() => import('./pages/polygon/collection/PolygonsPage').then(m => ({ default: m.PolygonsPage }))); +const BostonBuildingsPage = lazy(() => import('./pages/polygon/boston/BostonBuildingsPage').then(m => ({ default: m.BostonBuildingsPage }))); +const BostonRoadsPage = lazy(() => import('./pages/polyline/boston/BostonRoadsPage').then(m => ({ default: m.BostonRoadsPage }))); +const AntennaHorizonsPage = lazy(() => import('./pages/circle/antennas/AntennaHorizonsPage').then(m => ({ default: m.AntennaHorizonsPage }))); +const BostonTreesPage = lazy(() => import('./pages/circle/boston/BostonTreesPage').then(m => ({ default: m.BostonTreesPage }))); const PolylineClickPage = lazy(() => import('./pages/polyline/click/PolylineClickPage').then(m => ({ default: m.PolylineClickPage }))); const RasterLayerPage = lazy(() => import('./pages/rasterlayer/RasterLayerPage').then(m => ({ default: m.RasterLayerPage }))); const VectorTileLayerPage = lazy(() => import('./pages/vectortile/VectorTileLayerPage').then(m => ({ default: m.VectorTileLayerPage }))); @@ -86,6 +92,7 @@ function pageContent(page: string | undefined) { case 'tilt': return ; case 'ui-settings': return ; case 'visible-region': return ; + case 'projected-coordinates': return ; case 'camera-sync': return ; case 'marker': return ; case 'marker-label-position': return ; @@ -98,6 +105,11 @@ function pageContent(page: string | undefined) { case 'polygon-click': return ; case 'polygon-geodesic': return ; case 'polygon-hole': return ; + case 'polygons': return ; + case 'boston-buildings': return ; + case 'boston-roads': return ; + case 'antenna-horizons': return ; + case 'boston-trees': return ; case 'ground-image': return ; case 'raster-layer': return ; case 'vector-tile': return ; diff --git a/examples/basic/src/MapViewContainer.tsx b/examples/basic/src/MapViewContainer.tsx index 6045a30..cfdd071 100644 --- a/examples/basic/src/MapViewContainer.tsx +++ b/examples/basic/src/MapViewContainer.tsx @@ -9,6 +9,8 @@ import type { MapViewStateInterface, MarkerTilingOptions, MapViewStyle, + PolylineTilingOptions, + CircleTilingOptions, } from '@mapconductor/js-sdk-core'; import { type InitialCamera, DEFAULT_CAMERA } from './common'; import { SingletonMapSlot, useSingletonMapState, type SingletonMapId } from './SingletonMaps'; @@ -54,6 +56,16 @@ interface MapViewContainerProps { /** 地図の見た目そのもの。`createVectorStyle()` が作る。 */ mapStyle?: MapViewStyle | null; onStyleDiagnostics?: (diagnostics: readonly string[]) => void; + /** + * When the shared map draws this page's polylines as tiles. Applies from the next time the + * polylines are handed over; back to the default when the page leaves. + */ + polylineTilingOptions?: PolylineTilingOptions; + /** + * When the shared map draws this page's circles as tiles. Applies from the next time the + * circles are handed over; back to the default when the page leaves. + */ + circleTilingOptions?: CircleTilingOptions; } function SingletonProviderView({ @@ -69,6 +81,8 @@ function SingletonProviderView({ cameraRestriction: cameraRestrictionProp, mapStyle, onStyleDiagnostics, + polylineTilingOptions, + circleTilingOptions, }: ProviderViewProps & { id: SingletonMapId }) { const cameraPosition = useInitialCameraPosition(initialCamera); const state = useSingletonMapState(id, cameraPosition); @@ -93,6 +107,8 @@ function SingletonProviderView({ cameraRestriction={cameraRestriction} mapStyle={mapStyle} onStyleDiagnostics={onStyleDiagnostics} + polylineTilingOptions={polylineTilingOptions} + circleTilingOptions={circleTilingOptions} > {children} @@ -112,6 +128,8 @@ export function MapViewContainer({ restrictBounds, mapStyle, onStyleDiagnostics, + polylineTilingOptions, + circleTilingOptions, }: MapViewContainerProps) { const location = useLocation(); const isGoogle3D = location.pathname.startsWith('/google-maps-3d'); @@ -146,6 +164,8 @@ export function MapViewContainer({ cameraRestriction, mapStyle, onStyleDiagnostics, + polylineTilingOptions, + circleTilingOptions, }; switch (true) { diff --git a/examples/basic/src/SingletonMaps.tsx b/examples/basic/src/SingletonMaps.tsx index 8e3dfee..09ea96b 100644 --- a/examples/basic/src/SingletonMaps.tsx +++ b/examples/basic/src/SingletonMaps.tsx @@ -16,6 +16,8 @@ import { createGeoPoint, createMapCameraPosition, MarkerTilingOptions, + PolylineTilingOptions, + CircleTilingOptions, type MapCameraPosition, type MapDesignTypeInterface, type MapViewStateInterface, @@ -278,6 +280,8 @@ export function SingletonMapsProvider({ children }: { children: ReactNode }) { onCameraMoveEnd={content['google-2d']?.onCameraMoveEnd} mapStyle={content['google-2d']?.mapStyle} onStyleDiagnostics={content['google-2d']?.onStyleDiagnostics} + polylineTilingOptions={content['google-2d']?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content['google-2d']?.circleTilingOptions ?? CircleTilingOptions.Default} > {content['google-2d'] && {content['google-2d']!.children}} @@ -381,7 +385,7 @@ export function SingletonMapsProvider({ children }: { children: ReactNode }) { ); } -export function SingletonMapSlot({ id, children, onMapClick, onCameraMoveStart, onCameraMove, onCameraMoveEnd, cameraRestriction, mapStyle, onStyleDiagnostics }: SingletonMapSlotProps) { +export function SingletonMapSlot({ id, children, onMapClick, onCameraMoveStart, onCameraMove, onCameraMoveEnd, cameraRestriction, mapStyle, onStyleDiagnostics, polylineTilingOptions, circleTilingOptions }: SingletonMapSlotProps) { const { register, unregister } = useSingletonMapsContext(); const owner = useId(); @@ -396,6 +400,8 @@ export function SingletonMapSlot({ id, children, onMapClick, onCameraMoveStart, cameraRestriction, mapStyle, onStyleDiagnostics, + polylineTilingOptions, + circleTilingOptions, }); return () => unregister(id, owner); }, [ @@ -409,6 +415,8 @@ export function SingletonMapSlot({ id, children, onMapClick, onCameraMoveStart, cameraRestriction, mapStyle, onStyleDiagnostics, + polylineTilingOptions, + circleTilingOptions, register, unregister, ]); diff --git a/examples/basic/src/components/ControlPanel.tsx b/examples/basic/src/components/ControlPanel.tsx index 6259bfe..1f08317 100644 --- a/examples/basic/src/components/ControlPanel.tsx +++ b/examples/basic/src/components/ControlPanel.tsx @@ -5,11 +5,34 @@ interface ControlPanelProps { children: ReactNode; } +/** + * The options of a sample, over the map. + * + * The title is a button that folds the panel away. Until someone presses it, + * the screen width decides (`auto`, in CSS): open beside a desktop map, folded + * to its title on a phone, where an open panel would cover most of the map. + * Deciding in CSS keeps the server-rendered page and the first paint the same. + * Folding only hides the body, so the controls keep their state. + */ export function ControlPanel({ title, children }: ControlPanelProps) { + const [open, setOpen] = useState(null); + const toggle = () => { + setOpen(current => { + if (current !== null) return !current; + // Still `auto`: flip whatever the screen width shows now. + return typeof window !== 'undefined' && window.matchMedia('(max-width: 760px)').matches; + }); + }; + const mode = open === null ? 'auto' : open ? 'open' : 'folded'; return ( -
-

{title}

- {children} +
+ +
{children}
); } diff --git a/examples/basic/src/components/LoadingOverlay.tsx b/examples/basic/src/components/LoadingOverlay.tsx new file mode 100644 index 0000000..b438a3b --- /dev/null +++ b/examples/basic/src/components/LoadingOverlay.tsx @@ -0,0 +1,67 @@ +import { useEffect, useRef, useState } from 'react'; + +/** Shorter loads finish before the dialog appears, so small samples do not flash it. */ +const SHOW_DELAY_MS = 150; + +/** + * "Loading…" over the map while `visible`, put inside `` + * beside the collections it waits for. It does not block the map. + */ +export function LoadingOverlay({ visible }: { visible: boolean }) { + const [shown, setShown] = useState(false); + useEffect(() => { + if (!visible) { + setShown(false); + return; + } + const timer = setTimeout(() => setShown(true), SHOW_DELAY_MS); + return () => clearTimeout(timer); + }, [visible]); + if (!shown) return null; + return ( +
+
+
+
+ ); +} + +/** + * Whether any of a page's collections (``, ``, ``, + * ``) is still putting its states on the map. + * + * Spread `bind(key)` into each collection, one key per collection. A + * collection that stops being rendered while it loads gets no `onAddEnd`, so a + * key not bound in a render stops counting. + */ +export function useLoadingOverlay() { + const [active, setActive] = useState>(() => new Set()); + const bound = new Set(); + const boundRef = useRef(bound); + boundRef.current = bound; + + useEffect(() => { + setActive(current => { + const kept = [...current].filter(key => boundRef.current.has(key)); + return kept.length === current.size ? current : new Set(kept); + }); + }); + + const bind = (key: string) => { + bound.add(key); + return { + onAddStart: () => setActive(current => (current.has(key) ? current : new Set(current).add(key))), + onAddEnd: () => + setActive(current => { + if (!current.has(key)) return current; + const next = new Set(current); + next.delete(key); + return next; + }), + }; + }; + + return { active: active.size > 0, bind }; +} diff --git a/examples/basic/src/components/SamplePageLayout.tsx b/examples/basic/src/components/SamplePageLayout.tsx index 75da81c..c510bb1 100644 --- a/examples/basic/src/components/SamplePageLayout.tsx +++ b/examples/basic/src/components/SamplePageLayout.tsx @@ -1,4 +1,4 @@ -import type { ReactNode } from 'react'; +import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'; import type { SupportedLanguage } from '../samples/sampleRegistry'; import { SamplePageSeo } from '../samples/SamplePageSeo'; import { SampleDocumentation } from './SampleDocumentation'; @@ -16,6 +16,11 @@ export function SamplePageLayout({ language: SupportedLanguage; children?: ReactNode; }) { + const { stageRef, fullscreen, toggleFullscreen } = useMapFullscreen(); + const labels = { + enter: translate(language, { en: 'Full screen', ja: '全画面表示', 'es-419': 'Pantalla completa', de: 'Vollbild', th: 'เต็มหน้าจอ', hi: 'फ़ुल स्क्रीन' }), + exit: translate(language, { en: 'Exit full screen', ja: '全画面表示を終了', 'es-419': 'Salir de pantalla completa', de: 'Vollbild beenden', th: 'ออกจากโหมดเต็มหน้าจอ', hi: 'फ़ुल स्क्रीन से बाहर निकलें' }), + }; // The Hello Map tutorial is a full-page article (its own live demo + steps), // not the standard map-stage + documentation layout. if (page === 'hello-map') { @@ -31,7 +36,24 @@ export function SamplePageLayout({
-
+
+ {/* Camera Sync has its own full screen, for both of its maps. */} + {page !== 'camera-sync' && } {children ?? ( ); } + +/** + * Full screen for the map stage. The Fullscreen API where there is one; where + * there is not (iPhone Safari has none for a div), the stage is fixed over the + * whole page instead. Escape leaves either way. The maps live inside the stage + * (SingletonMaps), so they grow with it. + */ +function useMapFullscreen() { + const stageRef = useRef(null); + const [fullscreen, setFullscreen] = useState(false); + + // Maps that size themselves on window resize only (not every SDK watches its container). + const announceResize = () => requestAnimationFrame(() => window.dispatchEvent(new Event('resize'))); + + const toggleFullscreen = useCallback(() => { + const stage = stageRef.current; + if (!fullscreen) { + setFullscreen(true); + stage?.requestFullscreen?.().catch(() => {}); + } else { + setFullscreen(false); + if (document.fullscreenElement) document.exitFullscreen().catch(() => {}); + } + announceResize(); + }, [fullscreen]); + + useEffect(() => { + if (!fullscreen) return; + // Leaving native full screen (the system back gesture, Escape) ends ours too. + const onChange = () => { + if (!document.fullscreenElement) { + setFullscreen(false); + announceResize(); + } + }; + const onKey = (event: KeyboardEvent) => { + if (event.key === 'Escape' && !document.fullscreenElement) { + setFullscreen(false); + announceResize(); + } + }; + // The page behind must not scroll under the fixed stage. + const overflow = document.body.style.overflow; + document.body.style.overflow = 'hidden'; + document.addEventListener('fullscreenchange', onChange); + document.addEventListener('keydown', onKey); + return () => { + document.body.style.overflow = overflow; + document.removeEventListener('fullscreenchange', onChange); + document.removeEventListener('keydown', onKey); + }; + }, [fullscreen]); + + return { stageRef, fullscreen, toggleFullscreen }; +} diff --git a/examples/basic/src/index.css b/examples/basic/src/index.css index 59e0bf9..98440c6 100644 --- a/examples/basic/src/index.css +++ b/examples/basic/src/index.css @@ -659,8 +659,87 @@ body, .control-panel-title { font-size: 1rem; font-weight: 600; - margin: 0 0 12px; + margin: 0; + color: #333; +} + +/* The title is the button that folds the panel; it must not look like the + panel's own buttons (`.control-panel button`). */ +.control-panel .control-panel-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + width: 100%; + min-height: 0; + margin: 0; + padding: 0; + border: 0; + background: none; color: #333; + text-align: left; + cursor: pointer; +} + +.control-panel .control-panel-header:hover { + background: none; +} + +.control-panel-chevron { + flex: none; + color: #64748b; + transition: transform 140ms ease; +} + +.control-panel-body { + margin-top: 12px; +} + +.control-panel-folded .control-panel-body { + display: none; +} + +.control-panel-folded .control-panel-chevron { + transform: rotate(180deg); +} + +/* Full screen for the map stage (SamplePageLayout). */ +.map-fullscreen-button { + position: absolute; + top: 10px; + right: 10px; + z-index: 1300; + display: grid; + place-items: center; + width: 36px; + height: 36px; + padding: 0; + border: 1px solid #cbd5e1; + border-radius: 6px; + background: rgba(255, 255, 255, 0.95); + color: #1f2937; + box-shadow: 0 1px 4px rgba(15, 23, 42, 0.25); + cursor: pointer; +} + +.map-fullscreen-button:hover { + background: #f1f5f9; +} + +.sample-map-stage.is-fullscreen { + position: fixed; + inset: 0; + z-index: 4000; + width: 100vw; + height: 100vh; + height: 100dvh; + border: 0; + border-radius: 0; +} + +.sample-map-stage:fullscreen { + width: 100%; + height: 100%; } .toggle-control { @@ -866,8 +945,61 @@ body, display: block; } + /* The map is what a phone shows: under the header, one line of title, then a + stage that ends at the bottom of the screen, so the folded panel and the + map's own controls are in view without scrolling. The description stays in + the page for search engines but takes no room here. */ + .sample-page-seo { + padding: 8px 10px 0; + } + + .sample-page-seo h2 { + font-size: 0.95rem; + line-height: 1.3; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .sample-page-seo p { + display: none; + } + + .sample-map-padding { + padding: 6px 8px 8px; + } + .sample-map-stage { - height: clamp(360px, 62vh, 620px); + /* header 58 + title 33 + padding 14 */ + height: clamp(360px, calc(100dvh - 105px), 900px); + } + + /* Folded to its title until opened, and never over most of the map. */ + .control-panel { + left: 8px; + right: auto; + /* Clear of the map's attribution line, which must stay readable. */ + bottom: 30px; + max-width: calc(100% - 16px); + padding: 10px 12px; + } + + .control-panel-title { + font-size: 0.9rem; + } + + .control-panel-auto .control-panel-body { + display: none; + } + + .control-panel-auto .control-panel-chevron { + transform: rotate(180deg); + } + + .control-panel-open { + right: 8px; + max-height: 55%; + overflow-y: auto; } .desktop-sidebar { @@ -1052,3 +1184,41 @@ body, .diagnostic.error { color: #b91c1c; } + +/* "Loading..." while a collection puts its states on the map (LoadingOverlay). */ +.loading-overlay { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + pointer-events: none; + z-index: 1500; +} + +.loading-overlay-dialog { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 20px; + border-radius: 8px; + background: rgba(17, 24, 39, 0.85); + color: white; + font-size: 0.95rem; + box-shadow: 0 2px 12px rgba(0, 0, 0, 0.25); +} + +.loading-overlay-spinner { + width: 16px; + height: 16px; + border: 2px solid rgba(255, 255, 255, 0.35); + border-top-color: white; + border-radius: 50%; + animation: loading-overlay-spin 0.8s linear infinite; +} + +@keyframes loading-overlay-spin { + to { + transform: rotate(360deg); + } +} diff --git a/examples/basic/src/pages/CirclePage.tsx b/examples/basic/src/pages/CirclePage.tsx index d0ec173..cfa680f 100644 --- a/examples/basic/src/pages/CirclePage.tsx +++ b/examples/basic/src/pages/CirclePage.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from 'react'; import { ColorDefaultIcon, Planar, @@ -20,7 +20,6 @@ import { useSampleI18n } from '../samples/i18n'; const CIRCLE_CENTER = createGeoPoint({ latitude: 21.382314, longitude: -157.933097 }); const INIT_CAMERA = { lat: CIRCLE_CENTER.latitude, lng: CIRCLE_CENTER.longitude, zoom: 3 }; const INITIAL_RADIUS_METERS = 5000000.0; -const SUPPRESS_CIRCLE_CLICK_AFTER_MARKER_DRAG_MS = 300; const CIRCLE_COLORS = ['#0000ff', '#ff0000', '#008000', '#00ffff', '#d3d3d3', '#ff00ff']; function rgba(hex: string, alpha: number): string { @@ -57,7 +56,6 @@ export function CirclePage() { const [strokeWidth, setStrokeWidth] = useState(3); const [labelOffset, setLabelOffset] = useState(null); const [cameraTick, setCameraTick] = useState(0); - const suppressCircleClickUntilRef = useRef(0); const { messages, showToast, dismissToast } = useToast(); const radius = useMemo( () => Spherical.computeDistanceBetween(CIRCLE_CENTER, edgePosition), @@ -87,12 +85,6 @@ export function CirclePage() { setEdgePosition(dragged.position); }, []); - const handleMarkerDragEnd = useCallback((dragged: MarkerState) => { - suppressCircleClickUntilRef.current = - Date.now() + SUPPRESS_CIRCLE_CLICK_AFTER_MARKER_DRAG_MS; - setEdgePosition(dragged.position); - }, []); - const circleState = useMemo( () => createCircleState({ @@ -106,7 +98,6 @@ export function CirclePage() { geodesic: true, clickable: true, onClick: () => { - if (Date.now() < suppressCircleClickUntilRef.current) return; setColorIndex((index) => (index + 1) % CIRCLE_COLORS.length); showToast(`Circle clicked - Radius: ${radius.toFixed(0)}m`); }, @@ -152,7 +143,7 @@ export function CirclePage() { draggable onDragStart={handleMarkerMove} onDrag={handleMarkerMove} - onDragEnd={handleMarkerDragEnd} + onDragEnd={handleMarkerMove} /> {labelOffset && (
- + + ); diff --git a/examples/basic/src/pages/PolygonPage.tsx b/examples/basic/src/pages/PolygonPage.tsx index 6dab823..2fa58f4 100644 --- a/examples/basic/src/pages/PolygonPage.tsx +++ b/examples/basic/src/pages/PolygonPage.tsx @@ -11,10 +11,12 @@ import { Toast, useToast } from '../components/Toast'; import { POLYGON_VERTICES } from '../data/storeData'; import { MapViewContainer } from '../MapViewContainer'; import { useSampleI18n } from '../samples/i18n'; +import { LoadingOverlay, useLoadingOverlay } from '../components/LoadingOverlay'; const INIT_CAMERA = { lat: 41.7969, lng: 140.7569, zoom: 16 }; export function PolygonPage() { + const loading = useLoadingOverlay(); const { t } = useSampleI18n(); const [vertices, setVertices] = useState(POLYGON_VERTICES); const [fillOpacity, setFillOpacity] = useState(0.3); @@ -68,7 +70,8 @@ export function PolygonPage() { return ( - + + (INITIAL_POINTS); const setPointsRef = useRef(setPoints); @@ -80,7 +82,8 @@ export function PolylinePage() { return ( - + +

{t( diff --git a/examples/basic/src/pages/circle/antennas/AntennaHorizonsPage.tsx b/examples/basic/src/pages/circle/antennas/AntennaHorizonsPage.tsx new file mode 100644 index 0000000..ae18394 --- /dev/null +++ b/examples/basic/src/pages/circle/antennas/AntennaHorizonsPage.tsx @@ -0,0 +1,75 @@ +import { useEffect, useMemo, useState } from 'react'; +import { createCircleState, createGeoPoint, type CircleEvent, type CircleState } from '@mapconductor/js-sdk-core'; +import { Circles, InfoBubble } from '@mapconductor/js-sdk-react'; +import { MapViewContainer } from '../../../MapViewContainer'; +import { ControlPanel } from '../../../components/ControlPanel'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; + +import { decodeAntennas, type Antenna } from './antennaData'; +const CARRIERS = ['AT&T', 'T-Mobile / Sprint', 'Verizon', 'Others']; +const COLORS = ['37,99,235', '219,39,119', '217,119,6', '100,116,139']; +const STROKE_COLORS = COLORS.map(color => `rgba(${color},0.35)`); +const FILL_COLORS = COLORS.map(color => `rgba(${color},0.65)`); + +// Keep the population out of React's development performance-entry payload. +class CircleSelection implements Iterable { + readonly #states: readonly CircleState[]; + + constructor(states: readonly CircleState[]) { this.#states = states; } + [Symbol.iterator]() { return this.#states[Symbol.iterator](); } +} + +export function AntennaHorizonsPage() { + const [data, setData] = useState(null); + const [error, setError] = useState(''); + const [carriers, setCarriers] = useState([0, 1, 2, 3]); + const [alaska, setAlaska] = useState(false); + const [tap, setTap] = useState(null); + const loading = useLoadingOverlay(); + useEffect(() => { + const abort = new AbortController(); + fetch('/antennas/us-antennas.bin', { signal: abort.signal }).then(r => { + if (!r.ok) throw new Error(`Data download: ${r.status}`); + return r.arrayBuffer(); + }).then(b => setData(decodeAntennas(b))).catch(e => { if (!abort.signal.aborted) setError(String(e)); }); + return () => abort.abort(); + }, []); + const allStates = useMemo(() => { + const onCellClick = (event: CircleEvent) => { + const id = event.state.extra; + if (typeof id === 'string' && id.startsWith('asr-')) setTap(data?.[Number(id.slice(4))] ?? null); + }; + return (data ?? []).map(a => { + const id = `asr-${a.registration}`; + return createCircleState({ + id, center: createGeoPoint(a), radiusMeters: 500, geodesic: true, zIndex: a.registration, + fillColor: FILL_COLORS[a.carrier], strokeColor: STROKE_COLORS[a.carrier], strokeWidth: 0.5, + extra: id, onClick: onCellClick, + }); + }); + }, [data]); + const counts = useMemo(() => { + const result = [0, 0, 0, 0]; + for (const row of data ?? []) result[row.carrier]++; + return result; + }, [data]); + const states = useMemo(() => { + if (carriers.length === CARRIERS.length) return allStates; + if (!data || carriers.length === 0) return []; + return allStates.filter((_, index) => carriers.includes(data[index].carrier)); + }, [allStates, data, carriers]); + const selection = useMemo(() => new CircleSelection(states), [states]); + useEffect(() => { setTap(null); }, [states]); + return setTap(null)}> + + + {tap &&

{CARRIERS[tap.carrier]}
Cell position · Display radius: 500 m
} + +
{error || (!data ? 'Loading OpenCellID data…' : `${states.length.toLocaleString()} / ${data.length.toLocaleString()} circles`)}
+ + {CARRIERS.map((name, index) => )} +

Cell positions shown as 500 m radius circles; not signal coverage. Showing all cells for the selected carriers. MCC 310–314; not a complete tower inventory.

+
Cell tower data from OpenCellID · CC BY-SA 4.0
+
+
; +} diff --git a/examples/basic/src/pages/circle/antennas/antennaData.ts b/examples/basic/src/pages/circle/antennas/antennaData.ts new file mode 100644 index 0000000..0d878ad --- /dev/null +++ b/examples/basic/src/pages/circle/antennas/antennaData.ts @@ -0,0 +1,17 @@ +export interface Antenna { latitude: number; longitude: number; radius: number; registration: number; carrier: number } +export function horizonMeters(height: number): number { + const r = 6378137; + return r * (Math.acos(r / (r + height)) + Math.acos(r / (r + 1.5))); +} +export function decodeAntennas(buffer: ArrayBuffer): Antenna[] { + const v = new DataView(buffer); + if (v.byteLength < 8 || v.getUint32(0, false) !== 0x4d434345) throw new Error('Invalid antenna file'); + const count = v.getUint32(4, true); + if (v.byteLength !== 8 + count * 16) throw new Error('Truncated antenna file'); + return Array.from({ length: count }, (_, i) => { + const p = 8 + i * 16; + const a = { latitude: v.getInt32(p, true) / 100000, longitude: v.getInt32(p + 4, true) / 100000, radius: v.getFloat32(p + 8, true), registration: i, carrier: Math.floor(v.getUint32(p + 12, true) / 1000) }; + if (!Number.isFinite(a.latitude) || Math.abs(a.latitude) > 90 || !Number.isFinite(a.longitude) || Math.abs(a.longitude) > 180 || !(a.radius > 0 && a.radius <= 100000) || a.carrier > 3) throw new Error('Invalid antenna record'); + return a; + }); +} diff --git a/examples/basic/src/pages/circle/boston/BostonTreesPage.tsx b/examples/basic/src/pages/circle/boston/BostonTreesPage.tsx new file mode 100644 index 0000000..655ee45 --- /dev/null +++ b/examples/basic/src/pages/circle/boston/BostonTreesPage.tsx @@ -0,0 +1,357 @@ +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { + CircleTilingOptions, + createCircleState, + createGeoPoint, + type CircleState, + type GeoPoint, +} from '@mapconductor/js-sdk-core'; +import { Circles, InfoBubble } from '@mapconductor/js-sdk-react'; +import { useLocation } from 'react-router-dom'; +import { ControlPanel } from '../../../components/ControlPanel'; +import { MapViewContainer } from '../../../MapViewContainer'; +import { useSampleI18n } from '../../../samples/i18n'; +import { LoadingOverlay, type OverlayPhase } from '../../polygon/boston/BostonOverlays'; +import { StackCheck } from './StackCheck'; +import { loadTrees, nextPaint, TREE_GROUPS, type Tree, type TreeGroup, type TreesDoc } from './bostonTreesData'; + +/** + * Every street and park tree of Boston (about 52,000 circles) drawn with one + * on top of the real map: the City of Boston's tree inventory (see + * treesFile.ts for the file). Each circle is the tree's estimated crown, so it + * keeps its size on the ground as the map zooms. + * + * Past CircleTilingOptions the SDK draws them as raster tiles; "Native" hands + * every one to the map SDK instead, and the time from handing the list over to + * every circle's onAdded is shown for both. Tapping a tree opens an InfoBubble + * at its centre; tapping elsewhere closes it. + */ +type Label = { en: string; ja: string; 'es-419': string; de: string; th: string; hi: string }; + +/** How a tree group is drawn: the outline in the colour, the crown in the same colour at half alpha. */ +export const TREE_STYLES: Record = { + maple: { color: '#E8590C', label: { en: 'Maple', ja: 'カエデ', 'es-419': 'Arce', de: 'Ahorn', th: 'เมเปิล', hi: 'मेपल' } }, + oak: { color: '#8C6239', label: { en: 'Oak', ja: 'ナラ・カシ', 'es-419': 'Roble', de: 'Eiche', th: 'โอ๊ก', hi: 'ओक' } }, + honeylocust: { color: '#FAB005', label: { en: 'Honeylocust', ja: 'アメリカサイカチ', 'es-419': 'Acacia de tres espinas', de: 'Gleditschie', th: 'ฮันนีโลคัสต์', hi: 'हनीलोकस्ट' } }, + linden: { color: '#12B886', label: { en: 'Linden', ja: 'シナノキ', 'es-419': 'Tilo', de: 'Linde', th: 'ลินเดน', hi: 'लिंडन' } }, + elm: { color: '#1C7ED6', label: { en: 'Elm', ja: 'ニレ', 'es-419': 'Olmo', de: 'Ulme', th: 'เอล์ม', hi: 'एल्म' } }, + flowering: { color: '#E64980', label: { en: 'Flowering', ja: '花木', 'es-419': 'De flor', de: 'Blühgehölz', th: 'ไม้ดอก', hi: 'फूलदार' } }, + conifer: { color: '#2B8A3E', label: { en: 'Conifer', ja: '針葉樹', 'es-419': 'Conífera', de: 'Nadelbaum', th: 'สน', hi: 'शंकुधारी' } }, + other: { color: '#868E96', label: { en: 'Other', ja: 'その他', 'es-419': 'Otros', de: 'Sonstige', th: 'อื่น ๆ', hi: 'अन्य' } }, +}; + +/** '#RRGGBB' at `alpha`, as rgba(). */ +function withAlpha(hex: string, alpha: number): string { + const n = parseInt(hex.slice(1), 16); + return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`; +} + +const DEFAULT_CAMERA = { lat: 42.3555, lng: -71.0605, zoom: 15 }; +const TILED = CircleTilingOptions.Default; +const NATIVE = CircleTilingOptions.Disabled; + +/** What the last tap hit: a tree, or nothing (`tree` null). */ +interface Tap { + seq: number; + tree: Tree | null; + point: GeoPoint | null; +} + +/** + * `?camera=lat,lng,zoom` and `?tiling=native` set where the page opens and how + * it starts drawing, so a measurement sees the same view on every provider. + * `?stack=1` adds tiled polygons, tiled roads and a marker round the trees + * (StackCheck); `?trees=0` leaves the trees out, for the picture to compare with. + */ +function initialParams(): { camera: typeof DEFAULT_CAMERA; tiled: boolean; stack: boolean; trees: boolean } { + if (typeof window === 'undefined') return { camera: DEFAULT_CAMERA, tiled: true, stack: false, trees: true }; + const params = new URLSearchParams(window.location.search); + const [lat, lng, zoom] = (params.get('camera') ?? '').split(',').map(Number); + const camera = [lat, lng, zoom].some(n => !Number.isFinite(n)) ? DEFAULT_CAMERA : { lat, lng, zoom }; + return { + camera, + tiled: params.get('tiling') !== 'native', + stack: params.get('stack') === '1', + trees: params.get('trees') !== '0', + }; +} + +function formatRadius(metres: number): string { + return `${metres.toFixed(1)} m`; +} + +export function BostonTreesPage() { + const { t } = useSampleI18n(); + const [initial] = useState(initialParams); + // The page stays mounted when the provider changes; the trees then go onto the other map. + const provider = useLocation().pathname.split('/').filter(Boolean)[0] ?? ''; + const [doc, setDoc] = useState(null); + const [tiled, setTiled] = useState(initial.tiled); + // False while a switch of tiling takes the trees off the map before handing them back. + const [mounted, setMounted] = useState(initial.trees); + const [loadError, setLoadError] = useState(null); + const [tap, setTap] = useState(null); + const [loadMs, setLoadMs] = useState(0); + // Time from handing the list to until every tree's onAdded ran, and until the frame after. + const [addedMs, setAddedMs] = useState(null); + const [frameMs, setFrameMs] = useState(null); + const [progress, setProgress] = useState(null); + // How many times the list has gone onto the map; a measurement waits for the next one. + const [round, setRound] = useState(0); + + useEffect(() => { + let cancelled = false; + const start = performance.now(); + setProgress({ phase: 'download', loaded: 0, total: null }); + loadTrees(p => { if (!cancelled) setProgress(p); }) + .then(async loaded => { + if (cancelled) return; + setLoadMs(performance.now() - start); + // Building the states blocks the main thread; show that phase first. + setProgress({ phase: 'build' }); + await nextPaint(); + if (cancelled) return; + setDoc(loaded); + // Without the trees (`?trees=0`) nothing goes onto the map to wait for. + if (!initial.trees) setProgress(null); + }) + .catch(error => { + if (cancelled) return; + setProgress(null); + setLoadError(String(error)); + }); + return () => { cancelled = true; }; + }, [initial.trees]); + + const onTapRef = useRef((_tree: Tree | null, _point: GeoPoint | null) => {}); + onTapRef.current = (tree, point) => setTap(prev => ({ seq: (prev?.seq ?? 0) + 1, tree, point })); + // A tap on the map that hits no tree closes the bubble. + const onMapClick = useCallback((point: GeoPoint) => onTapRef.current(null, point), []); + + // The overlay stays up until every tree of the list handed over has called + // onAdded. Each hand-over (the first load, and each switch of tiling, which + // takes the trees off the map first) is a new round; calls from an older + // round are ignored. + const commitRef = useRef(0); + const roundRef = useRef<{ round: number; ids: Set; total: number; waiting: boolean }>({ + round: 0, ids: new Set(), total: 0, waiting: false, + }); + const onAllAddedRef = useRef(() => {}); + onAllAddedRef.current = () => { + const added = performance.now() - commitRef.current; + setAddedMs(added); + setProgress(null); + requestAnimationFrame(() => requestAnimationFrame(() => setFrameMs(performance.now() - commitRef.current))); + }; + + // Every tree's state, built once. + const built = useMemo(() => { + if (!doc) return null; + const start = performance.now(); + const onAdded = (state: CircleState) => { + const r = roundRef.current; + if (!r.waiting || r.ids.has(state.id)) return; + r.ids.add(state.id); + if (r.ids.size === r.total) { + r.waiting = false; + onAllAddedRef.current(); + } + }; + const fills = Object.fromEntries(TREE_GROUPS.map(g => [g, withAlpha(TREE_STYLES[g].color, 0.5)])) as Record; + const list = doc.trees.map(tree => createCircleState({ + id: tree.id, + center: createGeoPoint({ latitude: tree.latitude, longitude: tree.longitude }), + radiusMeters: tree.radiusMeters, + fillColor: fills[tree.group], + strokeColor: TREE_STYLES[tree.group].color, + strokeWidth: 1, + zIndex: 0, + onClick: () => onTapRef.current(tree, createGeoPoint({ latitude: tree.latitude, longitude: tree.longitude })), + onAdded, + })); + return { list, buildMs: performance.now() - start }; + }, [doc]); + const states = built?.list ?? null; + const buildMs = built?.buildMs ?? 0; + + // A new round each time the list goes onto a map (also another provider's). + useLayoutEffect(() => { + if (!states || !mounted) return; + commitRef.current = performance.now(); + roundRef.current = { round: roundRef.current.round + 1, ids: new Set(), total: states.length, waiting: true }; + setRound(roundRef.current.round); + setAddedMs(null); + setFrameMs(null); + setProgress({ phase: 'draw' }); + }, [states, mounted, provider]); + + // Switching: take the trees off the map, let that reach it, then hand them back + // with the new tiling, so every tree is added again and calls onAdded again. + const switchTiling = (next: boolean) => { + if (next === tiled || !states || !initial.trees) return; + setTap(null); + setMounted(false); + setTiled(next); + setProgress({ phase: 'draw' }); + void nextPaint().then(() => nextPaint()).then(() => setMounted(true)); + }; + + const counts = useMemo(() => { + const byGroup = Object.fromEntries(TREE_GROUPS.map(g => [g, 0])) as Record; + for (const tree of doc?.trees ?? []) byGroup[tree.group]++; + return byGroup; + }, [doc]); + + const stackCenter = useMemo( + () => createGeoPoint({ latitude: initial.camera.lat, longitude: initial.camera.lng }), + [initial.camera], + ); + + return ( + + {states && mounted && } + {initial.stack && } + {progress && } + {tap?.tree && tap.point && ( + + + + )} + +
+ + +
+ {loadError &&

{loadError}

} + + {doc ? ( +

+ {t({ + en: `${doc.trees.length.toLocaleString()} trees`, + ja: `木 ${doc.trees.length.toLocaleString()} 本`, + 'es-419': `${doc.trees.length.toLocaleString()} árboles`, + de: `${doc.trees.length.toLocaleString()} Bäume`, + th: `ต้นไม้ ${doc.trees.length.toLocaleString()} ต้น`, + hi: `${doc.trees.length.toLocaleString()} पेड़`, + })} +
+ + {t({ + en: `load ${loadMs.toFixed(0)} ms, states ${buildMs.toFixed(0)} ms`, + ja: `読み込み ${loadMs.toFixed(0)} ms・state 作成 ${buildMs.toFixed(0)} ms`, + 'es-419': `carga ${loadMs.toFixed(0)} ms, estados ${buildMs.toFixed(0)} ms`, + de: `Laden ${loadMs.toFixed(0)} ms, States ${buildMs.toFixed(0)} ms`, + th: `โหลด ${loadMs.toFixed(0)} ms สร้าง state ${buildMs.toFixed(0)} ms`, + hi: `लोड ${loadMs.toFixed(0)} ms, state ${buildMs.toFixed(0)} ms`, + })} + {addedMs != null && ( + <> +
+ {t({ + en: `${tiled ? 'Tiles' : 'Native'}: every onAdded ${addedMs.toFixed(0)} ms${frameMs != null ? `, next frame ${frameMs.toFixed(0)} ms` : ''}`, + ja: `${tiled ? 'タイル' : 'ネイティブ'}: 全 onAdded まで ${addedMs.toFixed(0)} ms${frameMs != null ? `・次のフレームまで ${frameMs.toFixed(0)} ms` : ''}`, + 'es-419': `${tiled ? 'Teselas' : 'Nativo'}: todos los onAdded ${addedMs.toFixed(0)} ms${frameMs != null ? `, siguiente cuadro ${frameMs.toFixed(0)} ms` : ''}`, + de: `${tiled ? 'Kacheln' : 'Nativ'}: alle onAdded ${addedMs.toFixed(0)} ms${frameMs != null ? `, nächster Frame ${frameMs.toFixed(0)} ms` : ''}`, + th: `${tiled ? 'ไทล์' : 'เนทีฟ'}: onAdded ครบ ${addedMs.toFixed(0)} ms${frameMs != null ? ` เฟรมถัดไป ${frameMs.toFixed(0)} ms` : ''}`, + hi: `${tiled ? 'टाइलें' : 'नेटिव'}: सभी onAdded ${addedMs.toFixed(0)} ms${frameMs != null ? `, अगला फ़्रेम ${frameMs.toFixed(0)} ms` : ''}`, + })} + + )} +
+

+ ) : ( +

…

+ )} + {tap && ( +

+ {tap.tree + ? `${t(TREE_STYLES[tap.tree.group].label)} · ${formatRadius(tap.tree.radiusMeters)}` + : t({ en: 'No tree here', ja: 'ここに木はありません', 'es-419': 'Aquí no hay árbol', de: 'Hier ist kein Baum', th: 'ไม่มีต้นไม้ตรงนี้', hi: 'यहाँ कोई पेड़ नहीं' })} +

+ )} +

+ {doc ? doc.attribution : null} +
+ {t({ + en: 'A circle is the crown estimated from the trunk diameter (×22), not a measurement.', + ja: '円は幹の直径(×22)から見積もった樹冠で、実測ではありません。', + 'es-419': 'Cada círculo es la copa estimada a partir del diámetro del tronco (×22), no una medición.', + de: 'Ein Kreis ist die aus dem Stammdurchmesser (×22) geschätzte Krone, keine Messung.', + th: 'วงกลมคือทรงพุ่มที่ประมาณจากเส้นผ่านศูนย์กลางลำต้น (×22) ไม่ใช่ค่าที่วัดจริง', + hi: 'वृत्त तने के व्यास (×22) से अनुमानित छत्र है, मापा हुआ नहीं।', + })} +

+
+
+ ); +} + +function TreeLegend({ counts }: { counts: Record }) { + const { t } = useSampleI18n(); + return ( +
    + {TREE_GROUPS.map(group => { + const style = TREE_STYLES[group]; + return ( +
  • + + {t(style.label)} + {counts[group] > 0 && {counts[group].toLocaleString()}} +
  • + ); + })} +
+ ); +} + +/** What a tapped tree carries, shown in an InfoBubble at its centre. */ +function TreeInfo({ tree }: { tree: Tree }) { + const { t } = useSampleI18n(); + const rows: [string, string][] = [ + [t({ en: 'Group', ja: '種別', 'es-419': 'Grupo', de: 'Gruppe', th: 'กลุ่ม', hi: 'समूह' }), t(TREE_STYLES[tree.group].label)], + [t({ en: 'Crown radius', ja: '樹冠の半径', 'es-419': 'Radio de la copa', de: 'Kronenradius', th: 'รัศมีทรงพุ่ม', hi: 'छत्र की त्रिज्या' }), formatRadius(tree.radiusMeters)], + ]; + return ( + + + {rows.map(([key, value]) => ( + + + + + ))} + +
{key}{value}
+ ); +} diff --git a/examples/basic/src/pages/circle/boston/StackCheck.tsx b/examples/basic/src/pages/circle/boston/StackCheck.tsx new file mode 100644 index 0000000..a23df1e --- /dev/null +++ b/examples/basic/src/pages/circle/boston/StackCheck.tsx @@ -0,0 +1,66 @@ +import { useMemo } from 'react'; +import { createGeoPoint, createMarkerState, createPolygonState, createPolylineState, type GeoPoint } from '@mapconductor/js-sdk-core'; +import { Marker, Polygons, Polylines } from '@mapconductor/js-sdk-react'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; + +/** Opaque colours, so a pixel shows which one is on top. */ +export const STACK_SQUARE_COLOR = '#7C3AED'; +export const STACK_ROAD_COLOR = '#00C853'; + +const ROWS = 50; +const STEP = 0.0004; +const SIZE = 0.0003; +// Degrees of latitude the marker stands south of the road of its cell. +const MARKER_BELOW_ROAD = 0.0001; + +/** + * `?stack=1` on the trees page: other overlays where the trees are, to check the stack by pixel. + * Bottom to top it must read: polygon tiles (2,500 squares, enough to be tiled) < the tree + * circles (tiled) < road tiles (2,500 short polylines, tiled too) < the marker. + * + * Each square has a road along its north edge's inner side, so trees, squares and roads overlap + * in every cell; the road of the cell at the centre runs across the marker. + */ +export function StackCheck({ center }: { center: GeoPoint }) { + const loading = useLoadingOverlay(); + const { squares, roads } = useMemo(() => { + const squares = []; + const roads = []; + const p = (a: number, b: number) => createGeoPoint({ latitude: a, longitude: b }); + for (let i = 0; i < ROWS; i++) { + for (let j = 0; j < ROWS; j++) { + const lat = center.latitude - (ROWS / 2) * STEP + i * STEP; + const lng = center.longitude - (ROWS / 2) * STEP + j * STEP; + squares.push(createPolygonState({ + id: `stack-sq-${i}-${j}`, + points: [p(lat, lng), p(lat, lng + SIZE), p(lat + SIZE, lng + SIZE), p(lat + SIZE, lng)], + fillColor: STACK_SQUARE_COLOR, + strokeColor: 'transparent', + strokeWidth: 0, + })); + // From inside the square to past its east edge: over the square, then over the bare map. + const roadLat = lat + SIZE * 0.75; + roads.push(createPolylineState({ + id: `stack-road-${i}-${j}`, + points: [p(roadLat, lng + SIZE * 0.25), p(roadLat, lng + STEP)], + strokeColor: STACK_ROAD_COLOR, + strokeWidth: 4, + })); + } + } + return { squares, roads }; + }, [center]); + const marker = useMemo(() => createMarkerState({ + id: 'stack-marker', + // A little south of the road, so the road runs across the pin's head. + position: createGeoPoint({ latitude: center.latitude + SIZE * 0.75 - MARKER_BELOW_ROAD, longitude: center.longitude + SIZE * 0.6 }), + }), [center]); + return ( + <> + + + + + + ); +} diff --git a/examples/basic/src/pages/circle/boston/bostonTreesData.ts b/examples/basic/src/pages/circle/boston/bostonTreesData.ts new file mode 100644 index 0000000..d1d2b3e --- /dev/null +++ b/examples/basic/src/pages/circle/boston/bostonTreesData.ts @@ -0,0 +1,34 @@ +/** + * Loads the trees the Boston trees page draws (`public/boston/boston-city-trees.bin`): + * every street and park tree in the City of Boston's tree inventory (Analyze + * Boston, *BPRD Trees*), each a circle of its estimated crown. The file format + * is in treesFile.ts; `tools/boston/` builds the file from the official source + * (see its README). + */ +import { readWithProgress, nextPaint, type LoadProgress } from '../../polygon/boston/bostonData'; +import { decodeTrees, type Tree } from './treesFile'; + +export { nextPaint, type LoadProgress }; +export { TREE_GROUPS, type Tree, type TreeGroup } from './treesFile'; + +export interface TreesDoc { + attribution: string; + license: string; + trees: Tree[]; +} + +const SOURCE = { + file: 'boston/boston-city-trees.bin', + attribution: 'Trees: City of Boston (BPRD Trees, PDDL)', + license: 'ODC PDDL 1.0', +}; + +export async function loadTrees(onProgress: (progress: LoadProgress) => void = () => {}): Promise { + const response = await fetch(`${import.meta.env.BASE_URL}${SOURCE.file}`); + if (!response.ok) throw new Error(`${SOURCE.file}: ${response.status}`); + const bytes = await readWithProgress(response, onProgress); + onProgress({ phase: 'decode' }); + // Decoding blocks the main thread; let the overlay show the new phase first. + await nextPaint(); + return { attribution: SOURCE.attribution, license: SOURCE.license, trees: decodeTrees(bytes, 'tree') }; +} diff --git a/examples/basic/src/pages/circle/boston/treesFile.ts b/examples/basic/src/pages/circle/boston/treesFile.ts new file mode 100644 index 0000000..7b67eec --- /dev/null +++ b/examples/basic/src/pages/circle/boston/treesFile.ts @@ -0,0 +1,88 @@ +/** + * The circle file of the Boston trees page (`public/boston/boston-city-trees.bin`), + * read without anything from the page so the tests can load it in Node. + * + * The file carries no ids: this is a circle demo, and a tree's id on the map + * is its index in the file. Nor does it carry species, addresses or dates: + * only where a tree stands, the estimated radius of its crown and its group. + * + * Binary layout: MCPG v2 (see polygon/boston/bostonData.ts) with two more bits + * in `fields`: + * 64 = circles: each record is one circle, `varint radius` (0.1 m, at + * least 1) and its centre as one `svarint dLat, svarint dLng` of the + * file's difference series; no ring count. + * 128 = tree group: u8 after the road class's place, the index in TREE_GROUPS. + * The trees file has fields = 64 | 128, digits = 5, records in Hilbert-curve + * order of their centres: + * u8 group · varint radius · svarint dLat · svarint dLng + */ + +/** The tree groups, in the order the file stores them (a group is its index here). */ +export const TREE_GROUPS = ['maple', 'oak', 'honeylocust', 'linden', 'elm', 'flowering', 'conifer', 'other'] as const; + +export type TreeGroup = (typeof TREE_GROUPS)[number]; + +export interface Tree { + id: string; + group: TreeGroup; + latitude: number; + longitude: number; + /** The estimated crown radius on the ground, in metres (0.1 m steps). */ + radiusMeters: number; +} + +const FIELD_HEIGHT = 1; +const FIELD_USE = 2; +const FIELD_AREA = 4; +const FIELD_NAME = 8; +const FIELD_CLASS = 16; +const FIELD_LINES = 32; +const FIELD_CIRCLES = 64; +const FIELD_TREE = 128; + +/** Decodes an MCPG v2 file of circles (the circles bit set); tree `i` gets the id "-". */ +export function decodeTrees(bytes: Uint8Array, idPrefix: string): Tree[] { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const magic = String.fromCharCode(bytes[0], bytes[1], bytes[2], bytes[3]); + if (magic !== 'MCPG' || view.getUint32(4, true) !== 2) throw new Error('not an MCPG v2 file'); + const count = view.getUint32(8, true); + const fields = bytes[12]; + if (!(fields & FIELD_CIRCLES)) throw new Error('not a file of circles (no circles bit)'); + if (fields & FIELD_LINES) throw new Error('a file of circles cannot also be one of polylines'); + if (!(fields & FIELD_TREE)) throw new Error('no tree group in the file'); + const scale = 10 ** bytes[13]; + let offset = 14; + // Values stay below 2^31 here, so the shifts and the zigzag work on 32-bit ints. + const varint = (): number => { + let value = 0; + let shift = 0; + for (;;) { + const b = bytes[offset++]; + value |= (b & 0x7f) << shift; + if (b < 0x80) return value >>> 0; + shift += 7; + } + }; + const svarint = (): number => { + const v = varint(); + return (v >>> 1) ^ -(v & 1); + }; + const trees: Tree[] = new Array(count); + let lat = 0; + let lng = 0; + for (let i = 0; i < count; i++) { + // Fields a trees file does not carry are still skipped by their layout. + if (fields & FIELD_HEIGHT) varint(); + if (fields & FIELD_USE) offset++; + if (fields & FIELD_AREA) offset++; + if (fields & FIELD_NAME) offset += varint(); + if (fields & FIELD_CLASS) offset++; + const group = TREE_GROUPS[bytes[offset++]]; + if (group === undefined) throw new Error(`tree ${i}: unknown group ${bytes[offset - 1]}`); + const radius = varint(); + lat += svarint(); + lng += svarint(); + trees[i] = { id: `${idPrefix}-${i}`, group, latitude: lat / scale, longitude: lng / scale, radiusMeters: radius / 10 }; + } + return trees; +} diff --git a/examples/basic/src/pages/groundimage/GroundImagePage.tsx b/examples/basic/src/pages/groundimage/GroundImagePage.tsx index 0696cb6..62d0a79 100644 --- a/examples/basic/src/pages/groundimage/GroundImagePage.tsx +++ b/examples/basic/src/pages/groundimage/GroundImagePage.tsx @@ -14,11 +14,13 @@ import { ControlPanel, SliderControl } from '../../components/ControlPanel'; import { Toast, useToast } from '../../components/Toast'; import { MapViewContainer } from '../../MapViewContainer'; import { useSampleI18n } from '../../samples/i18n'; +import { LoadingOverlay, useLoadingOverlay } from '../../components/LoadingOverlay'; const INIT_CAMERA = { lat: -26.479235, lng: 31.306239, zoom: 15 }; const GROUND_IMAGE_URL = `${import.meta.env.BASE_URL}university_of_eswatini.png`; export function GroundImagePage() { + const loading = useLoadingOverlay(); const { t } = useSampleI18n(); const { messages, showToast, dismissToast } = useToast(); const [southWest, setSouthWest] = useState(createGeoPoint({ latitude: -26.484901389754125, longitude: 31.2995982170105 })); @@ -110,7 +112,8 @@ export function GroundImagePage() { return ( - + + >( () => new Set(['marker_0', 'marker_1', 'marker_2']) ); @@ -48,7 +50,8 @@ export function MultipleBubblesPage() { return ( setSelectedMarkerIds(new Set())}> - + + {markers.map(marker => selectedMarkerIds.has(marker.id) ? ( diff --git a/examples/basic/src/pages/map/basic/StoreMapPage.tsx b/examples/basic/src/pages/map/basic/StoreMapPage.tsx index f395c51..613bbb3 100644 --- a/examples/basic/src/pages/map/basic/StoreMapPage.tsx +++ b/examples/basic/src/pages/map/basic/StoreMapPage.tsx @@ -11,6 +11,7 @@ import { InfoBubble, Markers } from '@mapconductor/js-sdk-react'; import { STORES, type StoreInfo } from '../../../data/storeData'; import { MapViewContainer } from '../../../MapViewContainer'; import { StoreInfoView } from './StoreInfoView'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; const INIT_CAMERA = { lat: 21.382314, lng: -157.933097, zoom: 10 }; @@ -22,6 +23,7 @@ const STORE_ICON_URLS: Record = { }; export function MapPage() { + const loading = useLoadingOverlay(); // Gets the mapViewState for controll map view. const [mapViewState, setMapViewState] = useState> | null>(null); // Holds the selected marker state. @@ -76,7 +78,8 @@ export function MapPage() { return ( setSelectedMarker(null)}> - + + {selectedMarker && ( diff --git a/examples/basic/src/pages/map/camerasync/camera-sync-page.css b/examples/basic/src/pages/map/camerasync/camera-sync-page.css index a9281bd..9bdb1f7 100644 --- a/examples/basic/src/pages/map/camerasync/camera-sync-page.css +++ b/examples/basic/src/pages/map/camerasync/camera-sync-page.css @@ -263,17 +263,35 @@ width: 100%; } + /* Two maps share a phone screen: keep only the selector and the numbers, + so most of each map stays in view. */ .camera-sync-provider { - width: min(86%, 300px); + top: 6px; + left: 6px; + width: auto; + max-width: calc(100% - 12px); + padding: 3px; + gap: 0; + font-size: 0; + } + + .camera-sync-provider select { + min-height: 28px; + font-size: 0.8rem; } .camera-sync-info { - max-width: calc(100% - 20px); + left: 6px; + bottom: 6px; + min-width: 0; + max-width: calc(100% - 12px); + padding: 4px 7px; grid-template-columns: repeat(2, minmax(0, auto)); column-gap: 10px; + font-size: 0.68rem; } .camera-sync-info strong { - grid-column: 1 / -1; + display: none; } } diff --git a/examples/basic/src/pages/map/flyto/FlyToPage.tsx b/examples/basic/src/pages/map/flyto/FlyToPage.tsx index 1df6013..e32caf2 100644 --- a/examples/basic/src/pages/map/flyto/FlyToPage.tsx +++ b/examples/basic/src/pages/map/flyto/FlyToPage.tsx @@ -12,6 +12,7 @@ import { Markers, Polyline } from '@mapconductor/js-sdk-react'; import { ControlPanel } from '../../../components/ControlPanel'; import { MapViewContainer } from '../../../MapViewContainer'; import { useSampleI18n } from '../../../samples/i18n'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; const INIT_CAMERA = { lat: 35.0, lng: 0.0, zoom: 3 }; @@ -34,6 +35,7 @@ const CONNECTIONS = [ ] as const; function FlyToContent({ mapViewState }: { mapViewState: MapViewStateInterface> }) { + const loading = useLoadingOverlay(); const { t } = useSampleI18n(); const [icons, setIcons] = useState | null>(null); const [geodesic, setGeodesic] = useState(false); @@ -82,7 +84,8 @@ function FlyToContent({ mapViewState }: { mapViewState: MapViewStateInterface {polylines.map(polyline => )} - + + ; + +let dropCount = 0; + +/** + * タップした地点(赤)と、その投影座標を緯度経度へ戻した地点(青・小)に落とすマーカー。 + * + * 投影と逆投影が合っていれば、青は赤のピン先に重なる。タップのたびに新しい id に + * するので、Drop がそのつど再生される。青は zIndex 1 にして、赤より手前に描く。 + * 青は `iconSize` で小さくしている(android / ios の同ページと同じ)。 + */ +function dropMarkers(tapped: GeoPoint, holder: Holder | null): MarkerState[] { + dropCount += 1; + const markers = [ + createMarkerState({ + id: `projected-tapped-${dropCount}`, + position: tapped, + icon: new ColorDefaultIcon({ fillColor: '#e53935', label: 'T' }), + animation: MarkerAnimation.Drop, + }), + ]; + const projected = holder?.toProjectedPoint(tapped) ?? null; + const back = projected && holder ? holder.fromProjectedPoint(projected) : null; + if (back) { + markers.push(createMarkerState({ + id: `projected-back-${dropCount}`, + position: back, + icon: new ColorDefaultIcon({ fillColor: '#1e88e5', label: 'P', iconSize: 28 }), + animation: MarkerAnimation.Drop, + zIndex: 1, + })); + } + return markers; +} + +function formatSystem(system: MapCoordinateSystem): string { + return `${system.code ?? '(engine-defined)'} (${system.unit})`; +} + +/** + * 1 地点ぶん: 緯度経度、投影座標(地図エンジンの座標系での x / y。画面座標ではない)、 + * その x / y を緯度経度へ戻した値と元の地点とのずれ。ずれが 0 に近ければ往復できている。 + */ +function ProjectionLines({ label, point, holder, unavailable }: { + label: string; + point: GeoPoint | null; + holder: Holder | null; + unavailable: string; +}) { + const projected = point && holder ? holder.toProjectedPoint(point) : null; + const back = projected && holder ? holder.fromProjectedPoint(projected) : null; + const error = point && back ? Spherical.computeDistanceBetween(point, back) : null; + return ( + <> +

{label}: {point?.toUrlValue(6) ?? unavailable}

+

+   Projected: {projected ? `x=${projected.x.toFixed(2)}, y=${projected.y.toFixed(2)}` : unavailable} +

+

+   Back: {back?.toUrlValue(6) ?? unavailable}{error !== null ? ` (error ${error.toFixed(3)} m)` : ''} +

+ + ); +} + +function ProjectedCoordinatesContent({ holder, center, tapped }: { + holder: Holder | null; + center: GeoPoint | null; + tapped: GeoPoint | null; +}) { + const { t } = useSampleI18n(); + const unavailable = t({ + en: 'Unavailable', + ja: '取得できません', + 'es-419': 'No disponible', + de: 'Nicht verfügbar', + th: 'ไม่มีข้อมูล', + hi: 'उपलब्ध नहीं', + }); + + return ( + +

+ {t({ + en: 'Tap the map to project the tapped point.', + ja: '地図をタップすると、その地点の投影座標を表示します。', + 'es-419': 'Toca el mapa para proyectar el punto tocado.', + de: 'Tippen Sie auf die Karte, um den angetippten Punkt zu projizieren.', + th: 'แตะแผนที่เพื่อฉายพิกัดของจุดที่แตะ', + hi: 'टैप किए गए बिंदु को प्रक्षेपित करने के लिए मैप पर टैप करें।', + })} +

+

+ {t({ + en: 'Markers: red T = tapped, blue P = back from the projected point.', + ja: 'マーカー: 赤の T がタップ地点、青の P が投影座標から戻した地点。', + 'es-419': 'Marcadores: T rojo = punto tocado, P azul = de vuelta desde el punto proyectado.', + de: 'Marker: rotes T = angetippt, blaues P = aus dem projizierten Punkt zurückgerechnet.', + th: 'หมุด: T สีแดง = จุดที่แตะ, P สีน้ำเงิน = แปลงกลับจากพิกัดที่ฉาย', + hi: 'मार्कर: लाल T = टैप किया गया बिंदु, नीला P = प्रक्षेपित बिंदु से वापस बदला गया।', + })} +

+

+ {t({ en: 'Coordinate system', ja: '座標系', 'es-419': 'Sistema de coordenadas', de: 'Koordinatensystem', th: 'ระบบพิกัด', hi: 'निर्देशांक प्रणाली' })}: {holder ? formatSystem(holder.coordinateSystem) : unavailable} +

+ + +
+ ); +} + +export function ProjectedCoordinatesPage() { + const [state, setState] = useState> | null>(null); + const [center, setCenter] = useState(null); + const [tapped, setTapped] = useState(null); + // ホルダは地図が出来てから付く。描画のたびに読むと、付いた後に描き直しが + // 起きず取り残されるので、地図の通知で取り直して state に持つ。 + const [holder, setHolder] = useState(null); + const [markers, setMarkers] = useState([]); + // Some engines send no camera event when the map comes up: take the initial + // values from the state, retrying until the holder is attached. + useEffect(() => { + if (!state || holder) return; + const timer = window.setInterval(() => { + const attached = state.getMapViewHolder(); + if (!attached) return; + setHolder(attached); + setCenter(current => current ?? state.cameraPosition.position); + }, 300); + return () => window.clearInterval(timer); + }, [state, holder]); + const refresh = (camera: MapCameraPosition) => { + setHolder(state?.getMapViewHolder() ?? null); + setCenter(camera.position); + }; + + return ( + { + const current = state?.getMapViewHolder() ?? null; + setHolder(current); + setTapped(point); + setMarkers(dropMarkers(point, current)); + }} + > + {markers.map(marker => )} + + + ); +} diff --git a/examples/basic/src/pages/map/tilt/TiltPage.tsx b/examples/basic/src/pages/map/tilt/TiltPage.tsx index aad868b..c030ef4 100644 --- a/examples/basic/src/pages/map/tilt/TiltPage.tsx +++ b/examples/basic/src/pages/map/tilt/TiltPage.tsx @@ -15,6 +15,7 @@ import { Circle, Markers } from '@mapconductor/js-sdk-react'; import { ControlPanel, SliderControl } from '../../../components/ControlPanel'; import { MapViewContainer } from '../../../MapViewContainer'; import { useSampleI18n } from '../../../samples/i18n'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; /** * ほとんどのプロバイダは 60 度で頭打ちになるが、ArcGIS だけは 90 度近くまで実際に傾く。 @@ -167,13 +168,15 @@ function TiltContent({ mapViewState }: { mapViewState: MapViewStateInterface> | null>(null); return ( {ANCHOR_CIRCLES.map(circle => ( ))} - + + {mapViewState && } ); diff --git a/examples/basic/src/pages/marker/animation/MarkerAnimationPage.tsx b/examples/basic/src/pages/marker/animation/MarkerAnimationPage.tsx index fe6e5d2..3cf7135 100644 --- a/examples/basic/src/pages/marker/animation/MarkerAnimationPage.tsx +++ b/examples/basic/src/pages/marker/animation/MarkerAnimationPage.tsx @@ -3,6 +3,7 @@ import { Markers } from '@mapconductor/js-sdk-react'; import { ControlPanel } from '../../../components/ControlPanel'; import { MapViewContainer } from '../../../MapViewContainer'; import { useSampleI18n } from '../../../samples/i18n'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; // android の AnimationPageViewModel.kt / ios の AnimationPageViewModel.swift と同一仕様: // Drop / Bounce のラベルを持つ 2 マーカーを表示し、タップすると各マーカーに @@ -24,10 +25,12 @@ const MARKERS = SPOTS.map(spot => ); export function MarkerAnimationPage() { + const loading = useLoadingOverlay(); const { t } = useSampleI18n(); return ( - + + @@ -328,7 +328,8 @@ export function MarkerIconsPage() { return ( setSelected(null)}> - + + {typeof selected?.extra === 'string' && (
{selected.extra}
diff --git a/examples/basic/src/pages/marker/labelposition/MarkerLabelPositionPage.tsx b/examples/basic/src/pages/marker/labelposition/MarkerLabelPositionPage.tsx index f6c646a..ff83290 100644 --- a/examples/basic/src/pages/marker/labelposition/MarkerLabelPositionPage.tsx +++ b/examples/basic/src/pages/marker/labelposition/MarkerLabelPositionPage.tsx @@ -7,6 +7,7 @@ import { } from '@mapconductor/js-sdk-core'; import { InfoBubble, Markers } from '@mapconductor/js-sdk-react'; import { MapViewContainer } from '../../../MapViewContainer'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; // 信州大学(松本キャンパス)周辺に 3 × 3 で並べ、それぞれ違う labelPosition を付ける。 const CENTER = { latitude: 36.2526, longitude: 137.9828 }; @@ -20,6 +21,7 @@ const POSITIONS: MarkerLabelPosition[][] = [ ]; export function MarkerLabelPositionPage() { + const loading = useLoadingOverlay(); const [selectedId, setSelectedId] = useState(null); const markers = useMemo( () => @@ -47,7 +49,8 @@ export function MarkerLabelPositionPage() { return ( setSelectedId(null)}> - + + {selected ? ( labelPosition: "{selected.extra as string}" diff --git a/examples/basic/src/pages/marker/postoffice/PostOfficePage.tsx b/examples/basic/src/pages/marker/postoffice/PostOfficePage.tsx index 965b2e9..dc4700f 100644 --- a/examples/basic/src/pages/marker/postoffice/PostOfficePage.tsx +++ b/examples/basic/src/pages/marker/postoffice/PostOfficePage.tsx @@ -16,6 +16,7 @@ import { } from './PostOfficeMapProvider'; import { browserPostOfficeDataSource, type PostOfficeDataSource } from './postOfficeData'; import { usePostOfficeMarkers } from './usePostOfficeMarkers'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; const INITIAL_CAMERA = createMapCameraPosition({ position: createGeoPoint({ latitude: 35.68049, longitude: 139.76669 }), @@ -36,6 +37,7 @@ function PostOfficeContent({ renderMapView: PostOfficeMapContentProps['renderMapView']; dataSource: PostOfficeDataSource; }) { + const loading = useLoadingOverlay(); const { t } = useSampleI18n(); const [selected, setSelected] = useState(null); const selectMarker = useCallback((marker: MarkerState) => setSelected(marker), []); @@ -45,7 +47,8 @@ function PostOfficeContent({ return renderMapView( <> - + + {selected && } ; }); - const markerImagePromise = loadImage(`${baseUrl}postoffice/postoffice.webp`); const clusterImagePromise = includeClusterImage ? loadImage(`${baseUrl}postoffice/cluster_red.png`) : Promise.resolve(undefined); - const [records, markerImage, clusterImage] = await Promise.all([ - recordsPromise, - markerImagePromise, - clusterImagePromise, - ]); - return { records, markerImage, clusterImage }; + const [records, clusterImage] = await Promise.all([recordsPromise, clusterImagePromise]); + return { records, markerImageUrl: `${baseUrl}postoffice/postoffice.webp`, clusterImage }; }, }; } diff --git a/examples/basic/src/pages/marker/postoffice/usePostOfficeMarkers.ts b/examples/basic/src/pages/marker/postoffice/usePostOfficeMarkers.ts index 95222aa..2e3e08e 100644 --- a/examples/basic/src/pages/marker/postoffice/usePostOfficeMarkers.ts +++ b/examples/basic/src/pages/marker/postoffice/usePostOfficeMarkers.ts @@ -34,7 +34,7 @@ export function usePostOfficeMarkers( dataSource.load(includeClusterImage).then(assets => { if (!active) return; setRecords(assets.records); - setIcon(new ImageIcon(assets.markerImage, { scale: iconScale })); + setIcon(new ImageIcon(assets.markerImageUrl, { scale: iconScale })); setClusterImage(assets.clusterImage ?? null); }).catch(reason => { if (active) setError(String(reason)); diff --git a/examples/basic/src/pages/marker/streettree/StreetTreePage.tsx b/examples/basic/src/pages/marker/streettree/StreetTreePage.tsx index b9b5ecf..527d90c 100644 --- a/examples/basic/src/pages/marker/streettree/StreetTreePage.tsx +++ b/examples/basic/src/pages/marker/streettree/StreetTreePage.tsx @@ -1,4 +1,4 @@ -import { useCallback, useState } from 'react'; +import { useCallback, useRef, useState } from 'react'; import { MarkerTilingOptions, type MapDesignTypeInterface, @@ -13,8 +13,21 @@ import { useSampleI18n } from '../../../samples/i18n'; import { StreetTreeInfoBubble } from './StreetTreeInfoBubble'; import { browserStreetTreeDataSource } from './streetTreeData'; import { useStreetTreeMarkers } from './useStreetTreeMarkers'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; -const INIT_CAMERA = { lat: 35.6812, lng: 139.7671, zoom: 11 }; +const DEFAULT_CAMERA = { lat: 35.6812, lng: 139.7671, zoom: 11 }; + +/** + * `?camera=lat,lng,zoom` で開く場所を変えられる。ラベルの付き方を同じ場所で見比べるためのもの + * (android-sdk のサンプルの `camera` extra と同じ)。 + */ +function initialCamera(): { lat: number; lng: number; zoom: number } { + if (typeof window === 'undefined') return DEFAULT_CAMERA; + const value = new URLSearchParams(window.location.search).get('camera'); + const [lat, lng, zoom] = (value ?? '').split(',').map(Number); + if ([lat, lng, zoom].some(n => !Number.isFinite(n))) return DEFAULT_CAMERA; + return { lat, lng, zoom }; +} const MARKER_TILING_OPTIONS: MarkerTilingOptions = { ...MarkerTilingOptions.Default, @@ -27,11 +40,15 @@ const MARKER_TILING_OPTIONS: MarkerTilingOptions = { }; export function StreetTreePage() { + const loading = useLoadingOverlay(); const { t } = useSampleI18n(); const [selected, setSelected] = useState(null); const selectMarker = useCallback((marker: MarkerState) => setSelected(marker), []); - const { error, markerStates, trees, species, isLoading } = - useStreetTreeMarkers(browserStreetTreeDataSource, selectMarker); + const mapState = useRef> | null>(null); + const currentCamera = useCallback(() => mapState.current?.cameraPosition ?? null, []); + const { error, markerStates, trees, species, isLoading, relabel } = + useStreetTreeMarkers(browserStreetTreeDataSource, selectMarker, currentCamera); + const [startCamera] = useState(initialCamera); /** * Swaps in a basemap stripped down to what a tree map needs: land, water, @@ -45,6 +62,7 @@ export function StreetTreePage() { */ const applyTreeStyle = useCallback( (state: MapViewStateInterface>) => { + mapState.current = state; const maplibre = state as unknown as { mapDesignType?: unknown }; if (!('mapDesignType' in maplibre)) return; const design = state.mapDesignType as { styleJsonURL?: string } | undefined; @@ -67,12 +85,14 @@ export function StreetTreePage() { return ( setSelected(null)} + onCameraMoveEnd={relabel} onStateReady={applyTreeStyle} > - + + {selected && } (); + + private keysOf(r: Rect): string[] { + const keys: string[] = []; + const cell = PlacedRects.CELL; + for (let cx = Math.floor(r.left / cell); cx <= Math.floor(r.right / cell); cx++) { + for (let cy = Math.floor(r.top / cell); cy <= Math.floor(r.bottom / cell); cy++) keys.push(`${cx},${cy}`); + } + return keys; + } + + overlaps(r: Rect): boolean { + return this.keysOf(r).some(key => this.cells.get(key)?.some(other => overlaps(other, r)) === true); + } + + add(r: Rect): void { + for (const key of this.keysOf(r)) { + const list = this.cells.get(key); + if (list) list.push(r); + else this.cells.set(key, [r]); + } + } +} + +export interface ChooseLabelsParams { + trees: readonly StreetTree[]; + bounds: GeoRectBounds; + zoom: number; + /** ラベルのアイコンに掛かる倍率(タイルの iconScaleCallback と同じ値)。 */ + scale: number; + dotSize: number; + /** 点とラベルのすき間(SDK の配置と同じ値)。 */ + gap: number; + labelSize: (text: string, vertical: boolean) => { width: number; height: number }; + /** 前回の道路名 -> 向き。 */ + previousSides?: ReadonlyMap; +} + +/** + * 画面内の街路樹のうち、どれにどちら向きのラベルを付けるか。android-sdk の + * `StreetTreeLabels`、ios-sdk の `StreetTreeLabels` と同じ規則。 + * + * - 向きは**道路ごとに 1 つ**。道路の木の並びが横向きなら上か下、縦向きなら右か左 + * (道路に直交する向き)。同じ通りのラベルが揃って並ぶ。 + * - 2 つの候補のうち、置けるラベルが多い方を選ぶ。木の多い道路から決める。 + * ただし前回その道路で選んだ向き(`previousSides`)は、もう一方の 2/3 以上置けるなら + * そのまま使う。見えている範囲が変わるたびに数の多い方へ乗り換えると、パンするたびに + * ラベルが上下や左右で入れ替わる。 + * - すでに置いたラベルか、ほかの木の点の中心を覆うラベルは付けない(その木は点のまま)。 + * ラベルは点の後に描かれるので、端が隣の点に少しかかるのは許す。 + * - 上下に置くラベルは縦書き(`isVerticalSide`)なので、縦書きの寸法で測る。 + * + * 座標はカメラのズームでの CSS px。返り値は `trees` の添字 -> 向き。 + */ +export function chooseLabels(params: ChooseLabelsParams): Map { + const { trees, bounds, zoom, scale, dotSize, gap: gapPx, labelSize, previousSides } = params; + const southWest = bounds.southWest; + const northEast = bounds.northEast; + const sides = new Map(); + if (!southWest || !northEast) return sides; + const world = 256 * 2 ** zoom; + const x = (longitude: number) => ((longitude + 180) / 360) * world; + const y = (latitude: number) => { + const phi = (latitude * Math.PI) / 180; + return ((1 - Math.log(Math.tan(phi) + 1 / Math.cos(phi)) / Math.PI) / 2) * world; + }; + + // 道路ごとの、画面内の木 + const byRoad = new Map(); + trees.forEach((tree, index) => { + if (tree.latitude < southWest.latitude || tree.latitude > northEast.latitude) return; + if (tree.longitude < southWest.longitude || tree.longitude > northEast.longitude) return; + const members = byRoad.get(tree.roadName); + if (members) members.push(index); + else byRoad.set(tree.roadName, [index]); + }); + + const placed = new PlacedRects(); + const radius = (dotSize * scale) / 2; + const gap = gapPx * scale; + + // 画面内のすべての点の中心。ラベルがほかの木の点の中心を覆わないかを見る + const dots = new PlacedRects(); + for (const members of byRoad.values()) { + for (const index of members) { + const cx = x(trees[index].longitude); + const cy = y(trees[index].latitude); + dots.add({ left: cx - 0.5, top: cy - 0.5, right: cx + 0.5, bottom: cy + 0.5 }); + } + } + + const roads = [...byRoad.entries()].sort((a, b) => b[1].length - a[1].length); + for (const [road, members] of roads) { + const xs = members.map(index => x(trees[index].longitude)); + const ys = members.map(index => y(trees[index].latitude)); + + // 並びの向き(主成分) + const mx = xs.reduce((sum, v) => sum + v, 0) / xs.length; + const my = ys.reduce((sum, v) => sum + v, 0) / ys.length; + let sxx = 0; + let syy = 0; + let sxy = 0; + for (let i = 0; i < xs.length; i++) { + const dx = xs[i] - mx; + const dy = ys[i] - my; + sxx += dx * dx; + syy += dy * dy; + sxy += dx * dy; + } + const angle = 0.5 * Math.atan2(2 * sxy, sxx - syy); + const horizontal = Math.abs(Math.cos(angle)) >= Math.abs(Math.sin(angle)); + const candidates: LabelSide[] = horizontal ? ['top', 'bottom'] : ['right', 'left']; + + // 道路に沿って並べてから置いていく + const order = xs.map((_, i) => i) + .sort((a, b) => (xs[a] * Math.cos(angle) + ys[a] * Math.sin(angle)) - (xs[b] * Math.cos(angle) + ys[b] * Math.sin(angle))); + + const rect = (i: number, side: LabelSide): Rect => { + const size = labelSize(trees[members[i]].species, isVerticalSide(side)); + const w = size.width * scale; + const h = size.height * scale; + const cx = xs[i]; + const cy = ys[i]; + switch (side) { + case 'right': return { left: cx + radius + gap, top: cy - h / 2, right: cx + radius + gap + w, bottom: cy + h / 2 }; + case 'left': return { left: cx - radius - gap - w, top: cy - h / 2, right: cx - radius - gap, bottom: cy + h / 2 }; + case 'top': return { left: cx - w / 2, top: cy - radius - gap - h, right: cx + w / 2, bottom: cy - radius - gap }; + case 'bottom': return { left: cx - w / 2, top: cy + radius + gap, right: cx + w / 2, bottom: cy + radius + gap + h }; + } + }; + + const attempt = (side: LabelSide): Array<[number, Rect]> => { + const own = new PlacedRects(); + const accepted: Array<[number, Rect]> = []; + for (const i of order) { + const r = rect(i, side); + if (placed.overlaps(r) || own.overlaps(r) || dots.overlaps(r)) continue; + own.add(r); + accepted.push([i, r]); + } + return accepted; + }; + + const attempts = candidates.map(side => [side, attempt(side)] as const); + const most = attempts.reduce((a, b) => (b[1].length > a[1].length ? b : a)); + const kept = attempts.find(([side]) => side === previousSides?.get(road)); + const best = kept && kept[1].length * 3 >= most[1].length * 2 ? kept : most; + for (const [i, r] of best[1]) { + placed.add(r); + sides.set(members[i], best[0]); + } + } + return sides; +} diff --git a/examples/basic/src/pages/marker/streettree/treeIcons.ts b/examples/basic/src/pages/marker/streettree/treeIcons.ts index 5b3dc7e..772b1eb 100644 --- a/examples/basic/src/pages/marker/streettree/treeIcons.ts +++ b/examples/basic/src/pages/marker/streettree/treeIcons.ts @@ -1,4 +1,70 @@ import { ImageIcon } from '@mapconductor/js-sdk-core'; +import { isVerticalSide, type LabelSide } from './streetTreeLabels'; + +/** ラベルの文字の大きさ(CSS px)。ラベルの重なり判定もこの値で測る。 */ +export const LABEL_TEXT_PX = 11; + +/** ラベルの字体。SDK はこれを canvas の font と SVG の font-family にそのまま使う。 */ +const LABEL_TYPE_FACE = 'sans-serif'; + +/** + * 縁取りの太さ(CSS px)。SDK は `max(アイコンの scale, 2)` で、ラベルの幅と高さにこの 2 倍を足す。 + * 点とラベルのすき間も同じ値になる(`max(縁取り, 点の大きさ × 0.05)`)。 + */ +export const LABEL_OUTLINE_PX = 2; + +const labelSizes = new Map(); +let measureContext: CanvasRenderingContext2D | null = null; + +/** + * ラベルの幅と高さ(CSS px、縁取りを含む)。樹種名と向きごとに 1 回だけ測る。 + * SDK と同じ測り方(縦書きは 1 文字 1em に積み、列の幅は字の幅と 1em の大きい方)。 + */ +export function labelSize(text: string, vertical: boolean): { width: number; height: number } { + const key = `${vertical ? 'v' : 'h'}/${text}`; + const cached = labelSizes.get(key); + if (cached) return cached; + measureContext ??= document.createElement('canvas').getContext('2d'); + const measure = (value: string) => { + if (!measureContext) return value.length * LABEL_TEXT_PX * 0.6; + measureContext.font = `${LABEL_TEXT_PX}px ${LABEL_TYPE_FACE}`; + return measureContext.measureText(value).width; + }; + const outline = LABEL_OUTLINE_PX * 2; + let size: { width: number; height: number }; + if (vertical) { + const glyphs = Array.from(text); + let column = LABEL_TEXT_PX; + for (const glyph of glyphs) column = Math.max(column, measure(glyph)); + size = { width: Math.ceil(column) + outline, height: glyphs.length * LABEL_TEXT_PX + outline }; + } else { + size = { width: measure(text) + outline, height: LABEL_TEXT_PX + outline }; + } + labelSizes.set(key, size); + return size; +} + +/** + * 点の `side` 側に樹種名を添えたアイコン。 + * + * SDK の `ImageIcon` のラベルを使う。点の画像は作り直さない -- タイル描画は点の画像と + * 文字を別々に描くので、ラベル付きのアイコンをいくつ作っても点の画像は 1 枚のまま。 + * android-sdk / ios-sdk の `StreetTreeIcons.labelled` と同じ。 + */ +export function labelledIcon(dot: ImageIcon, text: string, side: LabelSide): ImageIcon { + return new ImageIcon(dot.image, { + iconSize: dot.iconSize, + anchor: { x: 0.5, y: 0.5 }, + infoAnchor: { x: 0.5, y: 0 }, + label: text, + labelTextColor: '#282828', + labelTextSize: LABEL_TEXT_PX, + labelTypeFace: LABEL_TYPE_FACE, + labelStrokeColor: '#FFFFFF', + labelPosition: side, + labelWritingMode: isVerticalSide(side) ? 'vertical-rl' : 'horizontal-tb', + }); +} /** * One coloured dot per species, shared by every tree of that species. diff --git a/examples/basic/src/pages/marker/streettree/useStreetTreeMarkers.ts b/examples/basic/src/pages/marker/streettree/useStreetTreeMarkers.ts index d8e7a9a..7fe2555 100644 --- a/examples/basic/src/pages/marker/streettree/useStreetTreeMarkers.ts +++ b/examples/basic/src/pages/marker/streettree/useStreetTreeMarkers.ts @@ -1,24 +1,62 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { createGeoPoint, + createGeoRectBounds, createMarkerState, + type GeoRectBounds, type ImageIcon, + type MapCameraPosition, type MarkerState, } from '@mapconductor/js-sdk-core'; -import { createSpeciesIcons } from './treeIcons'; +import { createSpeciesIcons, LABEL_OUTLINE_PX, labelledIcon, labelSize } from './treeIcons'; +import { chooseLabels, type LabelSide } from './streetTreeLabels'; import type { StreetTree, StreetTreeDataSource } from './streetTreeData'; +/** これより寄ったら樹種名を付ける。 */ +export const LABEL_MIN_ZOOM = 16; + +/** 点の大きさ(CSS px)。 */ +const DOT_SIZE = 10; + +/** zoom > 15 の iconScaleCallback と同じ値。ラベルの重なりはこの大きさで測る。 */ +export const LABEL_ICON_SCALE = 1.4; + +/** + * 見えている範囲が分からないときに使う、中心から上下左右 `AROUND_CENTER_PX` の箱。 + * web の地図は開いた直後のカメラに見えている範囲を持たないことがある。画面より広めに + * 取っても、画面の外の木にラベルが付くだけで害は無い。 + */ +const AROUND_CENTER_PX = 1024; + +function aroundCenter(camera: MapCameraPosition): GeoRectBounds { + const world = 256 * 2 ** camera.zoom; + const { latitude, longitude } = camera.position; + const x = ((longitude + 180) / 360) * world; + const phi = (latitude * Math.PI) / 180; + const y = ((1 - Math.log(Math.tan(phi) + 1 / Math.cos(phi)) / Math.PI) / 2) * world; + const lng = (px: number) => (px / world) * 360 - 180; + const lat = (py: number) => (Math.atan(Math.sinh(Math.PI * (1 - (2 * py) / world))) * 180) / Math.PI; + return createGeoRectBounds({ + southWest: createGeoPoint({ latitude: lat(y + AROUND_CENTER_PX), longitude: lng(x - AROUND_CENTER_PX) }), + northEast: createGeoPoint({ latitude: lat(y - AROUND_CENTER_PX), longitude: lng(x + AROUND_CENTER_PX) }), + }); +} + interface StreetTreeMarkerResult { error: string | null; markerStates: MarkerState[]; trees: StreetTree[] | null; species: string[] | null; isLoading: boolean; + /** カメラが止まったら呼ぶ。見えている木に樹種名を付け直す。 */ + relabel: (camera: MapCameraPosition) => void; } export function useStreetTreeMarkers( dataSource: StreetTreeDataSource, onMarkerClick: (marker: MarkerState) => void, + /** 開いた直後の位置。web の地図は開いたときにカメラの停止を知らせないことがある。 */ + currentCamera?: () => MapCameraPosition | null, ): StreetTreeMarkerResult { const [trees, setTrees] = useState(null); const [species, setSpecies] = useState(null); @@ -31,7 +69,7 @@ export function useStreetTreeMarkers( if (!active) return; setTrees(data.trees); setSpecies(data.species); - setIcons(createSpeciesIcons(data.species.length)); + setIcons(createSpeciesIcons(data.species.length, DOT_SIZE)); }).catch(reason => { if (active) setError(String(reason)); }); @@ -50,5 +88,59 @@ export function useStreetTreeMarkers( [icons, onMarkerClick, trees], ); - return { error, markerStates, trees, species, isLoading: trees === null && error === null }; + // 付けているラベル(木の添字 -> 向き)と、道路ごとの前回の向き。 + const labelled = useRef(new Map()); + const roadSides = useRef(new Map()); + const labelIcons = useRef(new Map()); + // カメラは木を読み終える前に止まる。そのときの位置を覚えておき、読み終えたら付ける。 + const lastCamera = useRef(null); + + /** + * 見えている木のうち、どれにどちら向きのラベルを付けるかを決め直し、変わった木だけ + * アイコンを差し替える(`MarkerState.icon` をその場で書き換える)。android-sdk の + * `StreetTreeViewModel.onCameraMoveEnd` と同じ。 + */ + const relabel = useCallback((camera: MapCameraPosition) => { + lastCamera.current = camera; + if (!trees || !icons || markerStates.length !== trees.length) return; + let sides = new Map(); + if (camera.zoom >= LABEL_MIN_ZOOM) { + const bounds = camera.visibleRegion?.bounds ?? aroundCenter(camera); + sides = chooseLabels({ + trees, + bounds, + zoom: camera.zoom, + scale: LABEL_ICON_SCALE, + dotSize: DOT_SIZE, + gap: LABEL_OUTLINE_PX, + labelSize, + previousSides: roadSides.current, + }); + for (const [index, side] of sides) roadSides.current.set(trees[index].roadName, side); + } + for (const index of labelled.current.keys()) { + if (!sides.has(index)) markerStates[index].icon = icons[trees[index].speciesIndex]; + } + for (const [index, side] of sides) { + if (labelled.current.get(index) === side) continue; + const tree = trees[index]; + const key = `${tree.speciesIndex}/${side}`; + let icon = labelIcons.current.get(key); + if (!icon) { + icon = labelledIcon(icons[tree.speciesIndex], tree.species, side); + labelIcons.current.set(key, icon); + } + markerStates[index].icon = icon; + } + labelled.current = sides; + }, [icons, markerStates, trees]); + + useEffect(() => { + labelled.current = new Map(); + labelIcons.current = new Map(); + const camera = lastCamera.current ?? currentCamera?.(); + if (camera) relabel(camera); + }, [relabel, currentCamera]); + + return { error, markerStates, trees, species, isLoading: trees === null && error === null, relabel }; } diff --git a/examples/basic/src/pages/polygon/boston/BostonBuildingsPage.tsx b/examples/basic/src/pages/polygon/boston/BostonBuildingsPage.tsx new file mode 100644 index 0000000..6aba673 --- /dev/null +++ b/examples/basic/src/pages/polygon/boston/BostonBuildingsPage.tsx @@ -0,0 +1,336 @@ +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { createGeoPoint, createPolygonState, type GeoPoint, type PolygonState } from '@mapconductor/js-sdk-core'; +import { InfoBubble, Polygons } from '@mapconductor/js-sdk-react'; +import { ControlPanel } from '../../../components/ControlPanel'; +import { MapViewContainer } from '../../../MapViewContainer'; +import { useSampleI18n } from '../../../samples/i18n'; +import { loadDataset, nextPaint, type Building, type BuildingsDoc, type Dataset } from './bostonData'; +import { areaSquareMetres, formatArea, LAND_USE_STYLES, LandUseLegend, LoadingOverlay, PolygonInfo, type OverlayPhase } from './BostonOverlays'; + +/** + * Polygons of Boston drawn with one on top of the real map. + * + * - Downtown: Overture building footprints in three nested areas around + * Downtown Crossing — 0.8 x 1.1 km, 1.6 x 2.2 km and 3.2 x 4.4 km — each + * building tagged with the smallest one that holds it. + * - City buildings / city parcels: the whole city (about 100,000 polygons + * each), a load test. See bostonData.ts for where those files come from. + * + * Tapping a polygon highlights it and names it; tapping elsewhere says nothing + * was hit, which is what makes the page usable for checking hit testing. + */ +const DATASETS: { key: Dataset; label: string }[] = [ + { key: 'downtown', label: 'Downtown' }, + { key: 'buildings', label: 'City buildings' }, + { key: 'parcels', label: 'City parcels' }, +]; + +const DEFAULT_CAMERA = { lat: 42.35545, lng: -71.0605, zoom: 16 }; +const AREAS = [ + { level: 0, label: '0.8 × 1.1 km' }, + { level: 1, label: '1.6 × 2.2 km' }, + { level: 2, label: '3.2 × 4.4 km' }, +] as const; +const TAPPED = 'rgba(37, 99, 235, 0.85)'; + +/** What the last tap hit: a building, or nothing (`building` null). */ +interface Tap { + seq: number; + building: Building | null; + /** Where the tap landed: the polygon event's point, or the map click's. */ + point: GeoPoint | null; +} + +/** + * `?camera=lat,lng,zoom`, `?data=downtown|buildings|parcels` and `?area=0|1|2` + * set where the page opens and what it starts with, so a measurement sees the + * same view on every provider. + */ +function initialParams(): { camera: typeof DEFAULT_CAMERA; area: number; dataset: Dataset } { + if (typeof window === 'undefined') return { camera: DEFAULT_CAMERA, area: 0, dataset: 'downtown' }; + const params = new URLSearchParams(window.location.search); + const [lat, lng, zoom] = (params.get('camera') ?? '').split(',').map(Number); + const camera = [lat, lng, zoom].some(n => !Number.isFinite(n)) ? DEFAULT_CAMERA : { lat, lng, zoom }; + const area = AREAS.find(a => String(a.level) === params.get('area'))?.level ?? 0; + const dataset = DATASETS.find(d => d.key === params.get('data'))?.key ?? 'downtown'; + return { camera, area, dataset }; +} + +// Parcels: by land use (Property Assessment). Buildings: darker for taller, +// grey when the height is unknown. +function fillFor(dataset: Dataset, building: Building): string { + if (dataset === 'parcels') return LAND_USE_STYLES[building.use ?? 'unknown'].fill; + const height = building.h; + if (height == null) return 'rgba(148, 163, 184, 0.6)'; + if (height < 15) return 'rgba(254, 240, 138, 0.7)'; + if (height < 30) return 'rgba(253, 186, 116, 0.7)'; + if (height < 60) return 'rgba(249, 115, 22, 0.7)'; + if (height < 120) return 'rgba(220, 38, 38, 0.7)'; + return 'rgba(127, 29, 29, 0.75)'; +} + +function toPoints(ring: number[]): GeoPoint[] { + const points: GeoPoint[] = []; + for (let i = 0; i < ring.length; i += 2) { + points.push(createGeoPoint({ longitude: ring[i], latitude: ring[i + 1] })); + } + return points; +} + +export function BostonBuildingsPage() { + const { t } = useSampleI18n(); + const [doc, setDoc] = useState(null); + const [initial] = useState(initialParams); + const [area, setArea] = useState(initial.area); + const [dataset, setDataset] = useState(initial.dataset); + const [loadError, setLoadError] = useState(null); + const [tap, setTap] = useState(null); + const [timing, setTiming] = useState<{ build: number; frame: number } | null>(null); + const highlightedRef = useRef<{ state: PolygonState; fill: string } | null>(null); + // Time from handing the list to until every polygon's onAdded ran. + const [addedMs, setAddedMs] = useState(null); + + const [loadMs, setLoadMs] = useState(0); + // Non-null while a dataset is on its way; drives the loading overlay. + const [progress, setProgress] = useState(null); + useEffect(() => { + let cancelled = false; + const start = performance.now(); + setDoc(null); + setTiming(null); + setAddedMs(null); + setLoadError(null); + setProgress({ phase: 'download', loaded: 0, total: null }); + highlightedRef.current = null; + loadDataset(dataset, p => { if (!cancelled) setProgress(p); }) + .then(async loaded => { + if (cancelled) return; + setLoadMs(performance.now() - start); + // Building the states blocks the main thread; show that phase first. + setProgress({ phase: 'build' }); + await nextPaint(); + if (!cancelled) setDoc(loaded); + }) + .catch(error => { + if (cancelled) return; + setProgress(null); + setLoadError(String(error)); + }); + return () => { cancelled = true; }; + }, [dataset]); + + // Moves the highlight to `state` (or clears it) and records the tap. + const onTap = (state: PolygonState | null, building: Building | null, point: GeoPoint | null = null) => { + const previous = highlightedRef.current; + if (previous) previous.state.fillColor = previous.fill; + highlightedRef.current = state ? { state, fill: state.fillColor } : null; + if (state) state.fillColor = TAPPED; + setTap(prev => ({ seq: (prev?.seq ?? 0) + 1, building, point })); + }; + const onTapRef = useRef(onTap); + onTapRef.current = onTap; + const onMapClick = useCallback((point: GeoPoint) => onTapRef.current(null, null, point), []); + + // The loading overlay stays up until the map has every polygon of the list + // now handed to it: each state's onAdded records its id, and `count` is how + // many ids of that list are recorded. `doc` tells this load's calls from + // those of a dataset switched away from. + // + // An id stays recorded when the area shrinks and drops it. The SDK only + // calls onAdded again for a polygon it saw leave, and a list replaced before + // the SDK got to it is never seen; a list's polygons that never came would + // leave the overlay up for good. So the count is redone against each new + // list, and an id already on the map counts for it. + const commitRef = useRef(0); + const addedRef = useRef<{ + doc: BuildingsDoc | null; + ids: Set; + list: Set; + count: number; + waiting: boolean; + }>({ doc: null, ids: new Set(), list: new Set(), count: 0, waiting: false }); + const onAllAddedRef = useRef(() => {}); + onAllAddedRef.current = () => { + setAddedMs(performance.now() - commitRef.current); + setProgress(null); + }; + + // Every building's state, built once; the area only filters them. + const allStates = useMemo(() => { + if (!doc) return null; + const start = performance.now(); + const onAdded = (state: PolygonState) => { + const added = addedRef.current; + if (added.doc !== doc || added.ids.has(state.id)) return; + added.ids.add(state.id); + if (!added.list.has(state.id)) return; // from a list since replaced + if (++added.count === added.list.size && added.waiting) { + added.waiting = false; + onAllAddedRef.current(); + } + }; + const states = doc.buildings.map(building => { + const [outer, ...holes] = building.rings; + return createPolygonState({ + id: building.id, + points: toPoints(outer), + holes: holes.map(toPoints), + strokeColor: dataset === 'parcels' ? 'rgba(71, 85, 105, 0.7)' : 'rgba(68, 64, 60, 0.8)', + strokeWidth: 1, + fillColor: fillFor(dataset, building), + extra: building.id, + onClick: event => onTapRef.current(event.state, building, event.clicked), + onAdded, + }); + }); + return { states, build: performance.now() - start }; + // `dataset` changes only together with `doc`. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [doc]); + + const shown = useMemo(() => { + if (!doc || !allStates) return null; + const states = allStates.states.filter((_, i) => doc.buildings[i].l <= area); + const vertices = states.reduce((n, s) => n + s.points.length + s.holes.reduce((m, h) => m + h.length, 0), 0); + return { states, vertices }; + }, [doc, allStates, area]); + + // Time from handing the list to until the frame after it: the + // child's effect has registered the polygons by the time this one runs. + // That is not when they are on the map; the overlay waits for onAdded. + useLayoutEffect(() => { + commitRef.current = performance.now(); + if (!shown || !doc) return; + const added = addedRef.current; + if (added.doc !== doc) { + // A new dataset. Runs before registers it, so no onAdded has come yet. + added.doc = doc; + added.ids = new Set(); + added.waiting = true; + setProgress(p => (p ? { phase: 'draw' } : p)); + } + // One per id: the map keeps one polygon per id. + added.list = new Set(shown.states.map(s => s.id)); + added.count = 0; + for (const id of added.list) if (added.ids.has(id)) added.count++; + if (added.waiting && added.count === added.list.size) { + added.waiting = false; + onAllAddedRef.current(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [shown]); + useEffect(() => { + if (!shown || !allStates) return; + let raf = requestAnimationFrame(() => { + raf = requestAnimationFrame(() => { + setTiming({ build: allStates.build, frame: performance.now() - commitRef.current }); + }); + }); + return () => cancelAnimationFrame(raf); + }, [shown, allStates]); + + return ( + + {shown && } + {progress && } + {tap?.building && tap.point && ( + + + + )} + +
+ {DATASETS.map(d => ( + + ))} +
+ {dataset === 'downtown' && ( +
+ {AREAS.map(a => ( + + ))} +
+ )} + {loadError &&

{loadError}

} + {dataset === 'parcels' && } + {shown ? ( +

+ {t({ + en: `${shown.states.length.toLocaleString()} polygons, ${shown.vertices.toLocaleString()} vertices`, + ja: `ポリゴン ${shown.states.length.toLocaleString()} 個・頂点 ${shown.vertices.toLocaleString()} 個`, + 'es-419': `${shown.states.length.toLocaleString()} polígonos, ${shown.vertices.toLocaleString()} vértices`, + de: `${shown.states.length.toLocaleString()} Polygone, ${shown.vertices.toLocaleString()} Eckpunkte`, + th: `โพลีกอน ${shown.states.length.toLocaleString()} รูป จุดยอด ${shown.vertices.toLocaleString()} จุด`, + hi: `${shown.states.length.toLocaleString()} पॉलीगॉन, ${shown.vertices.toLocaleString()} शीर्ष`, + })} + {timing && ( + <> +
+ + {t({ + en: `load ${loadMs.toFixed(0)} ms, states ${timing.build.toFixed(0)} ms, next frame ${timing.frame.toFixed(0)} ms`, + ja: `読み込み ${loadMs.toFixed(0)} ms・state 作成 ${timing.build.toFixed(0)} ms・次のフレームまで ${timing.frame.toFixed(0)} ms`, + 'es-419': `carga ${loadMs.toFixed(0)} ms, estados ${timing.build.toFixed(0)} ms, siguiente cuadro ${timing.frame.toFixed(0)} ms`, + de: `Laden ${loadMs.toFixed(0)} ms, States ${timing.build.toFixed(0)} ms, nächster Frame ${timing.frame.toFixed(0)} ms`, + th: `โหลด ${loadMs.toFixed(0)} ms สร้าง state ${timing.build.toFixed(0)} ms เฟรมถัดไป ${timing.frame.toFixed(0)} ms`, + hi: `लोड ${loadMs.toFixed(0)} ms, state ${timing.build.toFixed(0)} ms, अगला फ़्रेम ${timing.frame.toFixed(0)} ms`, + })} + + + )} +

+ ) : ( +

…

+ )} + {tap && ( +

+ {tap.building?.use + ? `${t({ en: 'Parcel', ja: '区画', 'es-419': 'Parcela', de: 'Flurstück', th: 'แปลงที่ดิน', hi: 'भूखंड' })} · ${t(LAND_USE_STYLES[tap.building.use].label)} · ${formatArea(areaSquareMetres(tap.building))}` + : tap.building + ? `${tap.building.n ?? t({ en: 'Building', ja: '建物', 'es-419': 'Edificio', de: 'Gebäude', th: 'อาคาร', hi: 'इमारत' })} · ${ + tap.building.h == null + ? t({ en: 'height unknown', ja: '高さ不明', 'es-419': 'altura desconocida', de: 'Höhe unbekannt', th: 'ไม่ทราบความสูง', hi: 'ऊँचाई अज्ञात' }) + : `${tap.building.h} m` + } · ${formatArea(areaSquareMetres(tap.building))}` + : t({ en: 'No building here', ja: 'ここに建物はありません', 'es-419': 'Aquí no hay edificio', de: 'Hier ist kein Gebäude', th: 'ไม่มีอาคารตรงนี้', hi: 'यहाँ कोई इमारत नहीं' })} +

+ )} +

+ {doc ? `${doc.attribution} (${doc.license})` : null} +

+
+
+ ); +} diff --git a/examples/basic/src/pages/polygon/boston/BostonOverlays.tsx b/examples/basic/src/pages/polygon/boston/BostonOverlays.tsx new file mode 100644 index 0000000..e729a69 --- /dev/null +++ b/examples/basic/src/pages/polygon/boston/BostonOverlays.tsx @@ -0,0 +1,177 @@ +import { computeArea, createGeoPoint } from '@mapconductor/js-sdk-core'; +import { useSampleI18n } from '../../../samples/i18n'; +import type { Building, LandUse, LoadProgress } from './bostonData'; + +type Label = { en: string; ja: string; 'es-419': string; de: string; th: string; hi: string }; + +/** Land use of a parcel (Property Assessment `LU`, grouped) and how it is drawn. */ +export const LAND_USE_STYLES: Record = { + family: { + fill: 'rgba(250, 204, 21, 0.55)', + label: { en: '1–3 family', ja: '戸建て・2〜3 世帯', 'es-419': '1 a 3 familias', de: '1–3 Familien', th: 'บ้าน 1–3 ครอบครัว', hi: '1–3 परिवार' }, + }, + apartment: { + fill: 'rgba(249, 115, 22, 0.55)', + label: { en: 'Apartments', ja: '集合住宅', 'es-419': 'Departamentos', de: 'Mehrfamilienhaus', th: 'อพาร์ตเมนต์', hi: 'अपार्टमेंट' }, + }, + condo: { + fill: 'rgba(236, 72, 153, 0.5)', + label: { en: 'Condominium', ja: '区分所有', 'es-419': 'Condominio', de: 'Eigentumswohnungen', th: 'คอนโดมิเนียม', hi: 'कॉन्डोमिनियम' }, + }, + mixed: { + fill: 'rgba(168, 85, 247, 0.5)', + label: { en: 'Residential + commercial', ja: '住商併用', 'es-419': 'Residencial y comercial', de: 'Wohnen + Gewerbe', th: 'ที่อยู่อาศัยผสมพาณิชย์', hi: 'आवासीय + व्यावसायिक' }, + }, + commercial: { + fill: 'rgba(239, 68, 68, 0.55)', + label: { en: 'Commercial', ja: '商業', 'es-419': 'Comercial', de: 'Gewerbe', th: 'พาณิชย์', hi: 'व्यावसायिक' }, + }, + industrial: { + fill: 'rgba(100, 116, 139, 0.6)', + label: { en: 'Industrial', ja: '工業', 'es-419': 'Industrial', de: 'Industrie', th: 'อุตสาหกรรม', hi: 'औद्योगिक' }, + }, + exempt: { + fill: 'rgba(59, 130, 246, 0.5)', + label: { en: 'Exempt (public, institutions)', ja: '非課税(公共・団体)', 'es-419': 'Exento (público, instituciones)', de: 'Steuerfrei (öffentlich)', th: 'ยกเว้นภาษี (รัฐ สถาบัน)', hi: 'कर-मुक्त (सार्वजनिक)' }, + }, + vacant: { + fill: 'rgba(34, 197, 94, 0.45)', + label: { en: 'Vacant land', ja: '空き地', 'es-419': 'Terreno baldío', de: 'Brachland', th: 'ที่ดินว่าง', hi: 'खाली ज़मीन' }, + }, + unknown: { + fill: 'rgba(148, 163, 184, 0.35)', + label: { en: 'No assessment (roads, islands)', ja: '評価なし(道路・島)', 'es-419': 'Sin tasación (calles, islas)', de: 'Ohne Bewertung (Straßen)', th: 'ไม่มีการประเมิน (ถนน เกาะ)', hi: 'मूल्यांकन नहीं (सड़कें)' }, + }, +}; + +export function LandUseLegend() { + const { t } = useSampleI18n(); + return ( +
    + {Object.entries(LAND_USE_STYLES).map(([key, style]) => ( +
  • + + {t(style.label)} +
  • + ))} +
+ ); +} + +/** Where loading has got to after the data itself is in. */ +export type OverlayPhase = LoadProgress | { phase: 'build' } | { phase: 'draw' }; + +const MB = 1024 * 1024; + +/** + * Covers the map while a dataset loads. The spinner turns by a CSS transform, + * which the compositor keeps animating while decoding or building the states + * holds the main thread. + */ +export function LoadingOverlay({ progress, shapes = 'polygons' }: { progress: OverlayPhase; shapes?: 'polygons' | 'roads' | 'trees' }) { + const { t } = useSampleI18n(); + let text: string; + let percent: number | null = null; + switch (progress.phase) { + case 'download': { + const loaded = (progress.loaded / MB).toFixed(1); + if (progress.total) { + percent = Math.round((progress.loaded / progress.total) * 100); + const total = (progress.total / MB).toFixed(1); + text = t({ en: `Loading data… ${loaded} / ${total} MB`, ja: `データを読み込み中… ${loaded} / ${total} MB`, 'es-419': `Cargando datos… ${loaded} / ${total} MB`, de: `Daten werden geladen… ${loaded} / ${total} MB`, th: `กำลังโหลดข้อมูล… ${loaded} / ${total} MB`, hi: `डेटा लोड हो रहा है… ${loaded} / ${total} MB` }); + } else { + text = t({ en: `Loading data… ${loaded} MB`, ja: `データを読み込み中… ${loaded} MB`, 'es-419': `Cargando datos… ${loaded} MB`, de: `Daten werden geladen… ${loaded} MB`, th: `กำลังโหลดข้อมูล… ${loaded} MB`, hi: `डेटा लोड हो रहा है… ${loaded} MB` }); + } + break; + } + case 'decode': + text = shapes === 'roads' + ? t({ en: 'Reading the roads…', ja: '道路を読み取り中…', 'es-419': 'Leyendo las calles…', de: 'Straßen werden gelesen…', th: 'กำลังอ่านถนน…', hi: 'सड़कें पढ़ी जा रही हैं…' }) + : shapes === 'trees' + ? t({ en: 'Reading the trees…', ja: '木を読み取り中…', 'es-419': 'Leyendo los árboles…', de: 'Bäume werden gelesen…', th: 'กำลังอ่านต้นไม้…', hi: 'पेड़ पढ़े जा रहे हैं…' }) + : t({ en: 'Reading the polygons…', ja: 'ポリゴンを読み取り中…', 'es-419': 'Leyendo los polígonos…', de: 'Polygone werden gelesen…', th: 'กำลังอ่านโพลีกอน…', hi: 'पॉलीगॉन पढ़े जा रहे हैं…' }); + break; + case 'build': + text = shapes === 'roads' + ? t({ en: 'Preparing the roads…', ja: '道路を準備中…', 'es-419': 'Preparando las calles…', de: 'Straßen werden vorbereitet…', th: 'กำลังเตรียมถนน…', hi: 'सड़कें तैयार हो रही हैं…' }) + : shapes === 'trees' + ? t({ en: 'Preparing the trees…', ja: '木を準備中…', 'es-419': 'Preparando los árboles…', de: 'Bäume werden vorbereitet…', th: 'กำลังเตรียมต้นไม้…', hi: 'पेड़ तैयार हो रहे हैं…' }) + : t({ en: 'Preparing the polygons…', ja: 'ポリゴンを準備中…', 'es-419': 'Preparando los polígonos…', de: 'Polygone werden vorbereitet…', th: 'กำลังเตรียมโพลีกอน…', hi: 'पॉलीगॉन तैयार हो रहे हैं…' }); + break; + case 'draw': + text = t({ en: 'Drawing the map…', ja: '地図に描画中…', 'es-419': 'Dibujando el mapa…', de: 'Karte wird gezeichnet…', th: 'กำลังวาดแผนที่…', hi: 'मैप बनाया जा रहा है…' }); + break; + } + return ( +
+
+
+
{text}
+ {percent != null && ( +
+
+
+ )} + +
+
+ ); +} + +/** What a tapped polygon carries, shown in an InfoBubble at the tap. */ +export function PolygonInfo({ building }: { building: Building }) { + const { t } = useSampleI18n(); + const rows: [string, string][] = []; + if (building.use) { + rows.push([t({ en: 'Land use', ja: '土地利用', 'es-419': 'Uso del suelo', de: 'Nutzung', th: 'การใช้ที่ดิน', hi: 'भूमि उपयोग' }), t(LAND_USE_STYLES[building.use].label)]); + } else { + if (building.n) rows.push([t({ en: 'Name', ja: '名前', 'es-419': 'Nombre', de: 'Name', th: 'ชื่อ', hi: 'नाम' }), building.n]); + rows.push([ + t({ en: 'Height', ja: '高さ', 'es-419': 'Altura', de: 'Höhe', th: 'ความสูง', hi: 'ऊँचाई' }), + building.h == null ? t({ en: 'unknown', ja: '不明', 'es-419': 'desconocida', de: 'unbekannt', th: 'ไม่ทราบ', hi: 'अज्ञात' }) : `${building.h} m`, + ]); + } + rows.push([t({ en: 'Area', ja: '面積', 'es-419': 'Superficie', de: 'Fläche', th: 'พื้นที่', hi: 'क्षेत्रफल' }), formatArea(areaSquareMetres(building))]); + rows.push([ + t({ en: 'Vertices', ja: '頂点', 'es-419': 'Vértices', de: 'Eckpunkte', th: 'จุดยอด', hi: 'शीर्ष' }), + String(building.rings.reduce((n, r) => n + r.length / 2, 0)) + + (building.rings.length > 1 ? ` (${t({ en: 'holes', ja: '穴', 'es-419': 'huecos', de: 'Löcher', th: 'รู', hi: 'छेद' })} ${building.rings.length - 1})` : ''), + ]); + return ( + + + {rows.map(([key, value]) => ( + + + + + ))} + +
{key}{value}
+ ); +} + +/** The area of a polygon in square metres: its outline less its holes. */ +export function areaSquareMetres(building: Building): number { + const areas = building.rings.map(ring => { + const points = []; + for (let i = 0; i < ring.length; i += 2) points.push(createGeoPoint({ longitude: ring[i], latitude: ring[i + 1] })); + return computeArea(points); + }); + return areas.slice(1).reduce((rest, hole) => rest - hole, areas[0] ?? 0); +} + +/** "1,234 m²", or hectares from 10,000 m² up. */ +export function formatArea(squareMetres: number): string { + return squareMetres >= 10_000 + ? `${(squareMetres / 10_000).toFixed(2)} ha` + : `${Math.round(squareMetres).toLocaleString('en-US')} m²`; +} diff --git a/examples/basic/src/pages/polygon/boston/bostonData.ts b/examples/basic/src/pages/polygon/boston/bostonData.ts new file mode 100644 index 0000000..739944f --- /dev/null +++ b/examples/basic/src/pages/polygon/boston/bostonData.ts @@ -0,0 +1,199 @@ +/** + * Loads the polygons the Boston page draws. + * + * - `downtown`: Overture building footprints of downtown in three nested + * areas (`public/boston/boston-downtown.bin`). + * - `buildings` / `parcels`: the whole city (`public/boston/boston-city-*.bin`): + * Overture buildings, and Analyze Boston Parcels 2025 joined with the FY2026 + * Property Assessment land use. + * + * All three are bundled. `tools/boston/` builds them from the official sources + * (see its README). + * + * The files carry no ids: this is a polygon demo, and a polygon's id on the + * map is its index in the file. + * + * Binary layout, MCPG v2: + * 'MCPG' u32 version=2 u32 count u8 fields u8 digits (little-endian) + * fields: 1 = height, 2 = land use, 4 = area, 8 = name (what the file carries) + * digits: coordinates are integers of 10^-digits degree (buildings 6, parcels 5) + * per polygon, only the fields present, in this order: + * height varint, 0 = unknown, else the height in 0.1 m plus 1 + * land use u8, the index in LAND_USES (family … unknown) + * area u8, the smallest downtown area (0, 1 or 2) the building fits in + * name varint byte length (0 = none), UTF-8 + * varint ringCount, per ring: varint n, n x (svarint dLat, svarint dLng) + * varint is LEB128 (7 bits at a time, low first); svarint is a zigzag varint. + * Coordinates are integers of 10^-digits degree, each the difference from + * the previous vertex across the whole file. A ring's closing vertex (the same + * as its first) is not stored: n counts the others, and the reader closes + * the ring again. + */ +export type Dataset = 'downtown' | 'buildings' | 'parcels'; + +export interface Building { + id: string; + /** The smallest downtown area (0, 1 or 2) the building fits in; 0 for the city-wide sets. */ + l: number; + h: number | null; + n?: string; + /** A parcel's land use, from the City of Boston's Property Assessment. */ + use?: LandUse; + /** Rings as flat [lng, lat, lng, lat, ...]; the first is the outline, the rest holes. */ + rings: number[][]; +} + +/** The land uses, in the order the file stores them (a land use is its index here). */ +export const LAND_USES = [ + 'family', + 'apartment', + 'condo', + 'mixed', + 'commercial', + 'industrial', + 'exempt', + 'vacant', + 'unknown', +] as const; + +export type LandUse = (typeof LAND_USES)[number]; + +/** Where loading has got to, for the overlay. */ +export type LoadProgress = + | { phase: 'download'; loaded: number; total: number | null } + | { phase: 'decode' }; + +export interface BuildingsDoc { + attribution: string; + license: string; + buildings: Building[]; +} + +const OVERTURE = { + attribution: '© OpenStreetMap contributors, Esri Community Maps contributors, USGS, Microsoft — via Overture Maps Foundation', + license: 'ODbL 1.0', +}; + +const SOURCES: Record = { + downtown: { file: 'boston/boston-downtown.bin', ...OVERTURE }, + buildings: { file: 'boston/boston-city-buildings.bin', ...OVERTURE }, + parcels: { + file: 'boston/boston-city-parcels.bin', + attribution: 'City of Boston, Parcels 2025 and FY2026 Property Assessment (Analyze Boston)', + license: 'ODC PDDL', + }, +}; + +export async function loadDataset( + dataset: Dataset, + onProgress: (progress: LoadProgress) => void = () => {}, +): Promise { + const source = SOURCES[dataset]; + const response = await fetch(`${import.meta.env.BASE_URL}${source.file}`); + if (!response.ok) throw new Error(`${source.file}: ${response.status}`); + const bytes = await readWithProgress(response, onProgress); + onProgress({ phase: 'decode' }); + // Decoding blocks the main thread; let the overlay show the new phase first. + await nextPaint(); + return { attribution: source.attribution, license: source.license, buildings: decodeMcpg(bytes, dataset) }; +} + +/** Resolves after the browser has painted, so a state change shows before blocking work. */ +export function nextPaint(): Promise { + return new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve, 0))); +} + +export async function readWithProgress(response: Response, onProgress: (progress: LoadProgress) => void): Promise { + const header = response.headers.get('Content-Length'); + // A compressed response's Content-Length counts compressed bytes; fall back to a byte count. + const total = header && !response.headers.get('Content-Encoding') ? Number(header) : null; + if (!response.body) return new Uint8Array(await response.arrayBuffer()); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let loaded = 0; + onProgress({ phase: 'download', loaded, total }); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + loaded += value.byteLength; + onProgress({ phase: 'download', loaded, total }); + } + const bytes = new Uint8Array(loaded); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return bytes; +} + +const FIELD_HEIGHT = 1; +const FIELD_USE = 2; +const FIELD_AREA = 4; +const FIELD_NAME = 8; + +/** Decodes an MCPG v2 file (see the top of this file); polygon `i` gets the id "-". */ +export function decodeMcpg(bytes: Uint8Array, idPrefix: string): Building[] { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const magic = String.fromCharCode(bytes[0], bytes[1], bytes[2], bytes[3]); + if (magic !== 'MCPG' || view.getUint32(4, true) !== 2) throw new Error('not an MCPG v2 file'); + const count = view.getUint32(8, true); + const fields = bytes[12]; + const scale = 10 ** bytes[13]; + let offset = 14; + // Values stay below 2^31 here, so the shifts and the zigzag work on 32-bit ints. + const varint = (): number => { + let value = 0; + let shift = 0; + for (;;) { + const b = bytes[offset++]; + value |= (b & 0x7f) << shift; + if (b < 0x80) return value >>> 0; + shift += 7; + } + }; + const svarint = (): number => { + const v = varint(); + return (v >>> 1) ^ -(v & 1); + }; + const text = new TextDecoder(); + const buildings: Building[] = new Array(count); + let lat = 0; + let lng = 0; + for (let i = 0; i < count; i++) { + let h: number | null = null; + let use: LandUse | undefined; + let l = 0; + let n: string | undefined; + if (fields & FIELD_HEIGHT) { + const height = varint(); + h = height === 0 ? null : (height - 1) / 10; + } + if (fields & FIELD_USE) use = LAND_USES[bytes[offset++]]; + if (fields & FIELD_AREA) l = bytes[offset++]; + if (fields & FIELD_NAME) { + const length = varint(); + if (length > 0) n = text.decode(bytes.subarray(offset, offset + length)); + offset += length; + } + const ringCount = varint(); + const rings: number[][] = new Array(ringCount); + for (let r = 0; r < ringCount; r++) { + const vertices = varint(); + // The closing vertex is not stored; it is the first one again. + const ring = new Array((vertices + 1) * 2); + for (let v = 0; v < vertices; v++) { + lat += svarint(); + lng += svarint(); + ring[v * 2] = lng / scale; + ring[v * 2 + 1] = lat / scale; + } + ring[vertices * 2] = ring[0]; + ring[vertices * 2 + 1] = ring[1]; + rings[r] = ring; + } + buildings[i] = { id: `${idPrefix}-${i}`, l, h, n, use, rings }; + } + return buildings; +} diff --git a/examples/basic/src/pages/polygon/collection/PolygonsPage.tsx b/examples/basic/src/pages/polygon/collection/PolygonsPage.tsx new file mode 100644 index 0000000..f7d9974 --- /dev/null +++ b/examples/basic/src/pages/polygon/collection/PolygonsPage.tsx @@ -0,0 +1,99 @@ +import { useState } from 'react'; +import { createGeoPoint, createPolygonState, type GeoPoint, type PolygonState } from '@mapconductor/js-sdk-core'; +import { Polygons } from '@mapconductor/js-sdk-react'; +import { ControlPanel } from '../../../components/ControlPanel'; +import { MapViewContainer } from '../../../MapViewContainer'; +import { useSampleI18n } from '../../../samples/i18n'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; + +const COLUMNS = 10; +const SPACING = 0.004; +const ORIGIN = { latitude: 35.6895, longitude: 139.6917 }; +const INIT_CAMERA = { lat: ORIGIN.latitude - 0.006, lng: ORIGIN.longitude + 0.018, zoom: 14 }; +const PALETTE = ['rgba(66, 133, 244, 0.4)', 'rgba(234, 67, 53, 0.4)', 'rgba(251, 188, 5, 0.4)', 'rgba(52, 168, 83, 0.4)']; +const TAPPED = 'rgba(156, 39, 176, 0.8)'; + +function hexagon(center: { latitude: number; longitude: number }, radius: number): GeoPoint[] { + return Array.from({ length: 7 }, (_, i) => { + const angle = (Math.PI / 3) * i; + return createGeoPoint({ + latitude: center.latitude + radius * Math.sin(angle), + longitude: center.longitude + radius * Math.cos(angle), + }); + }); +} + +function buildRow(row: number, paletteIndex: number): PolygonState[] { + return Array.from({ length: COLUMNS }, (_, column) => { + const center = { + latitude: ORIGIN.latitude - row * SPACING, + longitude: ORIGIN.longitude + column * SPACING + (row % 2 === 1 ? SPACING / 2 : 0), + }; + return createPolygonState({ + id: `hex-${row}-${column}`, + points: hexagon(center, SPACING * 0.45), + strokeColor: '#444444', + strokeWidth: 1, + fillColor: PALETTE[(paletteIndex + row + column) % PALETTE.length], + onClick: event => { + event.state.fillColor = TAPPED; + }, + }); + }); +} + +function buildStates(rows: number, paletteIndex: number): PolygonState[] { + return Array.from({ length: rows }, (_, row) => buildRow(row, paletteIndex)).flat(); +} + +export function PolygonsPage() { + const loading = useLoadingOverlay(); + const { t } = useSampleI18n(); + const [paletteIndex, setPaletteIndex] = useState(0); + const [states, setStates] = useState(() => buildStates(3, 0)); + const rows = states.length / COLUMNS; + + const addRow = () => setStates(prev => [...prev, ...buildRow(rows, paletteIndex)]); + const removeRow = () => setStates(prev => prev.slice(0, Math.max(0, prev.length - COLUMNS))); + // New state objects with the same ids: must update them in place, not add. + const recolor = () => { + const next = (paletteIndex + 1) % PALETTE.length; + setPaletteIndex(next); + setStates(buildStates(rows, next)); + }; + + return ( + + + + +
+ + + +
+

+ {t({ + en: 'A grid of hexagons registered with one . Tap a hexagon to change its fill in place.', + ja: '六角形の格子を 1 つの で登録しています。六角形をタップすると、その塗りだけがその場で変わります。', + 'es-419': 'Una cuadrícula de hexágonos registrada con un solo . Toca un hexágono para cambiar su relleno.', + de: 'Ein Sechseckraster, registriert mit einem einzigen . Tippen Sie auf ein Sechseck, um seine Füllung zu ändern.', + th: 'ตารางหกเหลี่ยมที่ลงทะเบียนด้วย ตัวเดียว แตะหกเหลี่ยมเพื่อเปลี่ยนสีพื้น', + hi: 'षट्भुजों का ग्रिड एक ही से दर्ज है। किसी षट्भुज पर टैप करके उसका रंग बदलें।', + })} +

+
+
+ ); +} diff --git a/examples/basic/src/pages/polygon/hole/PolygonHolePage.tsx b/examples/basic/src/pages/polygon/hole/PolygonHolePage.tsx index 5e90388..b9a0e2b 100644 --- a/examples/basic/src/pages/polygon/hole/PolygonHolePage.tsx +++ b/examples/basic/src/pages/polygon/hole/PolygonHolePage.tsx @@ -12,6 +12,7 @@ import { Markers, Polygon } from '@mapconductor/js-sdk-react'; import { ControlPanel } from '../../../components/ControlPanel'; import { MapViewContainer } from '../../../MapViewContainer'; import { useSampleI18n } from '../../../samples/i18n'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; const INIT_CAMERA = { lat: 43.0602, lng: 141.3195, zoom: 11 }; // A regional mask generously covering the Sapporo area. Cesium cannot @@ -46,6 +47,7 @@ const INITIAL_HOLES = [ const HOLE_MARKER_COLORS = ['#2563eb', '#f97316']; export function PolygonHolePage() { + const loading = useLoadingOverlay(); const { t } = useSampleI18n(); const [holes, setHoles] = useState(() => INITIAL_HOLES.map(hole => [...hole])); const setHolesRef = useRef(setHoles); @@ -101,7 +103,8 @@ export function PolygonHolePage() { return ( - + + on + * top of the real map: Overture `transportation/segment`, cut at the city + * boundary (see bostonRoadsData.ts for the file). + * + * Bigger roads are drawn wider and on top. Past PolylineTilingOptions the SDK + * draws them as raster tiles; "Native" hands every one to the map SDK instead, + * and the time from handing the list over to every polyline's onAdded is shown + * for both. Tapping a road opens an InfoBubble at the nearest point on it; + * tapping elsewhere closes it. + */ +type Label = { en: string; ja: string; 'es-419': string; de: string; th: string; hi: string }; + +/** How a road class is drawn: colour, width in CSS px, zIndex (bigger roads on top). */ +export const ROAD_STYLES: Record = { + highway: { color: '#E8590C', width: 5, zIndex: 6, label: { en: 'Highway', ja: '高速・幹線', 'es-419': 'Autopista', de: 'Autobahn', th: 'ทางหลวง', hi: 'राजमार्ग' } }, + primary: { color: '#F08C00', width: 4, zIndex: 5, label: { en: 'Primary', ja: '主要道', 'es-419': 'Principal', de: 'Hauptstraße', th: 'ถนนสายหลัก', hi: 'मुख्य सड़क' } }, + secondary: { color: '#FAB005', width: 3.5, zIndex: 4, label: { en: 'Secondary', ja: '二次道', 'es-419': 'Secundaria', de: 'Nebenstraße', th: 'ถนนสายรอง', hi: 'द्वितीयक सड़क' } }, + tertiary: { color: '#FFD43B', width: 3, zIndex: 3, label: { en: 'Tertiary', ja: '三次道', 'es-419': 'Terciaria', de: 'Verbindungsstraße', th: 'ถนนสายย่อย', hi: 'तृतीयक सड़क' } }, + local: { color: '#868E96', width: 2, zIndex: 2, label: { en: 'Local', ja: '生活道路', 'es-419': 'Local', de: 'Anliegerstraße', th: 'ถนนในชุมชน', hi: 'स्थानीय सड़क' } }, + service: { color: '#ADB5BD', width: 1.5, zIndex: 1, label: { en: 'Service', ja: '構内道路', 'es-419': 'De servicio', de: 'Zufahrt', th: 'ถนนบริการ', hi: 'सर्विस रोड' } }, + path: { color: '#74B816', width: 1, zIndex: 0, label: { en: 'Path', ja: '歩道・小径', 'es-419': 'Sendero', de: 'Weg', th: 'ทางเดิน', hi: 'पथ' } }, +}; + +const DEFAULT_CAMERA = { lat: 42.3555, lng: -71.0605, zoom: 15 }; +const TILED = PolylineTilingOptions.Default; +const NATIVE = PolylineTilingOptions.Disabled; + +/** What the last tap hit: a road, or nothing (`road` null). */ +interface Tap { + seq: number; + road: Road | null; + /** Where the bubble goes: the nearest point on the road, or the map click's point. */ + point: GeoPoint | null; +} + +/** + * `?camera=lat,lng,zoom` and `?tiling=native` set where the page opens and how + * it starts drawing, so a measurement sees the same view on every provider. + * `?stack=1` adds tiled polygons, a circle and a marker over the roads (StackCheck). + */ +function initialParams(): { camera: typeof DEFAULT_CAMERA; tiled: boolean; stack: boolean } { + if (typeof window === 'undefined') return { camera: DEFAULT_CAMERA, tiled: true, stack: false }; + const params = new URLSearchParams(window.location.search); + const [lat, lng, zoom] = (params.get('camera') ?? '').split(',').map(Number); + const camera = [lat, lng, zoom].some(n => !Number.isFinite(n)) ? DEFAULT_CAMERA : { lat, lng, zoom }; + return { camera, tiled: params.get('tiling') !== 'native', stack: params.get('stack') === '1' }; +} + +function toPoints(path: number[]): GeoPoint[] { + const points: GeoPoint[] = []; + for (let i = 0; i < path.length; i += 2) points.push(createGeoPoint({ longitude: path[i], latitude: path[i + 1] })); + return points; +} + +/** The length of a road in metres: the sum of its segments' geodesic lengths. */ +export function roadLength(points: readonly GeoPoint[]): number { + let metres = 0; + for (let i = 1; i < points.length; i++) metres += computeWGS84DistanceBetween(points[i - 1], points[i]); + return metres; +} + +function formatLength(metres: number): string { + return metres >= 1000 ? `${(metres / 1000).toFixed(2)} km` : `${Math.round(metres).toLocaleString('en-US')} m`; +} + +export function BostonRoadsPage() { + const { t } = useSampleI18n(); + const [initial] = useState(initialParams); + // The page stays mounted when the provider changes; the roads then go onto the other map. + const provider = useLocation().pathname.split('/').filter(Boolean)[0] ?? ''; + const [doc, setDoc] = useState(null); + const [tiled, setTiled] = useState(initial.tiled); + // False while a switch of tiling takes the roads off the map before handing them back. + const [mounted, setMounted] = useState(true); + const [loadError, setLoadError] = useState(null); + const [tap, setTap] = useState(null); + const [loadMs, setLoadMs] = useState(0); + // Time from handing the list to until every road's onAdded ran, and until the frame after. + const [addedMs, setAddedMs] = useState(null); + const [frameMs, setFrameMs] = useState(null); + const [progress, setProgress] = useState(null); + // How many times the list has gone onto the map; a measurement waits for the next one. + const [round, setRound] = useState(0); + + useEffect(() => { + let cancelled = false; + const start = performance.now(); + setProgress({ phase: 'download', loaded: 0, total: null }); + loadRoads(p => { if (!cancelled) setProgress(p); }) + .then(async loaded => { + if (cancelled) return; + setLoadMs(performance.now() - start); + // Building the states blocks the main thread; show that phase first. + setProgress({ phase: 'build' }); + await nextPaint(); + if (!cancelled) setDoc(loaded); + }) + .catch(error => { + if (cancelled) return; + setProgress(null); + setLoadError(String(error)); + }); + return () => { cancelled = true; }; + }, []); + + const onTapRef = useRef((_road: Road | null, _point: GeoPoint | null) => {}); + onTapRef.current = (road, point) => setTap(prev => ({ seq: (prev?.seq ?? 0) + 1, road, point })); + // A tap on the map that hits no road closes the bubble. + const onMapClick = useCallback((point: GeoPoint) => onTapRef.current(null, point), []); + + // The overlay stays up until every road of the list handed over has called + // onAdded. Each hand-over (the first load, and each switch of tiling, which + // takes the roads off the map first) is a new round; calls from an older + // round are ignored. + const commitRef = useRef(0); + const roundRef = useRef<{ round: number; ids: Set; total: number; waiting: boolean }>({ + round: 0, ids: new Set(), total: 0, waiting: false, + }); + const onAllAddedRef = useRef(() => {}); + onAllAddedRef.current = () => { + const added = performance.now() - commitRef.current; + setAddedMs(added); + setProgress(null); + requestAnimationFrame(() => requestAnimationFrame(() => setFrameMs(performance.now() - commitRef.current))); + }; + + // Every road's state, built once. + const built = useMemo(() => { + if (!doc) return null; + const start = performance.now(); + const onAdded = (state: PolylineState) => { + const r = roundRef.current; + if (!r.waiting || r.ids.has(state.id)) return; + r.ids.add(state.id); + if (r.ids.size === r.total) { + r.waiting = false; + onAllAddedRef.current(); + } + }; + const list = doc.roads.map(road => { + const style = ROAD_STYLES[road.cls]; + return createPolylineState({ + id: road.id, + points: toPoints(road.path), + strokeColor: style.color, + strokeWidth: style.width, + zIndex: style.zIndex, + onClick: event => onTapRef.current(road, event.clicked), + onAdded, + }); + }); + return { list, buildMs: performance.now() - start }; + }, [doc]); + const states = built?.list ?? null; + const buildMs = built?.buildMs ?? 0; + + // A new round each time the list goes onto a map (also another provider's). + useLayoutEffect(() => { + if (!states || !mounted) return; + commitRef.current = performance.now(); + roundRef.current = { round: roundRef.current.round + 1, ids: new Set(), total: states.length, waiting: true }; + setRound(roundRef.current.round); + setAddedMs(null); + setFrameMs(null); + setProgress({ phase: 'draw' }); + }, [states, mounted, provider]); + + // Switching: take the roads off the map, let that reach it, then hand them back + // with the new tiling, so every road is added again and calls onAdded again. + const switchTiling = (next: boolean) => { + if (next === tiled || !states) return; + setTap(null); + setMounted(false); + setTiled(next); + setProgress({ phase: 'draw' }); + void nextPaint().then(() => nextPaint()).then(() => setMounted(true)); + }; + + const counts = useMemo(() => { + const byClass = Object.fromEntries(ROAD_CLASSES.map(c => [c, 0])) as Record; + let vertices = 0; + for (const road of doc?.roads ?? []) { + byClass[road.cls]++; + vertices += road.path.length / 2; + } + return { byClass, vertices }; + }, [doc]); + + const tapLength = useMemo(() => (tap?.road ? roadLength(toPoints(tap.road.path)) : null), [tap]); + + return ( + + {states && mounted && } + {initial.stack && } + {progress && } + {tap?.road && tap.point && tapLength != null && ( + + + + )} + +
+ + +
+ {loadError &&

{loadError}

} + + {doc ? ( +

+ {t({ + en: `${doc.roads.length.toLocaleString()} roads, ${counts.vertices.toLocaleString()} vertices`, + ja: `道路 ${doc.roads.length.toLocaleString()} 本・頂点 ${counts.vertices.toLocaleString()} 個`, + 'es-419': `${doc.roads.length.toLocaleString()} calles, ${counts.vertices.toLocaleString()} vértices`, + de: `${doc.roads.length.toLocaleString()} Straßen, ${counts.vertices.toLocaleString()} Eckpunkte`, + th: `ถนน ${doc.roads.length.toLocaleString()} เส้น จุดยอด ${counts.vertices.toLocaleString()} จุด`, + hi: `${doc.roads.length.toLocaleString()} सड़कें, ${counts.vertices.toLocaleString()} शीर्ष`, + })} +
+ + {t({ + en: `load ${loadMs.toFixed(0)} ms, states ${buildMs.toFixed(0)} ms`, + ja: `読み込み ${loadMs.toFixed(0)} ms・state 作成 ${buildMs.toFixed(0)} ms`, + 'es-419': `carga ${loadMs.toFixed(0)} ms, estados ${buildMs.toFixed(0)} ms`, + de: `Laden ${loadMs.toFixed(0)} ms, States ${buildMs.toFixed(0)} ms`, + th: `โหลด ${loadMs.toFixed(0)} ms สร้าง state ${buildMs.toFixed(0)} ms`, + hi: `लोड ${loadMs.toFixed(0)} ms, state ${buildMs.toFixed(0)} ms`, + })} + {addedMs != null && ( + <> +
+ {t({ + en: `${tiled ? 'Tiles' : 'Native'}: every onAdded ${addedMs.toFixed(0)} ms${frameMs != null ? `, next frame ${frameMs.toFixed(0)} ms` : ''}`, + ja: `${tiled ? 'タイル' : 'ネイティブ'}: 全 onAdded まで ${addedMs.toFixed(0)} ms${frameMs != null ? `・次のフレームまで ${frameMs.toFixed(0)} ms` : ''}`, + 'es-419': `${tiled ? 'Teselas' : 'Nativo'}: todos los onAdded ${addedMs.toFixed(0)} ms${frameMs != null ? `, siguiente cuadro ${frameMs.toFixed(0)} ms` : ''}`, + de: `${tiled ? 'Kacheln' : 'Nativ'}: alle onAdded ${addedMs.toFixed(0)} ms${frameMs != null ? `, nächster Frame ${frameMs.toFixed(0)} ms` : ''}`, + th: `${tiled ? 'ไทล์' : 'เนทีฟ'}: onAdded ครบ ${addedMs.toFixed(0)} ms${frameMs != null ? ` เฟรมถัดไป ${frameMs.toFixed(0)} ms` : ''}`, + hi: `${tiled ? 'टाइलें' : 'नेटिव'}: सभी onAdded ${addedMs.toFixed(0)} ms${frameMs != null ? `, अगला फ़्रेम ${frameMs.toFixed(0)} ms` : ''}`, + })} + + )} +
+

+ ) : ( +

…

+ )} + {tap && ( +

+ {tap.road + ? `${t(ROAD_STYLES[tap.road.cls].label)}${tap.road.name ? ` · ${tap.road.name}` : ''}${tapLength != null ? ` · ${formatLength(tapLength)}` : ''}` + : t({ en: 'No road here', ja: 'ここに道路はありません', 'es-419': 'Aquí no hay calle', de: 'Hier ist keine Straße', th: 'ไม่มีถนนตรงนี้', hi: 'यहाँ कोई सड़क नहीं' })} +

+ )} +

+ {doc ? `${doc.attribution} (${doc.license})` : null} +

+
+
+ ); +} + +function RoadLegend({ counts }: { counts: Record }) { + const { t } = useSampleI18n(); + return ( +
    + {ROAD_CLASSES.map(cls => { + const style = ROAD_STYLES[cls]; + return ( +
  • + + {t(style.label)} + {counts[cls] > 0 && {counts[cls].toLocaleString()}} +
  • + ); + })} +
+ ); +} + +/** What a tapped road carries, shown in an InfoBubble at the nearest point on it. */ +function RoadInfo({ road, length }: { road: Road; length: number }) { + const { t } = useSampleI18n(); + const rows: [string, string][] = [ + [t({ en: 'Class', ja: '種別', 'es-419': 'Tipo', de: 'Klasse', th: 'ประเภท', hi: 'वर्ग' }), t(ROAD_STYLES[road.cls].label)], + ]; + if (road.name) rows.push([t({ en: 'Name', ja: '名前', 'es-419': 'Nombre', de: 'Name', th: 'ชื่อ', hi: 'नाम' }), road.name]); + rows.push([t({ en: 'Length', ja: '長さ', 'es-419': 'Longitud', de: 'Länge', th: 'ความยาว', hi: 'लंबाई' }), formatLength(length)]); + return ( + + + {rows.map(([key, value]) => ( + + + + + ))} + +
{key}{value}
+ ); +} diff --git a/examples/basic/src/pages/polyline/boston/StackCheck.tsx b/examples/basic/src/pages/polyline/boston/StackCheck.tsx new file mode 100644 index 0000000..05527ad --- /dev/null +++ b/examples/basic/src/pages/polyline/boston/StackCheck.tsx @@ -0,0 +1,44 @@ +import { useMemo } from 'react'; +import { createCircleState, createGeoPoint, createMarkerState, createPolygonState, type GeoPoint } from '@mapconductor/js-sdk-core'; +import { Circle, Marker, Polygons } from '@mapconductor/js-sdk-react'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; + +/** + * `?stack=1` on the roads page: other overlays where the roads are, to see the stack. + * Bottom to top it must read: polygon tiles (a grid of 2,500 squares, enough to be tiled) < + * the circle < the road tiles < the marker. + */ +export function StackCheck({ center }: { center: GeoPoint }) { + const loading = useLoadingOverlay(); + const squares = useMemo(() => { + const out = []; + const step = 0.0004, size = 0.0003; + for (let i = 0; i < 50; i++) { + for (let j = 0; j < 50; j++) { + const lat = center.latitude - 0.01 + i * step, lng = center.longitude - 0.01 + j * step; + const p = (a: number, b: number) => createGeoPoint({ latitude: a, longitude: b }); + out.push(createPolygonState({ + id: `stack-sq-${i}-${j}`, + points: [p(lat, lng), p(lat, lng + size), p(lat + size, lng + size), p(lat + size, lng)], + fillColor: 'rgba(124, 58, 237, 0.85)', + strokeColor: 'transparent', + strokeWidth: 0, + })); + } + } + return out; + }, [center]); + const circle = useMemo(() => createCircleState({ + id: 'stack-circle', center: createGeoPoint({ latitude: center.latitude + 0.002, longitude: center.longitude + 0.003 }), + radiusMeters: 180, fillColor: 'rgba(14, 165, 233, 0.9)', strokeColor: '#0369a1', strokeWidth: 2, + }), [center]); + const marker = useMemo(() => createMarkerState({ id: 'stack-marker', position: center }), [center]); + return ( + <> + + + + + + ); +} diff --git a/examples/basic/src/pages/polyline/boston/bostonRoadsData.ts b/examples/basic/src/pages/polyline/boston/bostonRoadsData.ts new file mode 100644 index 0000000..33bfcf8 --- /dev/null +++ b/examples/basic/src/pages/polyline/boston/bostonRoadsData.ts @@ -0,0 +1,34 @@ +/** + * Loads the roads the Boston roads page draws (`public/boston/boston-city-roads.bin`): + * every road of the City of Boston from Overture Maps (`transportation/segment`, + * road subtype), cut at the city boundary. The file format is in roadsFile.ts; + * `tools/boston/` builds the file from the official sources (see its README). + */ +import { readWithProgress, nextPaint, type LoadProgress } from '../../polygon/boston/bostonData'; +import { decodeRoads, type Road } from './roadsFile'; + +export { nextPaint, type LoadProgress }; +export { ROAD_CLASSES, type Road, type RoadClass } from './roadsFile'; + +export interface RoadsDoc { + attribution: string; + license: string; + roads: Road[]; +} + +const SOURCE = { + file: 'boston/boston-city-roads.bin', + attribution: '© OpenStreetMap contributors, TomTom — via Overture Maps Foundation', + license: 'ODbL 1.0', +}; + +export async function loadRoads(onProgress: (progress: LoadProgress) => void = () => {}): Promise { + const response = await fetch(`${import.meta.env.BASE_URL}${SOURCE.file}`); + if (!response.ok) throw new Error(`${SOURCE.file}: ${response.status}`); + const bytes = await readWithProgress(response, onProgress); + onProgress({ phase: 'decode' }); + // Decoding blocks the main thread; let the overlay show the new phase first. + await nextPaint(); + return { attribution: SOURCE.attribution, license: SOURCE.license, roads: decodeRoads(bytes, 'road') }; +} + diff --git a/examples/basic/src/pages/polyline/boston/roadsFile.ts b/examples/basic/src/pages/polyline/boston/roadsFile.ts new file mode 100644 index 0000000..4a0c7a1 --- /dev/null +++ b/examples/basic/src/pages/polyline/boston/roadsFile.ts @@ -0,0 +1,96 @@ +/** + * The roads file of the Boston roads page (`public/boston/boston-city-roads.bin`), + * read without anything from the page so the tests can load it in Node. + * + * The file carries no ids: this is a polyline demo, and a road's id on the map + * is its index in the file. + * + * Binary layout: MCPG v2 (see polygon/boston/bostonData.ts) with two more bits + * in `fields`: + * 16 = road class: u8 after the name, the index in ROAD_CLASSES + * 32 = lines: each record's "ring" is an open polyline. Every vertex is + * stored (n >= 2) and the reader does not close it. + * The roads file has fields = 8 | 16 | 32 (name, class, lines), digits = 5, + * and one polyline per record: + * varint name length (0 = none), UTF-8 · u8 class · varint 1 · varint n · + * n x (svarint dLat, svarint dLng) + */ + +/** The road classes, in the order the file stores them (a class is its index here). */ +export const ROAD_CLASSES = ['highway', 'primary', 'secondary', 'tertiary', 'local', 'service', 'path'] as const; + +export type RoadClass = (typeof ROAD_CLASSES)[number]; + +export interface Road { + id: string; + cls: RoadClass; + name?: string; + /** The polyline as flat [lng, lat, lng, lat, ...], open. */ + path: number[]; +} + +const FIELD_HEIGHT = 1; +const FIELD_USE = 2; +const FIELD_AREA = 4; +const FIELD_NAME = 8; +const FIELD_CLASS = 16; +const FIELD_LINES = 32; + +/** Decodes an MCPG v2 file of polylines (the lines bit set); road `i` gets the id "-". */ +export function decodeRoads(bytes: Uint8Array, idPrefix: string): Road[] { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const magic = String.fromCharCode(bytes[0], bytes[1], bytes[2], bytes[3]); + if (magic !== 'MCPG' || view.getUint32(4, true) !== 2) throw new Error('not an MCPG v2 file'); + const count = view.getUint32(8, true); + const fields = bytes[12]; + if (!(fields & FIELD_LINES)) throw new Error('not a file of polylines (no lines bit)'); + if (!(fields & FIELD_CLASS)) throw new Error('no road class in the file'); + const scale = 10 ** bytes[13]; + let offset = 14; + // Values stay below 2^31 here, so the shifts and the zigzag work on 32-bit ints. + const varint = (): number => { + let value = 0; + let shift = 0; + for (;;) { + const b = bytes[offset++]; + value |= (b & 0x7f) << shift; + if (b < 0x80) return value >>> 0; + shift += 7; + } + }; + const svarint = (): number => { + const v = varint(); + return (v >>> 1) ^ -(v & 1); + }; + const text = new TextDecoder(); + const roads: Road[] = []; + let lat = 0; + let lng = 0; + for (let i = 0; i < count; i++) { + // Fields a roads file does not carry are still skipped by their layout. + if (fields & FIELD_HEIGHT) varint(); + if (fields & FIELD_USE) offset++; + if (fields & FIELD_AREA) offset++; + let name: string | undefined; + if (fields & FIELD_NAME) { + const length = varint(); + if (length > 0) name = text.decode(bytes.subarray(offset, offset + length)); + offset += length; + } + const cls = ROAD_CLASSES[bytes[offset++]]; + const pathCount = varint(); + for (let r = 0; r < pathCount; r++) { + const vertices = varint(); + const path = new Array(vertices * 2); + for (let v = 0; v < vertices; v++) { + lat += svarint(); + lng += svarint(); + path[v * 2] = lng / scale; + path[v * 2 + 1] = lat / scale; + } + // One polyline per record in the roads file; were there more, each would be a road. + roads.push({ id: `${idPrefix}-${pathCount === 1 ? i : `${i}.${r}`}`, cls, name, path }); + } + } + return roads; +} diff --git a/examples/basic/src/pages/polyline/click/PolylineClickPage.tsx b/examples/basic/src/pages/polyline/click/PolylineClickPage.tsx index 052eff9..53e8df6 100644 --- a/examples/basic/src/pages/polyline/click/PolylineClickPage.tsx +++ b/examples/basic/src/pages/polyline/click/PolylineClickPage.tsx @@ -12,10 +12,12 @@ import { Markers, Polyline } from '@mapconductor/js-sdk-react'; import { ControlPanel } from '../../../components/ControlPanel'; import { MapViewContainer } from '../../../MapViewContainer'; import { useSampleI18n } from '../../../samples/i18n'; +import { LoadingOverlay, useLoadingOverlay } from '../../../components/LoadingOverlay'; const INIT_CAMERA = { lat: 35.548852, lng: 139.784086, zoom: 4 }; export function PolylineClickPage() { + const loading = useLoadingOverlay(); const { t } = useSampleI18n(); const [clickMarkers, setClickMarkers] = useState([]); // The Android polyline-click sample draws no waypoint markers, so neither do @@ -52,7 +54,8 @@ export function PolylineClickPage() { - + +

{t( diff --git a/examples/basic/src/providers/singleton/ArcGISSingletonView.tsx b/examples/basic/src/providers/singleton/ArcGISSingletonView.tsx index aaa9f5f..c374654 100644 --- a/examples/basic/src/providers/singleton/ArcGISSingletonView.tsx +++ b/examples/basic/src/providers/singleton/ArcGISSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { ArcGISMapView, ArcGISMapView2D, type ArcGISMapViewStateInterface } from '@mapconductor/react-for-arcgis'; import type { SingletonMapContent } from './types'; @@ -14,6 +15,8 @@ export default function ArcGISSingletonView({ state, content, useSceneView }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/AzureMapsSingletonView.tsx b/examples/basic/src/providers/singleton/AzureMapsSingletonView.tsx index 459f95e..dd48204 100644 --- a/examples/basic/src/providers/singleton/AzureMapsSingletonView.tsx +++ b/examples/basic/src/providers/singleton/AzureMapsSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { AzureMapsMapView, type AzureMapsViewStateInterface } from '@mapconductor/react-for-azuremaps'; import '@mapconductor/react-for-azuremaps/style.css'; @@ -13,6 +14,8 @@ export default function AzureMapsSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/CesiumSingletonView.tsx b/examples/basic/src/providers/singleton/CesiumSingletonView.tsx index 5db3f45..cbb6372 100644 --- a/examples/basic/src/providers/singleton/CesiumSingletonView.tsx +++ b/examples/basic/src/providers/singleton/CesiumSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { CesiumMapView, type CesiumMapViewStateInterface } from '@mapconductor/react-for-cesium'; import '@mapconductor/react-for-cesium/style.css'; @@ -13,6 +14,8 @@ export default function CesiumSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/DeckGLSingletonView.tsx b/examples/basic/src/providers/singleton/DeckGLSingletonView.tsx index 8db268d..5fe27b7 100644 --- a/examples/basic/src/providers/singleton/DeckGLSingletonView.tsx +++ b/examples/basic/src/providers/singleton/DeckGLSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { DeckGLMapView, type DeckGLMapViewStateInterface } from '@mapconductor/react-for-deckgl'; import type { SingletonMapContent } from './types'; @@ -12,6 +13,8 @@ export default function DeckGLSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/HereSingletonView.tsx b/examples/basic/src/providers/singleton/HereSingletonView.tsx index 5f146c9..91825fc 100644 --- a/examples/basic/src/providers/singleton/HereSingletonView.tsx +++ b/examples/basic/src/providers/singleton/HereSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment, useMemo } from 'react'; import { HereMapView2D, type HereViewStateInterface } from '@mapconductor/react-for-here'; import type { SingletonMapContent } from './types'; @@ -21,6 +22,8 @@ export default function HereSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/LeafletSingletonView.tsx b/examples/basic/src/providers/singleton/LeafletSingletonView.tsx index f073649..6eacc1d 100644 --- a/examples/basic/src/providers/singleton/LeafletSingletonView.tsx +++ b/examples/basic/src/providers/singleton/LeafletSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { LeafletMapView, type LeafletMapViewStateInterface } from '@mapconductor/react-for-leaflet'; import '@mapconductor/react-for-leaflet/style.css'; @@ -13,6 +14,8 @@ export default function LeafletSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/LongdoSingletonView.tsx b/examples/basic/src/providers/singleton/LongdoSingletonView.tsx index 44623ea..6cd0bb7 100644 --- a/examples/basic/src/providers/singleton/LongdoSingletonView.tsx +++ b/examples/basic/src/providers/singleton/LongdoSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { LongdoMapView2D, type LongdoViewStateInterface } from '@mapconductor/react-for-longdo'; import type { SingletonMapContent } from './types'; @@ -20,6 +21,8 @@ export default function LongdoSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/MapKitSingletonView.tsx b/examples/basic/src/providers/singleton/MapKitSingletonView.tsx index f1eabb8..8b04562 100644 --- a/examples/basic/src/providers/singleton/MapKitSingletonView.tsx +++ b/examples/basic/src/providers/singleton/MapKitSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { MapKitMapView, type MapKitViewStateInterface } from '@mapconductor/react-for-mapkit'; import type { SingletonMapContent } from './types'; @@ -12,6 +13,8 @@ export default function MapKitSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/MapLibreSingletonView.tsx b/examples/basic/src/providers/singleton/MapLibreSingletonView.tsx index 44e4fe3..8be4b8f 100644 --- a/examples/basic/src/providers/singleton/MapLibreSingletonView.tsx +++ b/examples/basic/src/providers/singleton/MapLibreSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { MapLibreMapView, MapLibreMapView2D, type MapLibreViewStateInterface } from '@mapconductor/react-for-maplibre'; import '@mapconductor/react-for-maplibre/style.css'; @@ -15,6 +16,8 @@ export default function MapLibreSingletonView({ state, content, useGlobe }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/MapTilerSingletonView.tsx b/examples/basic/src/providers/singleton/MapTilerSingletonView.tsx index 6868d09..45e6265 100644 --- a/examples/basic/src/providers/singleton/MapTilerSingletonView.tsx +++ b/examples/basic/src/providers/singleton/MapTilerSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { MapTilerMapView2D, type MapTilerViewStateInterface } from '@mapconductor/react-for-maptiler'; import '@mapconductor/react-for-maptiler/style.css'; @@ -21,6 +22,8 @@ export default function MapTilerSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/MapboxSingletonView.tsx b/examples/basic/src/providers/singleton/MapboxSingletonView.tsx index c8cc1bb..3d9f4f2 100644 --- a/examples/basic/src/providers/singleton/MapboxSingletonView.tsx +++ b/examples/basic/src/providers/singleton/MapboxSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { MapBoxMapView2D, type MapboxViewStateInterface } from '@mapconductor/react-for-mapbox'; import '@mapconductor/react-for-mapbox/style.css'; @@ -23,6 +24,8 @@ export default function MapboxSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/MapplsSingletonView.tsx b/examples/basic/src/providers/singleton/MapplsSingletonView.tsx index 388b745..acfe461 100644 --- a/examples/basic/src/providers/singleton/MapplsSingletonView.tsx +++ b/examples/basic/src/providers/singleton/MapplsSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { MapplsMapView2D, type MapplsViewStateInterface } from '@mapconductor/react-for-mappls'; import type { SingletonMapContent } from './types'; @@ -20,6 +21,8 @@ export default function MapplsSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/OpenLayersSingletonView.tsx b/examples/basic/src/providers/singleton/OpenLayersSingletonView.tsx index 3464f4a..77d96af 100644 --- a/examples/basic/src/providers/singleton/OpenLayersSingletonView.tsx +++ b/examples/basic/src/providers/singleton/OpenLayersSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { OpenLayersMapView, type OpenLayersMapViewStateInterface } from '@mapconductor/react-for-openlayers'; import '@mapconductor/react-for-openlayers/style.css'; @@ -13,6 +14,8 @@ export default function OpenLayersSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/TomTomSingletonView.tsx b/examples/basic/src/providers/singleton/TomTomSingletonView.tsx index 4039466..672bfc4 100644 --- a/examples/basic/src/providers/singleton/TomTomSingletonView.tsx +++ b/examples/basic/src/providers/singleton/TomTomSingletonView.tsx @@ -1,3 +1,4 @@ +import { CircleTilingOptions, PolylineTilingOptions } from '@mapconductor/js-sdk-core'; import { Fragment } from 'react'; import { TomTomMapView2D, type TomTomViewStateInterface } from '@mapconductor/react-for-tomtom'; import type { SingletonMapContent } from './types'; @@ -20,6 +21,8 @@ export default function TomTomSingletonView({ state, content }: { cameraRestriction={content?.cameraRestriction} mapStyle={content?.mapStyle} onStyleDiagnostics={content?.onStyleDiagnostics} + polylineTilingOptions={content?.polylineTilingOptions ?? PolylineTilingOptions.Default} + circleTilingOptions={content?.circleTilingOptions ?? CircleTilingOptions.Default} onMapClick={content?.onMapClick} onCameraMoveStart={content?.onCameraMoveStart} onCameraMove={content?.onCameraMove} diff --git a/examples/basic/src/providers/singleton/types.ts b/examples/basic/src/providers/singleton/types.ts index b94431a..6de7ceb 100644 --- a/examples/basic/src/providers/singleton/types.ts +++ b/examples/basic/src/providers/singleton/types.ts @@ -1,4 +1,4 @@ -import type { CameraRestriction, GeoPoint, MapCameraPosition, MapViewStyle } from '@mapconductor/js-sdk-core'; +import type { CameraRestriction, GeoPoint, MapCameraPosition, MapViewStyle, PolylineTilingOptions, CircleTilingOptions } from '@mapconductor/js-sdk-core'; import type { ReactNode } from 'react'; export interface SingletonMapContent { @@ -28,4 +28,15 @@ export interface SingletonMapContent { */ mapStyle?: MapViewStyle | null; onStyleDiagnostics?: (diagnostics: readonly string[]) => void; + /** + * ページが指定するポリラインのタイル化の条件。共有インスタンスなので、ページを離れたら + * 既定(`PolylineTilingOptions.Default`)に戻す(各ビューが `?? Default` で渡す)。 + * 次にポリラインを渡したときから効く。 + */ + polylineTilingOptions?: PolylineTilingOptions; + /** + * ページが指定する円のタイル化の条件。ポリラインと同じく、ページを離れたら既定 + * (`CircleTilingOptions.Default`)に戻り、次に円を渡したときから効く。 + */ + circleTilingOptions?: CircleTilingOptions; } diff --git a/examples/basic/src/providers/types.ts b/examples/basic/src/providers/types.ts index 35f44a1..cb6ac90 100644 --- a/examples/basic/src/providers/types.ts +++ b/examples/basic/src/providers/types.ts @@ -8,6 +8,8 @@ import type { MapViewStateInterface, MarkerTilingOptions, MapViewStyle, + PolylineTilingOptions, + CircleTilingOptions, } from '@mapconductor/js-sdk-core'; import type { InitialCamera } from '../common'; @@ -32,4 +34,8 @@ export interface ProviderViewProps { /** 地図の見た目そのもの。`createVectorStyle()` が作る。 */ mapStyle?: MapViewStyle | null; onStyleDiagnostics?: (diagnostics: readonly string[]) => void; + /** When the shared map draws this page's polylines as tiles (the default when omitted). */ + polylineTilingOptions?: PolylineTilingOptions; + /** When the shared map draws this page's circles as tiles (the default when omitted). */ + circleTilingOptions?: CircleTilingOptions; } diff --git a/examples/basic/src/samples/documentation/index.ts b/examples/basic/src/samples/documentation/index.ts index 3be4ffe..46625dd 100644 --- a/examples/basic/src/samples/documentation/index.ts +++ b/examples/basic/src/samples/documentation/index.ts @@ -1,3 +1,4 @@ +import antennaHorizons from './pages/antenna-horizons'; import type { SupportedLanguage } from '../sampleRegistry'; import { PROVIDER_IMPORTS, @@ -13,6 +14,7 @@ import mapDesign from './pages/map-design'; import flyTo from './pages/fly-to'; import tilt from './pages/tilt'; import visibleRegion from './pages/visible-region'; +import projectedCoordinates from './pages/projected-coordinates'; import cameraSync from './pages/camera-sync'; import marker from './pages/marker'; import markerLabelPosition from './pages/marker-label-position'; @@ -38,17 +40,24 @@ import geojsonLayer from './pages/geojson-layer'; import kmlLayer from './pages/kml-layer'; import heatmapLayer from './pages/heatmap-layer'; import threejsObject from './pages/threejs-object'; +import fitBounds from './pages/fit-bounds'; +import cameraRestriction from './pages/camera-restriction'; +import uiSettings from './pages/ui-settings'; +import streetTree from './pages/street-tree'; +import styleAdjustments from './pages/style-adjustments'; export type { SamplePageDoc } from './types'; /** Every sample page's documentation, keyed by its route id. */ const DOCUMENTATION: Record = { + 'antenna-horizons': antennaHorizons, 'hello-map': helloMap, map, 'map-design': mapDesign, 'fly-to': flyTo, tilt, 'visible-region': visibleRegion, + 'projected-coordinates': projectedCoordinates, 'camera-sync': cameraSync, marker, 'marker-label-position': markerLabelPosition, @@ -74,6 +83,11 @@ const DOCUMENTATION: Record = { 'kml-layer': kmlLayer, 'heatmap-layer': heatmapLayer, 'threejs-object': threejsObject, + 'fit-bounds': fitBounds, + 'camera-restriction': cameraRestriction, + 'ui-settings': uiSettings, + 'street-tree': streetTree, + 'style-adjustments': styleAdjustments, }; const FALLBACK: SamplePageDoc = { @@ -129,6 +143,7 @@ const SECTION_COMMENTS: Record').join(``); } @@ -149,7 +164,10 @@ const IMPORT_DEFINITIONS: readonly ImportDefinition[] = [ values: [ 'ColorDefaultIcon', 'DefaultMarkerIcon', + 'ImageIcon', + 'MapUISettings', 'MarkerAnimation', + 'CircleTilingOptions', 'MarkerTilingOptions', 'PolygonManager', 'RasterLayerSource', @@ -178,6 +196,7 @@ const IMPORT_DEFINITIONS: readonly ImportDefinition[] = [ { source: '@mapconductor/js-sdk-react', values: [ + 'Circles', 'Circle', 'GroundImage', 'InfoBubble', @@ -195,9 +214,17 @@ const IMPORT_DEFINITIONS: readonly ImportDefinition[] = [ ...PROVIDER_IMPORTS, { source: '@mapconductor/react-geojson', - values: ['GeoJSONLayer', 'GeoJSONLayerState', 'colorArgb'], + values: ['GeoJSONLayer', 'GeoJSONLayerState', 'GeoJSONParser', 'colorArgb'], types: ['GeoJSONFeatureData'], }, + { + source: '@mapconductor/react-vectortile', + values: ['VectorTileLayer'], + }, + { + source: '@mapconductor/js-vectorstyle', + values: ['buildStyleRules', 'LayerRole'], + }, { source: '@mapconductor/react-kml', values: ['KMLLayer', 'KMLLayerState', 'KMLParser', 'KMLLoader'], @@ -210,11 +237,14 @@ const IMPORT_DEFINITIONS: readonly ImportDefinition[] = [ { source: '@mapconductor/react-marker-clustering', values: ['MarkerClusterGroup'], + types: ['MarkerCluster'], }, ]; function usesIdentifier(code: string, identifier: string): boolean { - return new RegExp(`\\b${identifier}\\b`).test(code); + // Names in comments and data (e.g. GeoJSON's type: 'Polygon') are not imports. + const source = code.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`/g, ''); + return new RegExp(`\\b${identifier}\\b`).test(source); } function formatImport(definition: ImportDefinition, code: string): string | null { @@ -238,6 +268,13 @@ function importCode(code: string): string { if (usesIdentifier(code, 'THREE')) { imports.splice(1, 0, "import * as THREE from 'three';"); } + for (const definition of PROVIDER_IMPORTS) { + if (['maplibre', 'mapbox', 'leaflet', 'openlayers', 'maptiler', 'azuremaps', 'cesium'] + .some(name => definition.source === `@mapconductor/react-for-${name}`) + && definition.values.some(name => usesIdentifier(code, name))) { + imports.push(`import '${definition.source}/style.css';`); + } + } return imports.join('\n'); } @@ -247,20 +284,25 @@ export function getSampleDocumentation( language: SupportedLanguage = 'en', ): SamplePageDoc { const documentation = DOCUMENTATION[page ?? ''] ?? FALLBACK; - const provider = providerCode(providerName); + const provider = providerCode(providerName, documentation.camera); const providerSetup = page === 'camera-sync' - ? initialCameraCode() + ? initialCameraCode(documentation.camera) : provider.stateSetup; const comments = SECTION_COMMENTS[language]; const stateSection = documentation.state - ? [`// (2) ${comments.state}`, documentation.state].join('\n') + ? [`// (2) ${comments.state}`, adaptProviderView(documentation.state, provider)].join('\n') : ''; - const mainCode = [ + const body = [ `// (1) ${comments.map}`, providerSetup, stateSection, `// (${documentation.state ? 3 : 2}) ${comments.render}`, - adaptProviderView(documentation.code, provider), + `return (\n

\n${adaptProviderView(documentation.code, provider).split('\n').map(line => ` ${line}`).join('\n')}\n
\n);`, + ].filter(Boolean).join('\n\n'); + const mainCode = [ + page === 'camera-sync' ? undefined : provider.prerequisites, + documentation.helpers, + `export default function App() {\n${body.split('\n').map(line => line ? ` ${line}` : '').join('\n')}\n}`, ].filter(Boolean).join('\n\n'); return { ...documentation, diff --git a/examples/basic/src/samples/documentation/pages/antenna-horizons.ts b/examples/basic/src/samples/documentation/pages/antenna-horizons.ts new file mode 100644 index 0000000..97fe850 --- /dev/null +++ b/examples/basic/src/samples/documentation/pages/antenna-horizons.ts @@ -0,0 +1,44 @@ +import type { SamplePageDoc } from '../types'; +const doc: SamplePageDoc = { + "camera": { + "latitude": 39, + "longitude": -98, + "zoom": 4 + }, + "code": "\n \n", + "state": "const [states, setStates] = useState[]>([]);\nuseEffect(() => {\n if (typeof window === 'undefined') return;\n const abort = new AbortController();\n fetch('/antennas/us-antennas.bin', { signal: abort.signal })\n .then(response => { if (!response.ok) throw new Error('FCC data download failed'); return response.arrayBuffer(); })\n .then(buffer => setStates(decodeAntennas(buffer).map(a => createCircleState({\n center: createGeoPoint(a), radiusMeters: horizonMeters(a.height), geodesic: true,\n id: `asr-${a.registration}`, fillColor: 'rgba(37,99,235,0.035)', strokeWidth: 0.5,\n }))))\n .catch(error => { if (!abort.signal.aborted) console.error(error); });\n return () => abort.abort();\n}, []);", + "helpers": "interface Antenna { latitude: number; longitude: number; height: number; registration: number }\nfunction horizonMeters(height: number): number {\n const r = 6378137;\n return r * (Math.acos(r / (r + height)) + Math.acos(r / (r + 1.5)));\n}\nfunction decodeAntennas(buffer: ArrayBuffer): Antenna[] {\n const v = new DataView(buffer);\n if (v.byteLength < 8 || v.getUint32(0, false) !== 0x4d434341) throw new Error('Invalid antenna file');\n const count = v.getUint32(4, true);\n if (v.byteLength !== 8 + count * 16) throw new Error('Truncated antenna file');\n return Array.from({ length: count }, (_, i) => {\n const p = 8 + i * 16;\n const a = { latitude: v.getFloat32(p, true), longitude: v.getFloat32(p + 4, true), height: v.getFloat32(p + 8, true), registration: v.getUint32(p + 12, true) };\n if (!Number.isFinite(a.latitude) || Math.abs(a.latitude) > 90 || !Number.isFinite(a.longitude) || Math.abs(a.longitude) > 180 || !(a.height > 0 && a.height <= 1000)) throw new Error('Invalid antenna record');\n return a;\n });\n}\n", + "explanation": { + "en": [ + "Draw 141,979 FCC antenna structures using one Circles component. The binary file is bundled with this example at /antennas/us-antennas.bin.", + "The radius is a spherical geometric horizon derived from structure height and a 1.5 m receiver, not actual radio coverage. geodesic=true keeps the radius a surface distance.", + "FCC ASR includes non-cellular structures. Terrain, radiation patterns and refraction are omitted; source and reproducible packing instructions are in tools/antennas." + ], + "ja": [ + "FCC のアンテナ構造物141,979件を Circles で一括登録します。データは example の /antennas/us-antennas.bin に同梱しています。", + "高さと受信点1.5 mから球面上の見通し距離を計算し、geodesic=true で描きます。実際の電波カバー範囲ではありません。", + "携帯基地局以外も含み、地形・指向性・屈折は考慮しません。出典と再生成手順は tools/antennas にあります。" + ], + "es-419": [ + "Draw 141,979 FCC antenna structures using one Circles component. The binary file is bundled with this example at /antennas/us-antennas.bin.", + "The radius is a spherical geometric horizon derived from structure height and a 1.5 m receiver, not actual radio coverage. geodesic=true keeps the radius a surface distance.", + "FCC ASR includes non-cellular structures. Terrain, radiation patterns and refraction are omitted; source and reproducible packing instructions are in tools/antennas." + ], + "de": [ + "Draw 141,979 FCC antenna structures using one Circles component. The binary file is bundled with this example at /antennas/us-antennas.bin.", + "The radius is a spherical geometric horizon derived from structure height and a 1.5 m receiver, not actual radio coverage. geodesic=true keeps the radius a surface distance.", + "FCC ASR includes non-cellular structures. Terrain, radiation patterns and refraction are omitted; source and reproducible packing instructions are in tools/antennas." + ], + "th": [ + "Draw 141,979 FCC antenna structures using one Circles component. The binary file is bundled with this example at /antennas/us-antennas.bin.", + "The radius is a spherical geometric horizon derived from structure height and a 1.5 m receiver, not actual radio coverage. geodesic=true keeps the radius a surface distance.", + "FCC ASR includes non-cellular structures. Terrain, radiation patterns and refraction are omitted; source and reproducible packing instructions are in tools/antennas." + ], + "hi": [ + "Draw 141,979 FCC antenna structures using one Circles component. The binary file is bundled with this example at /antennas/us-antennas.bin.", + "The radius is a spherical geometric horizon derived from structure height and a 1.5 m receiver, not actual radio coverage. geodesic=true keeps the radius a surface distance.", + "FCC ASR includes non-cellular structures. Terrain, radiation patterns and refraction are omitted; source and reproducible packing instructions are in tools/antennas." + ] + } +}; +export default doc; diff --git a/examples/basic/src/samples/documentation/pages/camera-restriction.ts b/examples/basic/src/samples/documentation/pages/camera-restriction.ts new file mode 100644 index 0000000..d55c8ca --- /dev/null +++ b/examples/basic/src/samples/documentation/pages/camera-restriction.ts @@ -0,0 +1,27 @@ +import type { SamplePageDoc } from '../types'; + +const doc: SamplePageDoc = { + state: `const [enabled, setEnabled] = useState(true); +const restriction = useMemo(() => ({ + bounds: createGeoRectBounds({ + southWest: createGeoPoint({ latitude: 35.63, longitude: 139.70 }), + northEast: createGeoPoint({ latitude: 35.75, longitude: 139.85 }), + }), + minZoom: 12, maxZoom: 16, +}), []);`, + code: ` + +`, + explanation: { + en: ['cameraRestriction limits the camera position and zoom. Toggle the restriction and request a position outside Tokyo to compare the behavior. Providers may reject the move or clamp it to the permitted range.'], + ja: ['cameraRestriction で移動可能な範囲とズームの上下限を指定します。制限の有無を切り替え、範囲外への移動を試せます。プロバイダーによって、移動を拒否するか、許可範囲へ補正します。'], + 'es-419': ['cameraRestriction limita la posición y el zoom. Activa la restricción y solicita una posición fuera de Tokio. El proveedor puede rechazar el movimiento o ajustarlo al rango permitido.'], + de: ['cameraRestriction begrenzt Position und Zoom. Schalten Sie die Begrenzung um und fordern Sie eine Position außerhalb Tokios an. Der Anbieter lehnt die Bewegung ab oder korrigiert sie auf den erlaubten Bereich.'], + th: ['cameraRestriction จำกัดตำแหน่งและซูม ลองสลับข้อจำกัดและขอเคลื่อนที่ออกนอกโตเกียว ผู้ให้บริการอาจปฏิเสธการเคลื่อนที่หรือปรับกลับเข้าสู่ขอบเขตที่อนุญาต'], + hi: ['cameraRestriction स्थिति और ज़ूम सीमित करता है। सीमा चालू करके टोक्यो के बाहर की स्थिति माँगें। प्रोवाइडर बदलाव रोक सकता है या अनुमत सीमा में सुधार सकता है।'], + }, +}; +export default doc; diff --git a/examples/basic/src/samples/documentation/pages/camera-sync.ts b/examples/basic/src/samples/documentation/pages/camera-sync.ts index ea06a78..b45e002 100644 --- a/examples/basic/src/samples/documentation/pages/camera-sync.ts +++ b/examples/basic/src/samples/documentation/pages/camera-sync.ts @@ -1,28 +1,17 @@ import type { SamplePageDoc } from '../types'; const doc: SamplePageDoc = { - code: `const syncCamera = ( - source: 'left' | 'right', - camera: MapCameraPosition, -) => { - const targetState = source === 'left' ? rightMapState : leftMapState; - const targetGuard = source === 'left' ? rightProgrammatic : leftProgrammatic; - if (targetGuard.current) return; - - targetGuard.current = true; - targetState.moveCameraTo(camera, 0); - requestAnimationFrame(() => { targetGuard.current = false; }); -}; - -
- syncCamera('left', camera)} - /> - syncCamera('right', camera)} - /> + code: `
+
{ activeMap.current = 'left'; }} + onWheel={() => { activeMap.current = 'left'; }} onFocusCapture={() => { activeMap.current = 'left'; }}> + syncCamera('left', camera)} /> +
+
{ activeMap.current = 'right'; }} + onWheel={() => { activeMap.current = 'right'; }} onFocusCapture={() => { activeMap.current = 'right'; }}> + syncCamera('right', camera)} /> +
`, state: `const leftMapState = useMapLibreViewState({ mapDesignType: MapLibreDesign.OsmBrightJa, @@ -32,38 +21,37 @@ const rightMapState = useLeafletMapViewState({ mapDesignType: LeafletDesign.OpenStreetMap, cameraPosition: initialCamera, }); -const leftProgrammatic = useRef(false); -const rightProgrammatic = useRef(false);`, +// Only the map being manipulated forwards camera events. Mirrored events cannot echo. +const activeMap = useRef<'left' | 'right' | null>(null); +const syncCamera = (source: 'left' | 'right', camera: MapCameraPosition) => { + if (activeMap.current !== source) return; + const targetState = source === 'left' ? rightMapState : leftMapState; + targetState.moveCameraTo(createMapCameraPosition({ position: camera.position, zoom: camera.zoom }), 0); +};`, explanation: { - en: [ - 'Forward camera changes between two independently rendered providers while suppressing feedback loops.', - 'This page intentionally runs two providers at once: useMapLibreViewState and useLeafletMapViewState each build a separate view state that starts from the same initialCamera.', - "syncCamera copies one map's camera onto the other with moveCameraTo(camera, 0), and a useRef guard released on the next requestAnimationFrame stops the mirrored update from echoing back.", + 'en': [ + 'Forward camera changes between MapLibre and Leaflet without a feedback loop.', + 'activeMap records which map receives pointer input. Only that map forwards its position and zoom with moveCameraTo; events from the other map are ignored.', ], - ja: [ - '独立して描画した2つのプロバイダー間でカメラ変更を転送し、相互更新のループを抑制します。', - 'このページだけは2種類のプロバイダーを同時に使います。useMapLibreViewState と useLeafletMapViewState が同じ initialCamera から別々の ViewState を作ります。', - 'syncCamera は一方のカメラを moveCameraTo(camera, 0) でもう一方へ転写し、useRef のガードを次の requestAnimationFrame で解除することで、転写した更新が跳ね返るのを防ぎます。', + 'ja': [ + 'MapLibre と Leaflet の間でカメラ位置とズームを同期します。', + 'ポインター操作を受けた地図を activeMap に記録し、その地図のカメライベントだけを転送します。移動先から返るイベントは転送しないため、相互更新がループしません。', ], 'es-419': [ - 'Transfiere los cambios de cámara entre dos proveedores renderizados de forma independiente y evita ciclos de actualización.', - 'Esta página usa dos proveedores a la vez a propósito: useMapLibreViewState y useLeafletMapViewState crean cada uno un estado de vista separado que parte de la misma initialCamera.', - 'syncCamera copia la cámara de un mapa sobre el otro con moveCameraTo(camera, 0), y un guard con useRef liberado en el siguiente requestAnimationFrame impide que la actualización reflejada rebote.', + 'Sincroniza la posición y el zoom entre MapLibre y Leaflet.', + 'activeMap registra el mapa que recibe la entrada del puntero. Solo ese mapa envía cambios mediante moveCameraTo; se ignoran los eventos del otro mapa.', ], - de: [ - 'Kameraänderungen zwischen zwei unabhängig gerenderten Anbietern weiterreichen und dabei Rückkopplungsschleifen unterdrücken.', - 'Diese Seite betreibt bewusst zwei Anbieter gleichzeitig: useMapLibreViewState und useLeafletMapViewState bauen je einen eigenen View-State auf, der von derselben initialCamera ausgeht.', - 'syncCamera überträgt die Kamera der einen Karte mit moveCameraTo(camera, 0) auf die andere, und eine useRef-Sperre, die erst im nächsten requestAnimationFrame gelöst wird, verhindert, dass die gespiegelte Aktualisierung zurückhallt.', + 'de': [ + 'Position und Zoom zwischen MapLibre und Leaflet synchronisieren.', + 'activeMap merkt sich die Karte mit der Zeigereingabe. Nur diese Karte leitet Änderungen mit moveCameraTo weiter; Ereignisse der anderen Karte werden ignoriert.', ], - th: [ - 'ส่งต่อการเปลี่ยนแปลงของกล้องระหว่างผู้ให้บริการสองรายที่เรนเดอร์แยกกัน พร้อมกันไม่ให้เกิดลูปป้อนกลับ', - 'หน้านี้ตั้งใจให้ผู้ให้บริการสองรายทำงานพร้อมกัน โดย useMapLibreViewState และ useLeafletMapViewState ต่างสร้างสถานะมุมมองของตัวเองที่เริ่มจาก initialCamera เดียวกัน', - 'syncCamera คัดลอกกล้องของแผนที่ฝั่งหนึ่งไปยังอีกฝั่งด้วย moveCameraTo(camera, 0) และตัวกันด้วย useRef ที่ปลดใน requestAnimationFrame ถัดไปจะหยุดไม่ให้การอัปเดตที่สะท้อนกลับวนซ้ำ', + 'th': [ + 'ซิงก์ตำแหน่งและระดับซูมระหว่าง MapLibre กับ Leaflet', + 'activeMap บันทึกแผนที่ที่รับการควบคุมจากตัวชี้ เฉพาะแผนที่นั้นจะส่งการเปลี่ยนแปลงด้วย moveCameraTo และละเว้นเหตุการณ์จากอีกแผนที่', ], - hi: [ - 'अलग-अलग रेंडर होने वाले दो प्रोवाइडर के बीच कैमरे के बदलाव आगे भेजें, और फ़ीडबैक लूप को रोकें।', - 'यह पेज जानबूझकर दो प्रोवाइडर एक साथ चलाता है: useMapLibreViewState और useLeafletMapViewState दोनों अपना-अपना व्यू स्टेट बनाते हैं, जो एक ही initialCamera से शुरू होता है।', - 'syncCamera एक मैप का कैमरा moveCameraTo(camera, 0) से दूसरे पर उतार देता है, और अगले requestAnimationFrame पर छूटने वाला useRef का पहरा उस नकल हुए अपडेट को वापस गूँजने नहीं देता।', + 'hi': [ + 'MapLibre और Leaflet के बीच स्थिति और ज़ूम सिंक करें।', + 'activeMap पॉइंटर इनपुट पाने वाला मैप याद रखता है। सिर्फ़ वही मैप moveCameraTo से बदलाव भेजता है; दूसरे मैप के इवेंट अनदेखे होते हैं।', ], }, }; diff --git a/examples/basic/src/samples/documentation/pages/circle.ts b/examples/basic/src/samples/documentation/pages/circle.ts index 25f961c..70a063a 100644 --- a/examples/basic/src/samples/documentation/pages/circle.ts +++ b/examples/basic/src/samples/documentation/pages/circle.ts @@ -1,13 +1,14 @@ import type { SamplePageDoc } from '../types'; const doc: SamplePageDoc = { + camera: { latitude: 21.382314, longitude: -157.933097, zoom: 13 }, code: ` `, - state: `const center = createGeoPoint({ latitude: 21.382314, longitude: -157.933097 }); + state: `const center = useMemo(() => createGeoPoint({ latitude: 21.382314, longitude: -157.933097 }), []); const [edge, setEdge] = useState(() => Spherical.computeOffset({ origin: center, distance: 1000, heading: 90, })); diff --git a/examples/basic/src/samples/documentation/pages/fit-bounds.ts b/examples/basic/src/samples/documentation/pages/fit-bounds.ts new file mode 100644 index 0000000..2f411f2 --- /dev/null +++ b/examples/basic/src/samples/documentation/pages/fit-bounds.ts @@ -0,0 +1,33 @@ +import type { SamplePageDoc } from '../types'; + +const doc: SamplePageDoc = { + state: `const bounds = useMemo(() => createGeoRectBounds({ + southWest: createGeoPoint({ latitude: 35.66, longitude: 139.74 }), + northEast: createGeoPoint({ latitude: 35.70, longitude: 139.80 }), +}), []); +const marker = useMemo(() => createMarkerState({ + position: createGeoPoint({ latitude: 35.68, longitude: 139.76 }), + draggable: true, + onDragStart: state => { + bounds.southWest = state.position; + bounds.northEast = state.position; + }, + onDragEnd: state => { + bounds.extend(state.position); + mapViewState.fitBounds(bounds, 40); + }, +}), [bounds, mapViewState]);`, + code: ` + + +`, + explanation: { + en: ['fitBounds adjusts the camera to a geographic rectangle with 40 pixels of padding. Drag the marker to fit the rectangle between its start and end positions.'], + ja: ['fitBounds は指定した矩形が収まるようにカメラを調整します。第2引数は余白のピクセル数です。マーカーをドラッグすると、開始位置と終了位置を含む範囲へ移動します。'], + 'es-419': ['fitBounds ajusta la cámara a un rectángulo geográfico con 40 píxeles de margen. Arrastra el marcador para ajustar el rectángulo entre el inicio y el final del movimiento.'], + de: ['fitBounds passt die Kamera mit 40 Pixeln Rand an ein geografisches Rechteck an. Ziehen Sie den Marker, um den Bereich zwischen Start und Ende einzupassen.'], + th: ['fitBounds ปรับกล้องให้ครอบคลุมสี่เหลี่ยมภูมิศาสตร์พร้อมขอบ 40 พิกเซล ลากมาร์กเกอร์เพื่อปรับให้พอดีกับพื้นที่ระหว่างจุดเริ่มต้นและจุดสิ้นสุด'], + hi: ['fitBounds कैमरे को 40 पिक्सेल के अंतर के साथ भौगोलिक आयत में फ़िट करता है। मार्कर खींचने पर आरंभ और अंत के बीच का क्षेत्र दिखता है।'], + }, +}; +export default doc; diff --git a/examples/basic/src/samples/documentation/pages/fly-to.ts b/examples/basic/src/samples/documentation/pages/fly-to.ts index 4958f65..79d275e 100644 --- a/examples/basic/src/samples/documentation/pages/fly-to.ts +++ b/examples/basic/src/samples/documentation/pages/fly-to.ts @@ -1,6 +1,7 @@ import type { SamplePageDoc } from '../types'; const doc: SamplePageDoc = { + camera: { latitude: 35.65, longitude: 139.70, zoom: 10 }, code: ` @@ -8,11 +9,11 @@ const doc: SamplePageDoc = { `, - state: `const destination = createMapCameraPosition({ + state: `const destination = useMemo(() => createMapCameraPosition({ position: createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }), zoom: 13, -}); -const destinations = [createMarkerState({ id: 'tokyo', position: destination.position })];`, +}), []); +const destinations = useMemo(() => [createMarkerState({ id: 'tokyo', position: destination.position })], [destination]);`, explanation: { en: [ 'Move the camera to a destination with a one-second animation while using the same API for every provider.', diff --git a/examples/basic/src/samples/documentation/pages/geojson-basic.ts b/examples/basic/src/samples/documentation/pages/geojson-basic.ts index 025c222..5b117b6 100644 --- a/examples/basic/src/samples/documentation/pages/geojson-basic.ts +++ b/examples/basic/src/samples/documentation/pages/geojson-basic.ts @@ -4,42 +4,46 @@ const doc: SamplePageDoc = { code: ` `, - state: `const [features, setFeatures] = useState([]); + state: `// GeoJSON coordinates use [longitude, latitude]. Rings must be closed. +const features = useMemo(() => GeoJSONParser.parseFeatures(JSON.stringify({ + type: 'FeatureCollection', + features: [{ + type: 'Feature', properties: { name: 'Area with a hole' }, + geometry: { type: 'Polygon', coordinates: [ + [[139.74, 35.70], [139.74, 35.66], [139.80, 35.66], [139.80, 35.70], [139.74, 35.70]], + [[139.76, 35.69], [139.78, 35.68], [139.76, 35.67], [139.76, 35.69]], + ] }, + }], +})), []); const layer = useMemo(() => new GeoJSONLayerState({ fillColor: colorArgb(127, 0x3b, 0xb2, 0xd0), strokeColor: colorArgb(255, 0x1d, 0x70, 0x82), strokeWidth: 2, }), []);`, explanation: { - en: [ - 'Load GeoJSON features and render them with one provider-independent layer style.', - 'The features live in React state and layer is a GeoJSONLayerState created once with useMemo.', - 'Passing both to draws every feature with a single shared style that looks the same on any provider.', + 'en': [ + 'GeoJSONParser.parseFeatures converts inline GeoJSON into layer features. Coordinates use longitude before latitude, and polygon rings must be closed.', + 'GeoJSONLayerState supplies the shared fill and stroke. GeoJSONLayer renders the polygon and its hole from the memoized features.', ], - ja: [ - 'GeoJSON の Feature を読み込み、プロバイダーに依存しない1つのレイヤースタイルで描画します。', - 'features は React の state に保持し、layer は useMemo で一度だけ生成した GeoJSONLayerState です。', - '両方を へ渡すと、すべての Feature が共有の1スタイルで描画され、どのプロバイダーでも同じ見た目になります。', + 'ja': [ + 'GeoJSONParser.parseFeatures でコード内の GeoJSON を Feature 配列に変換します。座標は経度・緯度の順で、ポリゴンの各リングは始点と終点を一致させます。', + 'GeoJSONLayerState に塗りと線を設定し、useMemo で保持した features とともに GeoJSONLayer へ渡すと、穴付きポリゴンを描画できます。', ], 'es-419': [ - 'Carga elementos GeoJSON y los dibuja con un estilo de capa independiente del proveedor.', - 'Los features viven en el estado de React y layer es un GeoJSONLayerState creado una sola vez con useMemo.', - 'Pasar ambos a dibuja cada elemento con un único estilo compartido que se ve igual en cualquier proveedor.', + 'GeoJSONParser.parseFeatures convierte el GeoJSON incluido en elementos de capa. Las coordenadas usan longitud antes de latitud y los anillos deben estar cerrados.', + 'GeoJSONLayerState define el relleno y el trazo. GeoJSONLayer dibuja el polígono con su hueco.', ], - de: [ - 'GeoJSON-Features laden und mit einem einzigen anbieterunabhängigen Ebenenstil zeichnen.', - 'Die Features liegen im React-State, und layer ist ein einmalig mit useMemo erzeugter GeoJSONLayerState.', - 'Beides an übergeben zeichnet jedes Feature mit einem gemeinsamen Stil, der bei jedem Anbieter gleich aussieht.', + 'de': [ + 'GeoJSONParser.parseFeatures wandelt eingebettetes GeoJSON in Features um. Koordinaten stehen als Länge vor Breite; Polygonringe müssen geschlossen sein.', + 'GeoJSONLayerState definiert Füllung und Kontur. GeoJSONLayer zeichnet das Polygon mit seinem Loch.', ], - th: [ - 'โหลดฟีเจอร์ GeoJSON แล้ววาดด้วยสไตล์เลเยอร์ชุดเดียวที่ไม่ผูกกับผู้ให้บริการ', - 'ฟีเจอร์เก็บอยู่ในสถานะของ React ส่วน layer คือ GeoJSONLayerState ที่สร้างครั้งเดียวด้วย useMemo', - 'การส่งทั้งสองเข้า จะวาดทุกฟีเจอร์ด้วยสไตล์ร่วมชุดเดียว ซึ่งหน้าตาเหมือนกันบนผู้ให้บริการทุกเจ้า', + 'th': [ + 'GeoJSONParser.parseFeatures แปลง GeoJSON ในโค้ดเป็นฟีเจอร์ พิกัดเรียงลองจิจูดก่อนละติจูด และวงแหวนของโพลีกอนต้องปิด', + 'GeoJSONLayerState กำหนดสีเติมและเส้นขอบ ส่วน GeoJSONLayer วาดโพลีกอนพร้อมรูจากฟีเจอร์ที่เก็บด้วย useMemo', ], - hi: [ - 'GeoJSON फ़ीचर लोड करें और उन्हें एक ही प्रोवाइडर-निरपेक्ष लेयर स्टाइल से रेंडर करें।', - 'फ़ीचर React स्टेट में रहते हैं, और layer एक GeoJSONLayerState है जो useMemo से एक बार बनता है।', - 'दोनों को को देने पर हर फ़ीचर एक ही साझा स्टाइल से खिंचता है, जो किसी भी प्रोवाइडर पर एक जैसा दिखता है।', + 'hi': [ + 'GeoJSONParser.parseFeatures कोड के GeoJSON को फ़ीचर में बदलता है। निर्देशांक में देशांतर पहले आता है और पॉलीगॉन के रिंग बंद होने चाहिए।', + 'GeoJSONLayerState भराव और रेखा तय करता है। GeoJSONLayer छेद वाला पॉलीगॉन बनाता है।', ], }, }; diff --git a/examples/basic/src/samples/documentation/pages/geojson-layer.ts b/examples/basic/src/samples/documentation/pages/geojson-layer.ts index 750bb2c..a0f6cea 100644 --- a/examples/basic/src/samples/documentation/pages/geojson-layer.ts +++ b/examples/basic/src/samples/documentation/pages/geojson-layer.ts @@ -5,46 +5,51 @@ const doc: SamplePageDoc = { {selected && ( - +
{JSON.stringify(selected.properties, null, 2)}
)} `, - state: `const [features, setFeatures] = useState([]); -const [selected, setSelected] = useState(null); + state: `const features = useMemo(() => GeoJSONParser.parseFeatures(JSON.stringify({ + type: 'FeatureCollection', + features: [{ type: 'Feature', properties: { name: 'Sample railway' }, + geometry: { type: 'LineString', coordinates: [[139.75, 35.68], [139.77, 35.69], [139.79, 35.68]] }, + }], +})), []); +const [selected, setSelected] = useState<{ + position: GeoPoint; properties: Record; +} | null>(null); const layerState = useMemo(() => new GeoJSONLayerState({ strokeColor: colorArgb(200, 250, 36, 29), strokeWidth: 6, -}), []);`, + onClick: (feature, position) => setSelected({ position: createGeoPoint(position), properties: feature.properties ?? {} }), +}), []); +const handleMapClick = (point: GeoPoint) => { + if (!layerState.processClick(point, 10, mapViewState.cameraPosition.zoom)) setSelected(null); +};`, explanation: { - en: [ - "Process clicks against GeoJSON features and show the selected feature's properties at the geographic click position.", - 'Both the features and the selected feature live in React state, and layerState is a GeoJSONLayerState holding the railway data.', - 'handleMapClick resolves which feature was hit and stores it, then InfoBubble anchors a PropertyTable of its properties at the clicked coordinate.', + 'en': [ + 'The inline GeoJSON contains a sample railway line, so the snippet needs no data server.', + 'handleMapClick calls processClick with the current zoom. A hit invokes layerState.onClick, which stores the feature properties and click position for the InfoBubble; a miss clears the selection.', ], - ja: [ - 'GeoJSON Feature へのクリックを判定し、選択した Feature の属性をクリック地点に表示します。', - 'features と選択中の Feature はどちらも React の state に保持し、layerState は鉄道データ用の GeoJSONLayerState です。', - 'handleMapClick がどの Feature に当たったかを判定して保存し、InfoBubble がその属性の PropertyTable をクリック座標に固定します。', + 'ja': [ + '外部データサーバーなしで試せるよう、説明用の鉄道路線を GeoJSON としてコード内に用意しています。', + 'handleMapClick は現在のズームを渡して processClick を呼びます。ヒット時に layerState.onClick が属性とクリック地点を保存して InfoBubble へ表示し、何もない場所をクリックすると選択を解除します。', ], 'es-419': [ - 'Procesa clics sobre elementos GeoJSON y muestra las propiedades del elemento seleccionado en la posición geográfica del clic.', - 'Tanto los features como el elemento seleccionado viven en el estado de React, y layerState es un GeoJSONLayerState con los datos ferroviarios.', - 'handleMapClick determina qué elemento se tocó y lo almacena, luego InfoBubble ancla un PropertyTable de sus propiedades en la coordenada tocada.', + 'El GeoJSON incluido contiene una línea de ferrocarril de ejemplo y no necesita servidor de datos.', + 'handleMapClick llama a processClick con el zoom actual. onClick guarda las propiedades para el InfoBubble cuando hay un acierto; de lo contrario borra la selección.', ], - de: [ - 'Klicks gegen GeoJSON-Features auswerten und die Eigenschaften des getroffenen Features an der geografischen Klickposition zeigen.', - 'Sowohl die Features als auch das ausgewählte Feature liegen im React-State, und layerState ist ein GeoJSONLayerState mit den Bahndaten.', - 'handleMapClick ermittelt das getroffene Feature und merkt es sich, dann verankert InfoBubble eine PropertyTable seiner Eigenschaften an der angeklickten Koordinate.', + 'de': [ + 'Das eingebettete GeoJSON enthält eine Beispielbahnlinie und benötigt keinen Datenserver.', + 'handleMapClick ruft processClick mit dem aktuellen Zoom auf. Bei einem Treffer speichert onClick die Attribute für die InfoBubble; andernfalls wird die Auswahl aufgehoben.', ], - th: [ - 'ประมวลผลการคลิกกับฟีเจอร์ GeoJSON แล้วแสดงคุณสมบัติของฟีเจอร์ที่เลือกไว้ ณ ตำแหน่งภูมิศาสตร์ที่คลิก', - 'ทั้งฟีเจอร์และฟีเจอร์ที่เลือกอยู่ในสถานะของ React ส่วน layerState คือ GeoJSONLayerState ที่ถือข้อมูลเส้นทางรถไฟ', - 'handleMapClick หาว่าโดนฟีเจอร์ใดแล้วเก็บไว้ จากนั้น InfoBubble จะตรึง PropertyTable ของคุณสมบัตินั้นไว้ที่พิกัดที่คลิก', + 'th': [ + 'GeoJSON ในโค้ดมีเส้นทางรถไฟตัวอย่าง จึงไม่ต้องใช้เซิร์ฟเวอร์ข้อมูล', + 'handleMapClick เรียก processClick ด้วยระดับซูมปัจจุบัน เมื่อพบฟีเจอร์ onClick จะเก็บคุณสมบัติให้ InfoBubble หากไม่พบจะล้างการเลือก', ], - hi: [ - 'क्लिक को GeoJSON फ़ीचर के विरुद्ध जाँचें और चुने गए फ़ीचर की प्रॉपर्टी उसी भौगोलिक जगह पर दिखाएँ।', - 'फ़ीचर और चुना गया फ़ीचर दोनों React स्टेट में रहते हैं, और layerState एक GeoJSONLayerState है जिसमें रेलवे का डेटा है।', - 'handleMapClick तय करता है कि कौन-सा फ़ीचर लगा और उसे रख लेता है; फिर InfoBubble उसकी प्रॉपर्टी की PropertyTable क्लिक किए गए निर्देशांक पर टिका देता है।', + 'hi': [ + 'कोड के GeoJSON में उदाहरण रेल लाइन है, इसलिए डेटा सर्वर की ज़रूरत नहीं।', + 'handleMapClick वर्तमान ज़ूम से processClick बुलाता है। फ़ीचर मिलने पर onClick गुणों को InfoBubble के लिए रखता है; न मिलने पर चयन हटता है।', ], }, }; diff --git a/examples/basic/src/samples/documentation/pages/ground-image.ts b/examples/basic/src/samples/documentation/pages/ground-image.ts index 953b096..914beeb 100644 --- a/examples/basic/src/samples/documentation/pages/ground-image.ts +++ b/examples/basic/src/samples/documentation/pages/ground-image.ts @@ -1,11 +1,32 @@ import type { SamplePageDoc } from '../types'; const doc: SamplePageDoc = { + camera: { latitude: -26.479235, longitude: 31.306239, zoom: 15 }, code: ` `, - state: `const [groundImageState] = useState(() => createGroundImageState({ + state: `// Generate a PNG: MapLibre's image decoder cannot read SVG sources. +// In your app this can instead be a URL to a PNG or JPEG image. +const imageUrl = useMemo(() => { + const canvas = document.createElement('canvas'); + canvas.width = 400; + canvas.height = 300; + const context = canvas.getContext('2d')!; + context.fillStyle = '#bfdbfe'; + context.fillRect(0, 0, 400, 300); + context.fillStyle = '#2563eb'; + context.fillRect(196, 0, 8, 300); + context.fillRect(0, 146, 400, 8); + context.font = '24px sans-serif'; + context.fillText('Ground image', 20, 40); + return canvas.toDataURL('image/png'); +}, []); +const initialBounds = createGeoRectBounds({ + southWest: createGeoPoint({ latitude: -26.4849, longitude: 31.2996 }), + northEast: createGeoPoint({ latitude: -26.4736, longitude: 31.3129 }), +}); +const [groundImageState] = useState(() => createGroundImageState({ id: 'historic-map', imageUrl, bounds: initialBounds, opacity: 0.7, })); @@ -16,11 +37,19 @@ const moveSouthWest = (markerState: MarkerState) => { }); }; -const southWestMarker = createMarkerState({ +const moveNorthEast = (markerState: MarkerState) => { + groundImageState.bounds = createGeoRectBounds({ + southWest: groundImageState.bounds.southWest, + northEast: markerState.position, + }); +}; +const cornerMarkers = useMemo(() => [createMarkerState({ id: 'south-west', position: groundImageState.bounds.southWest!, draggable: true, onDrag: moveSouthWest, onDragEnd: moveSouthWest, -}); -const cornerMarkers = [southWestMarker, northEastMarker];`, +}), createMarkerState({ + id: 'north-east', position: groundImageState.bounds.northEast!, + draggable: true, onDrag: moveNorthEast, onDragEnd: moveNorthEast, +})], [groundImageState]);`, explanation: { en: [ 'Keep one GroundImageState instance and update its bounds from the draggable corner markers.', diff --git a/examples/basic/src/samples/documentation/pages/heatmap-layer.ts b/examples/basic/src/samples/documentation/pages/heatmap-layer.ts index 31533c2..21e9ec3 100644 --- a/examples/basic/src/samples/documentation/pages/heatmap-layer.ts +++ b/examples/basic/src/samples/documentation/pages/heatmap-layer.ts @@ -6,47 +6,40 @@ const doc: SamplePageDoc = { `, - state: `const [heatmapPoints, setHeatmapPoints] = useState([]); -useEffect(() => { - fetch('/postoffice/postoffices.json') - .then(response => response.json() as Promise<[number, number][]>) - .then(data => setHeatmapPoints(data.map(([latitude, longitude], index) => - new HeatmapPointState({ - id: \`post-office-\${index}\`, - position: createGeoPoint({ latitude, longitude }), - }), - ))); -}, []);`, + state: `// Inline points work without the example app's public data files. +const heatmapPoints = useMemo(() => Array.from({ length: 100 }, (_, index) => + new HeatmapPointState({ + id: \`point-\${index}\`, + position: createGeoPoint({ + latitude: 35.68 + Math.sin(index * 2.4) * (index % 10) * 0.001, + longitude: 139.77 + Math.cos(index * 2.4) * (index % 10) * 0.001, + }), + }), +), []);`, explanation: { - en: [ - 'Compose weighted geographic points inside the heatmap extension overlay.', - 'A useEffect fetches postoffices.json and maps each coordinate into a HeatmapPointState kept in React state.', - 'The inside composes the whole set at once, and the extension renders the density map on any provider.', + 'en': [ + 'HeatmapOverlay renders the density of geographic points.', + 'useMemo creates 100 sample HeatmapPointState objects without an external file. HeatmapPoints submits them together to the overlay.', ], - ja: [ - '重みを持つ地理座標の点群を、ヒートマップ拡張オーバーレイ内で一括構成します。', - 'useEffect が postoffices.json を取得し、各座標を HeatmapPointState へ変換して React の state に保持します。', - ' 内の が点群をまとめて構成し、拡張がどのプロバイダーでも密度マップを描画します。', + 'ja': [ + 'HeatmapOverlay は地理座標の点群を密度マップとして描画します。', + 'この短い例は外部ファイルを使わず、useMemo で説明用の HeatmapPointState を100件生成します。HeatmapPoints が点群をまとめてオーバーレイへ渡します。', ], 'es-419': [ - 'Compone puntos geográficos ponderados dentro de la superposición de la extensión de mapa de calor.', - 'Un useEffect obtiene postoffices.json y convierte cada coordenada en un HeatmapPointState guardado en el estado de React.', - 'El dentro de compone todo el conjunto de una vez, y la extensión dibuja el mapa de densidad en cualquier proveedor.', + 'HeatmapOverlay dibuja la densidad de puntos geográficos.', + 'useMemo crea 100 objetos HeatmapPointState de ejemplo sin archivos externos. HeatmapPoints los envía juntos a la capa.', ], - de: [ - 'Gewichtete geografische Punkte im Heatmap-Erweiterungs-Overlay zusammensetzen.', - 'Ein useEffect holt postoffices.json und bildet jede Koordinate auf einen HeatmapPointState im React-State ab.', - 'Das innerhalb von setzt den ganzen Satz auf einmal zusammen, und die Erweiterung zeichnet die Dichtekarte bei jedem Anbieter.', + 'de': [ + 'HeatmapOverlay zeichnet die Dichte geografischer Punkte.', + 'useMemo erzeugt 100 HeatmapPointState-Beispielpunkte ohne externe Datei. HeatmapPoints übergibt sie gemeinsam an das Overlay.', ], - th: [ - 'ประกอบจุดภูมิศาสตร์แบบถ่วงน้ำหนักไว้ในโอเวอร์เลย์ส่วนขยายฮีตแมป', - 'useEffect ดึง postoffices.json แล้วแปลงแต่ละพิกัดเป็น HeatmapPointState ที่เก็บไว้ในสถานะของ React', - ' ภายใน ประกอบชุดข้อมูลทั้งหมดในคราวเดียว และส่วนขยายจะเรนเดอร์แผนที่ความหนาแน่นได้บนผู้ให้บริการทุกเจ้า', + 'th': [ + 'HeatmapOverlay แสดงความหนาแน่นของจุดภูมิศาสตร์', + 'useMemo สร้าง HeatmapPointState ตัวอย่าง 100 จุดโดยไม่ใช้ไฟล์ภายนอก และ HeatmapPoints ส่งจุดทั้งหมดให้โอเวอร์เลย์พร้อมกัน', ], - hi: [ - 'भारित भौगोलिक बिंदुओं को हीटमैप एक्सटेंशन के ओवरले के भीतर जोड़ें।', - 'एक useEffect postoffices.json लाता है और हर निर्देशांक को React स्टेट में रखे HeatmapPointState में बदल देता है।', - ' के भीतर का पूरा सेट एक साथ जोड़ता है, और एक्सटेंशन घनत्व का मैप किसी भी प्रोवाइडर पर रेंडर कर देता है।', + 'hi': [ + 'HeatmapOverlay भौगोलिक बिंदुओं का घनत्व दिखाता है।', + 'useMemo बाहरी फ़ाइल के बिना 100 उदाहरण HeatmapPointState बनाता है। HeatmapPoints उन्हें एक साथ ओवरले को देता है।', ], }, }; diff --git a/examples/basic/src/samples/documentation/pages/info-bubble-multiple.ts b/examples/basic/src/samples/documentation/pages/info-bubble-multiple.ts index 92716ac..3cfabef 100644 --- a/examples/basic/src/samples/documentation/pages/info-bubble-multiple.ts +++ b/examples/basic/src/samples/documentation/pages/info-bubble-multiple.ts @@ -9,12 +9,18 @@ const doc: SamplePageDoc = { ))} `, - state: `const [selectedMarkers, setSelectedMarkers] = useState([]); + state: `const positions = useMemo(() => [ + createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }), + createGeoPoint({ latitude: 35.6862, longitude: 139.7771 }), +], []); +const [selectedMarkers, setSelectedMarkers] = useState([]); const markers = useMemo(() => positions.map((position, index) => createMarkerState({ id: \`marker-\${index}\`, position, - onClick: markerState => setSelectedMarkers(current => [...current, markerState]), + extra: \`Place \${index + 1}\`, + onClick: markerState => setSelectedMarkers(current => + current.some(item => item.id === markerState.id) ? current : [...current, markerState]), })), [positions]); -const activeMarker = selectedMarkers.at(-1) ?? null;`, +`, explanation: { en: [ 'Keep multiple markers selected and render one independently positioned bubble for each.', diff --git a/examples/basic/src/samples/documentation/pages/info-bubble-rich.ts b/examples/basic/src/samples/documentation/pages/info-bubble-rich.ts index f976481..fa92a53 100644 --- a/examples/basic/src/samples/documentation/pages/info-bubble-rich.ts +++ b/examples/basic/src/samples/documentation/pages/info-bubble-rich.ts @@ -3,18 +3,19 @@ import type { SamplePageDoc } from '../types'; const doc: SamplePageDoc = { code: ` - + {selected &&

Place details

-
+
}
`, - state: `const position = createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }); + state: `const position = useMemo(() => createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }), []); const [selected, setSelected] = useState(false); const marker = useMemo(() => createMarkerState({ id: 'place', position, onClick: () => setSelected(true), -}), [position]);`, +}), [position]); +const openDetails = () => window.alert('Tokyo Station, Tokyo, Japan');`, explanation: { en: [ 'Render interactive React elements inside a marker-anchored bubble, including headings and buttons.', diff --git a/examples/basic/src/samples/documentation/pages/info-bubble-simple.ts b/examples/basic/src/samples/documentation/pages/info-bubble-simple.ts index e595768..0112096 100644 --- a/examples/basic/src/samples/documentation/pages/info-bubble-simple.ts +++ b/examples/basic/src/samples/documentation/pages/info-bubble-simple.ts @@ -7,7 +7,7 @@ const doc: SamplePageDoc = { Simple text content )} `, - state: `const position = createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }); + state: `const position = useMemo(() => createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }), []); const [selected, setSelected] = useState(false); const marker = useMemo(() => createMarkerState({ id: 'place', position, onClick: () => setSelected(true), diff --git a/examples/basic/src/samples/documentation/pages/info-bubble-styled.ts b/examples/basic/src/samples/documentation/pages/info-bubble-styled.ts index 5b555fc..22b43fa 100644 --- a/examples/basic/src/samples/documentation/pages/info-bubble-styled.ts +++ b/examples/basic/src/samples/documentation/pages/info-bubble-styled.ts @@ -1,7 +1,13 @@ import type { SamplePageDoc } from '../types'; const doc: SamplePageDoc = { - code: ` + code: ` + + + + setStrokeWidth(Number(e.target.value))} /> + setMarkerScale(Number(e.target.value))} /> + {selected && ( - +
{JSON.stringify(selected.properties, null, 2)}
)}
`, - state: `const [features, setFeatures] = useState([]); -const [selected, setSelected] = useState(null); -const layerState = useMemo(() => new KMLLayerState({ /* fallback style */ }), []); - -// Fetch the document (here: public/sample.kml) and parse it into features. -useEffect(() => { - fetch('/sample.kml') - .then(response => response.text()) - .then(text => setFeatures(KMLParser.parse(text))); -}, []);`, + state: `const features = useMemo(() => KMLParser.parse( + '' + + 'Sample route' + + '139.75,35.68 139.77,35.69 139.79,35.68' + + '', +), []); +const [selected, setSelected] = useState<{ + position: GeoPoint; properties: Record; +} | null>(null); +const layerState = useMemo(() => new KMLLayerState({ + onClick: (feature, position) => setSelected({ position: createGeoPoint(position), properties: feature.properties ?? {} }), +}), []); +const handleMapClick = (point: GeoPoint) => { + if (!layerState.processClick(point, 10, mapViewState.cameraPosition.zoom)) setSelected(null); +};`, explanation: { - en: [ - 'Parse a KML document with KMLParser and render its placemarks — styled polygons, lines, and points — as a tiled overlay.', - 'KMLParser.parse takes the KML text, so fetch the document yourself first; KMLLoader.load takes a URL instead (anything fetch accepts — a same-origin path such as /sample.kml or an absolute https URL), follows references and unpacks KMZ archives. On the web that fetch is subject to CORS, so a cross-origin document loads only when its server sends Access-Control-Allow-Origin — otherwise serve it from your own origin or inject a proxying fetch through the KMLLoader constructor.', - 'Both the features and the selected feature live in React state, and layerState is a KMLLayerState whose style is the fallback used when a placemark carries no KML