Key changes:

- Add MapLibre GL JS viewer with light/dark themes, terrain layer,
  and embedded static map page for coordinate sharing
- Add map pin support with persistent map_pins.yaml config
- Add map region subscriptions and downloader with progress tracking,
  sourcing pre-extracted PMTiles from a cold CDN
- Add map export to PNG and GPS coordinate copy via context menu
- Add MapViewer React component alongside reworked Map page
- Add map catalog and region-building script (build_map_regions.py)
- Remove OSM import/render scripts, leaflet files, Apache configs,
  renderd service, and osm-map-dumper Docker container
- Update Caddyfile to serve PMTiles and map static assets
- Update build/install/repair scripts for Protomaps dependencies
- Drop map_file table, add/drop map_subscription table (alembic)
- Adding button to skip primary drive mounting during onboarding.
This commit is contained in:
Roland 2026-03-29 18:58:31 -06:00
parent 0a5fe7eebe
commit b8a532c8d9
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
102 changed files with 5033 additions and 2712 deletions

View file

@ -2054,10 +2054,10 @@ export function IframeViewer({title, src, fallback, style, timeout = 5000}) {
const iframeMedia = <>
<Media at='mobile'>
<iframe title={title} src={src} style={mobileStyle}/>
<iframe title={title} src={src} style={mobileStyle} allow="geolocation"/>
</Media>
<Media greaterThan='mobile'>
<iframe title={title} src={src} style={tabletStyle}/>
<iframe title={title} src={src} style={tabletStyle} allow="geolocation"/>
</Media>
</>;

View file

@ -1,302 +1,610 @@
import React, {useContext} from "react";
import React, {useEffect, useState} from "react";
import {
APIButton,
ErrorMessage,
HandPointMessage,
humanFileSize,
IframeViewer,
InfoMessage,
InfoPopup,
PageContainer,
TabLinks,
useTitle,
WROLModeMessage
} from "./Common";
import {Route, Routes} from "react-router";
import {getMapImportStatus, importMapFiles} from "../api";
import {Route, Routes, useNavigate} from "react-router";
import {
Checkbox,
deleteMapFile, deleteMapPin, fetchMapSubscriptions, getMapFiles, getMapPins,
mapSubscribe, mapUnsubscribe, updateMapPin
} from "../api";
import {
Button,
Divider,
Icon as SIcon,
Loader as SLoader,
Input,
TableCell,
TableFooter,
TableHeaderCell,
TableRow
} from "semantic-ui-react";
import {SortableTable} from "./SortableTable";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {Header, Loader, Segment} from "./Theme";
import {StatusContext} from "../contexts/contexts";
import _ from "lodash";
import {Header} from "./Theme";
import {Media} from "../contexts/contexts";
import {MAP_VIEWER_URI} from "./Vars";
import {Modal} from "./Theme";
import MapViewer from "./MapViewer";
import maplibregl from "maplibre-gl";
import {Protocol} from "pmtiles";
import layers from "protomaps-themes-base";
function DockerMapImportWarning() {
const {status} = useContext(StatusContext);
if (status['dockerized']) {
return <ErrorMessage storageName='hint_map_docker_warning'>
<Message.Header>
Maps are not fully supported in a Docker container!
</Message.Header>
// Ensure PMTiles protocol is registered (may already be registered by MapViewer).
try { maplibregl.addProtocol("pmtiles", new Protocol().tile); } catch (e) { /* already registered */ }
<p><b>Only one PBF can be imported and displayed in the docker container.</b></p>
const MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles";
<p>To import a map file, run the following docker-compose commands:</p>
<pre> docker-compose stop map</pre>
<pre> docker-compose rm map</pre>
<pre> docker-compose run --rm -v /absolute/path/to/map.osm.pbf:/data.osm.pbf
-v openstreetmap-data:/var/lib/postgresql/12/main map import
</pre>
<p>Be sure to change <b>/absolute/path/to/map.osm.pbf</b>!</p>
<p>After you have imported a new PBF file, you need to clear the rendered tile cache:</p>
<pre> docker volume rm openstreetmap-rendered-tiles</pre>
<pre> docker volume create openstreetmap-rendered-tiles</pre>
<p>Start your map container:</p>
<pre> docker-compose up -d map</pre>
<Divider/>
<p>You can merge multiple PBF files using osmium (the merged file can then be imported):</p>
<pre> osmium merge file1.osm.pbf file2.osm.pbf -o merged.osm.pbf</pre>
</ErrorMessage>;
}
return <></>;
// Detect full planet files: "planet-20260329.pmtiles" or bare date like "20260329.pmtiles".
function isPlanetFile(name) {
if (name.startsWith("planet-")) return true;
return /^\d{8}\.pmtiles$/.test(name);
}
function DownloadMessage() {
return <InfoMessage storageName='hint_map_download'>
<Message.Header>Where do I get map files?</Message.Header>
<p>You can download map files from&nbsp;
<a href='https://download.geofabrik.de/' rel='noopener noreferrer' target='_blank'>https://download.geofabrik.de/</a>
</p>
<p><b>Download only the areas you need</b>. Large regions like all of Asia, or the entire
planet are most likely <b>too large</b> and won't render quickly. It is recommend to only
import files less than 1GB on a Raspberry Pi.</p>
<p>Only <b>*.osm.pbf</b> files are supported!</p>
<p>Place downloaded map files into <b>map/pbf</b> so they can be imported here.</p>
</InfoMessage>
}
const ViewerMessage = () => {
return <HandPointMessage>
<p>You can view the Map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
</HandPointMessage>
}
function SlowImportMessage() {
const {status} = useContext(StatusContext);
if (status && status['cpu_stats'] && status['cpu_stats']['temperature'] >= 80) {
return <Message warning icon>
<SIcon name='exclamation'/>
<Message.Content>
<Message.Header>
CPU temperature is too high
</Message.Header>
<p>Any import may take much more time because the CPU is throttled.</p>
<small>If your import takes more time than estimated, you will need an aftermarket cooler.</small>
</Message.Content>
</Message>
}
return <></>
}
class ManageMap extends React.Component {
constructor(props) {
super(props);
this.state = {
files: null,
pending: null,
import_running: false,
selectedPaths: [],
dockerized: null,
// Resolve the best available base map source for preview maps.
// Checks for a user's planet file first, falls back to the overview blob.
async function getPreviewMapSource() {
try {
const data = await getMapFiles();
if (data?.files) {
for (const f of data.files) {
if (isPlanetFile(f.name)) {
return {type: 'vector', url: `pmtiles:///media/map/${f.name}`};
}
}
}
}
} catch (e) { /* ignore */ }
return {type: 'vector', url: `pmtiles://${MAP_OVERVIEW_URL}`};
}
async componentDidMount() {
await this.fetchImportStatus();
this.intervalId = setInterval(this.fetchImportStatus, 1000 * 30);
}
function RegionPreviewModal({bbox, name, open, onClose}) {
const mapContainer = React.useRef(null);
componentWillUnmount() {
clearInterval(this.intervalId);
}
React.useEffect(() => {
if (!open || !mapContainer.current || !bbox) return;
fetchImportStatus = async () => {
try {
const importStatus = await getMapImportStatus();
this.setState({
files: importStatus['files'],
pending: importStatus['pending'],
import_running: importStatus['import_running'],
dockerized: importStatus['dockerized'],
const [minLon, minLat, maxLon, maxLat] = bbox.split(',').map(Number);
const centerLon = (minLon + maxLon) / 2;
const centerLat = (minLat + maxLat) / 2;
let map;
getPreviewMapSource().then(source => {
if (!mapContainer.current) return;
map = new maplibregl.Map({
container: mapContainer.current,
style: {
version: 8,
sources: {'basemap': source},
layers: layers('basemap', 'light'),
glyphs: '/map-assets/fonts/{fontstack}/{range}.pbf',
sprite: `${window.location.origin}/map-assets/sprites/light`,
},
center: [centerLon, centerLat],
zoom: 1,
attributionControl: false,
});
map.on('load', () => {
map.addSource('bbox', {
type: 'geojson',
data: {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[
[minLon, minLat],
[maxLon, minLat],
[maxLon, maxLat],
[minLon, maxLat],
[minLon, minLat],
]],
},
},
});
map.addLayer({
id: 'bbox-fill',
type: 'fill',
source: 'bbox',
paint: {'fill-color': '#6435c9', 'fill-opacity': 0.2},
});
map.addLayer({
id: 'bbox-outline',
type: 'line',
source: 'bbox',
paint: {'line-color': '#6435c9', 'line-width': 2},
});
map.fitBounds([[minLon, minLat], [maxLon, maxLat]], {padding: 40});
});
});
return () => { if (map) map.remove(); };
}, [open, bbox]);
return <Modal open={open} onClose={onClose} size='large' closeIcon>
<Modal.Header>{name}</Modal.Header>
<Modal.Content>
<div ref={mapContainer} style={{width: '100%', height: '50vh'}}/>
</Modal.Content>
</Modal>;
}
// Random-ish distinct colors for region boxes.
const REGION_COLORS = [
'#6435c9', '#e03997', '#00b5ad', '#2185d0', '#f2711c', '#b5cc18',
'#a333c8', '#21ba45', '#db2828', '#fbbd08', '#a5673f', '#767676',
];
function AllRegionsPreviewModal({catalog, open, onClose}) {
const mapContainer = React.useRef(null);
React.useEffect(() => {
if (!open || !mapContainer.current) return;
let map;
getPreviewMapSource().then(source => {
if (!mapContainer.current) return;
map = new maplibregl.Map({
container: mapContainer.current,
style: {
version: 8,
sources: {'basemap': source},
layers: layers('basemap', 'light'),
glyphs: '/map-assets/fonts/{fontstack}/{range}.pbf',
sprite: `${window.location.origin}/map-assets/sprites/light`,
},
center: [0, 20],
zoom: 1,
attributionControl: false,
});
map.on('load', () => {
const regions = catalog.filter(r => r.bbox);
regions.forEach((region, i) => {
const [minLon, minLat, maxLon, maxLat] = region.bbox.split(',').map(Number);
const color = REGION_COLORS[i % REGION_COLORS.length];
const id = `region-${i}`;
map.addSource(id, {
type: 'geojson',
data: {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[
[minLon, minLat], [maxLon, minLat],
[maxLon, maxLat], [minLon, maxLat],
[minLon, minLat],
]],
},
properties: {name: region.name},
},
});
map.addLayer({
id: `${id}-fill`, type: 'fill', source: id,
paint: {'fill-color': color, 'fill-opacity': 0.15},
});
map.addLayer({
id: `${id}-outline`, type: 'line', source: id,
paint: {'line-color': color, 'line-width': 1.5},
});
map.addLayer({
id: `${id}-label`, type: 'symbol', source: id,
layout: {
'text-field': ['get', 'name'],
'text-size': 11,
'text-allow-overlap': true,
},
paint: {
'text-color': color,
'text-halo-color': 'white',
'text-halo-width': 1,
},
});
});
});
});
return () => { if (map) map.remove(); };
}, [open, catalog]);
return <Modal open={open} onClose={onClose} size='fullscreen' closeIcon>
<Modal.Header>All Map Regions</Modal.Header>
<Modal.Content>
<div ref={mapContainer} style={{width: '100%', height: '75vh'}}/>
</Modal.Content>
</Modal>;
}
function MapCatalogRow({item, subscribedRegions, fetchData}) {
const {name, region, size_estimate, bbox} = item;
const isSubscribed = subscribedRegions.has(region);
const [previewOpen, setPreviewOpen] = useState(false);
const handleButton = async () => {
if (isSubscribed) {
await mapUnsubscribe(region);
} else {
await mapSubscribe(name, region);
}
if (fetchData) {
await fetchData();
}
};
return <TableRow>
<TableCell>{name}</TableCell>
<TableCell>{humanFileSize(size_estimate)}</TableCell>
<TableCell collapsing>
{bbox && <Button
size='tiny'
icon='eye'
onClick={() => setPreviewOpen(true)}
/>}
<Button
color={isSubscribed ? 'red' : 'violet'}
size='tiny'
onClick={handleButton}
>
{isSubscribed ? 'Unsubscribe' : 'Subscribe'}
</Button>
</TableCell>
{previewOpen && <RegionPreviewModal
bbox={bbox}
name={name}
open={previewOpen}
onClose={() => setPreviewOpen(false)}
/>}
</TableRow>;
}
function ManageMap() {
const [files, setFiles] = useState(null);
const [catalog, setCatalog] = useState([]);
const [subscriptions, setSubscriptions] = useState([]);
const [allRegionsOpen, setAllRegionsOpen] = useState(false);
const fetchFiles = async () => {
try {
const data = await getMapFiles();
if (data) {
setFiles(data.files || []);
}
} catch (e) {
console.error(e);
this.setState({files: undefined});
setFiles(undefined);
}
}
};
import = async (e) => {
if (e) {
e.preventDefault();
}
this.setState({'ready': false});
const {files, selectedPaths} = this.state;
if (_.isEmpty(selectedPaths)) {
// No files are selected, import all.
let paths = [];
for (let i = 0; i < files.length; i++) {
paths = paths.concat([files[i].path]);
const fetchSubscriptionData = async () => {
try {
const data = await fetchMapSubscriptions();
if (data) {
setCatalog(data.catalog || []);
setSubscriptions(data.subscriptions || []);
}
await importMapFiles(paths);
} else {
await importMapFiles(selectedPaths);
} catch (e) {
console.error(e);
}
await this.fetchImportStatus();
}
};
handleCheckbox = (checked, pbf) => {
let {selectedPaths} = this.state;
if (checked === true) {
selectedPaths = selectedPaths.concat([pbf.path]);
} else {
const index = selectedPaths.indexOf(pbf.path);
if (index > -1) {
selectedPaths.splice(index, 1);
}
}
this.setState({selectedPaths});
}
useEffect(() => {
fetchFiles();
fetchSubscriptionData();
const interval = setInterval(fetchFiles, 30000);
return () => clearInterval(interval);
}, []);
render() {
const {files, selectedPaths, import_running, pending, dockerized} = this.state;
const handleDelete = async (filename) => {
await deleteMapFile(filename);
await fetchFiles();
};
const importingMessage = pending ?
pending.length > 1 ? 'Importing...' : `Importing ${pending[0]}`
: null;
// --- Files table ---
const fileHeaders = [
{key: 'name', text: 'File', sortBy: i => i.name.toLowerCase()},
{key: 'size', text: 'Size', sortBy: i => i.size || 0},
{key: 'actions', text: '', sortBy: null},
];
let disabled = dockerized || _.isEmpty(files) || import_running;
let importButton = <APIButton
color='violet'
disabled={disabled}
onClick={this.import}
>
{!_.isEmpty(selectedPaths) ? 'Import Selected' : 'Import All'}
</APIButton>;
let spaceInfoPopup = <InfoPopup
content='Upon importing, a PBF file will consume more disk space than the original file.'/>;
let timeInfoPopup = <InfoPopup content='Estimated for a Raspberry Pi 4'/>;
const tableHeaders = [
{key: 'select', text: '', sortBy: null},
{key: 'path', text: 'PBF File', sortBy: i => i.path.toLowerCase()},
{key: 'imported', text: 'Imported', sortBy: i => i.imported ? 1 : 0},
{key: 'size', text: 'Size', sortBy: i => i.size || 0},
{key: 'space', text: <>Space Required {spaceInfoPopup}</>, sortBy: i => i.size || 0},
{key: 'time', text: <>Time to Import {timeInfoPopup}</>, sortBy: i => i.seconds_to_import || 0},
];
const rowFunc = (pbf) => {
let ref = React.createRef();
const {size, path, imported, time_to_import} = pbf;
let sizeCells = (<>
<TableCell>{humanFileSize(size)}</TableCell>
<TableCell>{humanFileSize(size * 25)}</TableCell>
<TableCell>{time_to_import}</TableCell>
</>);
return <TableRow>
<TableCell collapsing>
<Checkbox
disabled={disabled}
ref={ref}
onChange={(e, data) => this.handleCheckbox(data.checked, pbf)}
/>
</TableCell>
<TableCell>
<a href={`/media/${path}`}>{path}</a>
</TableCell>
<TableCell>
{pending && pending.indexOf(path) >= 0 ?
<SLoader active inline size='mini'/> :
imported ? 'yes' : 'no'}
</TableCell>
{size !== null ? sizeCells : <TableCell colSpan={3}/>}
</TableRow>;
};
const emptyRow = <TableRow>
<TableCell/><TableCell colSpan={5}>No PBF map files were found in <b>map/pbf</b></TableCell>
const fileRowFunc = (file) => {
return <TableRow key={file.name}>
<TableCell>{file.name}</TableCell>
<TableCell>{humanFileSize(file.size)}</TableCell>
<TableCell collapsing>
<APIButton
color='red'
size='tiny'
confirmContent='Delete this map file?'
confirmButton='Delete'
onClick={() => handleDelete(file.name)}
>
Delete
</APIButton>
</TableCell>
</TableRow>;
};
const footer = <TableFooter>
<TableRow>
<TableHeaderCell/>
<TableHeaderCell colSpan={5}>
{importButton}
</TableHeaderCell>
</TableRow>
</TableFooter>;
const emptyRow = <TableRow>
<TableCell colSpan={3}>No PMTiles map files were found in <b>map/</b></TableCell>
</TableRow>;
// Handle error state (files === undefined)
if (files === undefined) {
return <PageContainer>
<WROLModeMessage content='Cannot modify Map'/>
<DockerMapImportWarning/>
<SlowImportMessage/>
<ErrorMessage>Could not fetch map files</ErrorMessage>
<DownloadMessage/>
<ViewerMessage/>
</PageContainer>;
}
// --- Catalog table ---
const catalogHeaders = [
{key: 'name', text: 'Region', sortBy: i => i.name.toLowerCase()},
{key: 'size', text: 'Estimated Size', sortBy: i => i.size_estimate || 0},
{key: 'actions', text: '', sortBy: null},
];
const catalogRowFunc = (item) => {
return <MapCatalogRow
key={item.region}
item={item}
subscribedRegions={new Set(subscriptions.map(s => s.region))}
fetchData={fetchSubscriptionData}
/>;
};
if (files === undefined) {
return <PageContainer>
<WROLModeMessage content='Cannot modify Map'/>
<DockerMapImportWarning/>
<SlowImportMessage/>
<Loader size='large' active={import_running} inline='centered'>
{importingMessage}
</Loader>
<SortableTable
tableHeaders={tableHeaders}
data={files}
rowFunc={rowFunc}
rowKey='path'
defaultSortColumn='path'
emptyRow={emptyRow}
footer={footer}
/>
<DownloadMessage/>
<ViewerMessage/>
</PageContainer>
<ErrorMessage>Could not fetch map files</ErrorMessage>
</PageContainer>;
}
return <PageContainer>
<WROLModeMessage content='Cannot modify Map'/>
<Header as='h3'>Map Files</Header>
<SortableTable
tableHeaders={fileHeaders}
data={files}
rowFunc={fileRowFunc}
rowKey='name'
defaultSortColumn='name'
emptyRow={emptyRow}
/>
<Divider/>
<div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5em'}}>
<Header as='h3'>Map Subscriptions</Header>
<Button size='tiny' icon='globe' content='View All Regions' onClick={() => setAllRegionsOpen(true)}/>
</div>
<AllRegionsPreviewModal catalog={catalog} open={allRegionsOpen} onClose={() => setAllRegionsOpen(false)}/>
<SortableTable
tableHeaders={catalogHeaders}
data={catalog}
rowFunc={catalogRowFunc}
rowKey='region'
defaultSortColumn='name'
/>
<InfoMessage storageName='hint_map_subscribe'>
<Message.Header>How to get map files</Message.Header>
<p>Subscribe to a map region to automatically download it. Subscriptions will
periodically check for updated maps. Downloads may take a long time depending on
the region size and your internet speed. You can monitor progress on
the <b>Downloads</b> page.</p>
<p>You can also manually extract a region using the <b>pmtiles</b> command-line tool
and place the resulting file into the <b>map/</b> directory:</p>
<pre> pmtiles extract https://build.protomaps.com/YYYYMMDD.pmtiles region.pmtiles \{'\n'} --bbox="-125.0,24.4,-66.9,49.4"</pre>
<p>Find the latest build date at&nbsp;
<a href='https://maps.protomaps.com/builds/' rel='noopener noreferrer'
target='_blank'>maps.protomaps.com/builds</a>
</p>
</InfoMessage>
<HandPointMessage>
<p>You can also view the map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
</HandPointMessage>
</PageContainer>
}
const PIN_COLORS = ["red", "blue", "green", "yellow", "orange", "purple"];
function PinEditRow({pin, onSave, onCancel}) {
const [label, setLabel] = useState(pin.label);
const [color, setColor] = useState(pin.color);
return <TableRow>
<TableCell collapsing>
<div style={{display: "flex", gap: 4}}>
{PIN_COLORS.map(c =>
<div
key={c}
onClick={() => setColor(c)}
style={{
width: 20, height: 20, borderRadius: "50%", background: c, cursor: "pointer",
border: color === c ? "3px solid #333" : "2px solid #ccc",
}}
/>
)}
</div>
</TableCell>
<TableCell>
<Input
size='small'
value={label}
onChange={(e) => setLabel(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && label.trim() && onSave(pin.id, label.trim(), color)}
/>
</TableCell>
<TableCell>{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}</TableCell>
<Media greaterThan='mobile'><TableCell>{pin.created}</TableCell></Media>
<TableCell collapsing>
<Button size='tiny' color='green' onClick={() => label.trim() && onSave(pin.id, label.trim(), color)}>Save</Button>
<Button size='tiny' onClick={onCancel}>Cancel</Button>
</TableCell>
</TableRow>;
}
function MapPins() {
const [pins, setPins] = useState([]);
const [filter, setFilter] = useState('');
const [editingId, setEditingId] = useState(null);
const navigate = useNavigate();
const fetchPins = async () => {
try {
const data = await getMapPins();
if (data) setPins(data.pins || []);
} catch (e) {
console.error(e);
}
};
useEffect(() => {
fetchPins();
}, []);
const handleDelete = async (pinId) => {
await deleteMapPin(pinId);
setEditingId(null);
await fetchPins();
};
const handleSave = async (pinId, label, color) => {
await updateMapPin(pinId, label, color);
setEditingId(null);
await fetchPins();
};
const handleNavigate = (pin) => {
navigate(`/map?lat=${pin.lat}&lon=${pin.lon}&z=14`);
};
// --- Desktop headers and row ---
const fullHeaders = [
{key: 'color', text: '', sortBy: i => i.color},
{key: 'label', text: 'Label', sortBy: i => i.label.toLowerCase()},
{key: 'coords', text: 'Coordinates', sortBy: i => i.lat},
{key: 'created', text: 'Created', sortBy: i => i.created},
{key: 'actions', text: '', sortBy: null},
];
const fullRowFunc = (pin) => {
if (editingId === pin.id) {
return <PinEditRow
key={pin.id}
pin={pin}
onSave={handleSave}
onCancel={() => setEditingId(null)}
/>;
}
return <TableRow key={pin.id}>
<TableCell collapsing>
<div style={{
width: 16, height: 16, borderRadius: "50%",
background: pin.color || "red", border: "1px solid #ccc",
}}/>
</TableCell>
<TableCell>{pin.label}</TableCell>
<TableCell>
<a href="#" onClick={(e) => {e.preventDefault(); handleNavigate(pin);}}>
{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}
</a>
</TableCell>
<TableCell>{pin.created}</TableCell>
<TableCell collapsing>
<Button size='tiny' icon='edit' onClick={() => setEditingId(pin.id)}/>
<APIButton
size='tiny'
color='red'
icon='trash'
confirmContent='Delete this pin?'
confirmButton='Delete'
onClick={() => handleDelete(pin.id)}
/>
</TableCell>
</TableRow>;
};
// --- Mobile headers and row ---
const mobileHeaders = [
{key: 'color', text: '', sortBy: i => i.color},
{key: 'label', text: 'Label', sortBy: i => i.label.toLowerCase()},
{key: 'actions', text: '', sortBy: null},
];
const mobileRowFunc = (pin) => {
return <TableRow key={pin.id}>
<TableCell collapsing>
<div style={{
width: 16, height: 16, borderRadius: "50%",
background: pin.color || "red", border: "1px solid #ccc",
}}/>
</TableCell>
<TableCell>
<a href="#" onClick={(e) => {e.preventDefault(); handleNavigate(pin);}}>
{pin.label}
</a>
<div style={{fontSize: 11, color: '#888'}}>{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}</div>
</TableCell>
<TableCell collapsing>
<APIButton
size='tiny'
color='red'
icon='trash'
confirmContent='Delete this pin?'
confirmButton='Delete'
onClick={() => handleDelete(pin.id)}
/>
</TableCell>
</TableRow>;
};
const emptyRow = <TableRow>
<TableCell colSpan={5}>No pins. Right-click on the map to add one.</TableCell>
</TableRow>;
const lowerFilter = filter.toLowerCase();
const filteredPins = lowerFilter
? pins.filter(p =>
(p.label || '').toLowerCase().includes(lowerFilter) ||
`${p.lat.toFixed(4)}, ${p.lon.toFixed(4)}`.includes(lowerFilter)
)
: pins;
return <PageContainer>
<Input
icon='search'
placeholder='Filter by label or coordinates...'
value={filter}
onChange={(e) => setFilter(e.target.value)}
style={{marginBottom: '1em', width: '100%'}}
/>
<Media at='mobile'>
<SortableTable
tableProps={{unstackable: true}}
tableHeaders={mobileHeaders}
data={filteredPins}
rowFunc={mobileRowFunc}
rowKey='label'
defaultSortColumn='label'
emptyRow={emptyRow}
/>
</Media>
<Media greaterThanOrEqual='tablet'>
<SortableTable
tableProps={{unstackable: true}}
tableHeaders={fullHeaders}
data={filteredPins}
rowFunc={fullRowFunc}
rowKey='label'
defaultSortColumn='label'
emptyRow={emptyRow}
/>
</Media>
</PageContainer>;
}
function MapPage() {
const fallback = <Segment>
<Header as='h3'>Failed to fetch Map service.</Header>
<p>You may need to give permission to access the page: <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
<p>Map startup is delayed on boot, if you have just started your WROLPi try again in a few minutes.</p>
<p>If the above does not work, try starting the service:</p>
<pre>sudo systemctl start renderd</pre>
<pre>sudo systemctl start apache2</pre>
<p>Check the logs</p>
<pre>journalctl -u renderd</pre>
<pre>sudo tail -f /var/log/apache2/*log</pre>
</Segment>;
return <IframeViewer title='map' src={MAP_VIEWER_URI} fallback={fallback}/>
return <MapViewer/>;
}
export function MapRoute() {
@ -304,6 +612,7 @@ export function MapRoute() {
const links = [
{text: 'Map', to: '/map', key: 'map', end: true},
{text: 'Pins', to: '/map/pins', key: 'pins'},
{text: 'Manage', to: '/map/manage', key: 'manage'},
];
@ -311,7 +620,8 @@ export function MapRoute() {
<TabLinks links={links}/>
<Routes>
<Route path='/' exact element={<MapPage/>}/>
<Route path='pins' exact element={<MapPins/>}/>
<Route path='manage' exact element={<ManageMap/>}/>
</Routes>
</div>
}
}

View file

@ -0,0 +1,781 @@
import React, {useCallback, useContext, useEffect, useRef, useState} from "react";
import {useSearchParams} from "react-router";
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import {Protocol} from "pmtiles";
import layers from "protomaps-themes-base";
import mlcontour from "@acalcutt/maplibre-contour-pmtiles";
import {addMapPin, deleteMapPin, getMapFiles, getMapPins} from "../api";
import {MAP_VIEWER_URI} from "./Vars";
import {Checkbox, Icon, Segment} from "semantic-ui-react";
import {Header} from "./Theme";
import {ThemeContext} from "../contexts/contexts";
// Terrain DEM file prefix for hillshade and contours.
const TERRAIN_PREFIX = "terrain-";
// Detect full planet files: "planet-20260329.pmtiles" or bare date like "20260329.pmtiles".
function isPlanetFile(name) {
if (name.startsWith("planet-")) return true;
return /^\d{8}\.pmtiles$/.test(name);
}
// Layer groups matching the standalone viewer.
const LAYER_GROUPS = {
"Hillshade": ["hillshade"],
"Contours": ["contour-lines", "contour-labels"],
"Water": ["water"],
"Land Cover": [
"landcover", "landuse_park", "landuse_urban_green", "landuse_beach",
"landuse_aerodrome", "landuse_hospital", "landuse_industrial",
"landuse_pedestrian", "landuse_pier", "landuse_school", "landuse_zoo",
],
"Buildings": ["buildings"],
"Roads - Highway": ["roads_highway"],
"Roads - Major": ["roads_major", "roads_link"],
"Roads - Minor": ["roads_minor", "roads_other"],
"Roads - Tunnels": ["roads_tunnels"],
"Roads - Bridges": ["roads_bridges"],
"Rail & Runways": ["roads_rail", "roads_runway", "roads_taxiway", "landuse_runway"],
"Boundaries": ["boundaries"],
"Labels": ["roads_labels", "places_", "address_label", "pois", "water_label", "water_waterway_label"],
};
// Register PMTiles protocol once.
const protocol = new Protocol();
maplibregl.addProtocol("pmtiles", protocol.tile);
// Planet overview blob — provides global basemap at zoom 0-6.
const MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles";
// Layers to skip from non-primary sources (they would paint over the primary source's content).
const SKIP_SECONDARY = new Set(["background", "earth"]);
// Set up contour DEM source (must be called once before buildStyle).
let demSource = null;
let terrainUrl = null;
function initContourSource(filename) {
terrainUrl = `/media/map/${filename}`;
if (demSource) return;
demSource = new mlcontour.DemSource({
url: `pmtiles://${window.location.origin}${terrainUrl}`,
encoding: "terrarium",
maxzoom: 8,
worker: true,
});
demSource.setupMaplibre(maplibregl);
}
// sources: [{name, url}] where name is used as the MapLibre source ID and url is the pmtiles:// URL.
// hasTerrain: whether to include hillshade and contour layers.
// scaleUnit: "metric" or "imperial" — affects contour intervals and labels.
function buildStyle(sources, flavor = "light", hasTerrain = false, scaleUnit = "metric") {
const styleSources = {};
const allLayers = [];
for (let i = 0; i < sources.length; i++) {
const {name, url} = sources[i];
styleSources[name] = {type: "vector", url};
const fileLayers = layers(name, flavor);
if (i === 0) {
// Primary source: use layer IDs as-is.
allLayers.push(...fileLayers);
} else {
// Additional sources: prefix layer IDs and skip background/earth.
for (const layer of fileLayers) {
if (SKIP_SECONDARY.has(layer.id)) continue;
allLayers.push({...layer, id: `${name}:${layer.id}`});
}
}
}
// Add terrain sources and layers if available.
if (hasTerrain && demSource) {
// Read saved visibility to set initial layer state correctly.
const savedVis = getInitialVisibility();
const hillshadeVis = savedVis["Hillshade"] ? "visible" : "none";
const contourVis = savedVis["Contours"] ? "visible" : "none";
// Hillshade from raster-dem source.
styleSources["terrain-dem"] = {
type: "raster-dem",
url: `pmtiles://${terrainUrl}`,
encoding: "terrarium",
tileSize: 512,
};
// Insert hillshade early (after earth/landcover, before roads).
const hillshadeSearch = allLayers.findIndex(l => l.id === "buildings");
const hillshadeIdx = hillshadeSearch === -1 ? allLayers.length : hillshadeSearch;
allLayers.splice(hillshadeIdx, 0, {
id: "hillshade",
type: "hillshade",
source: "terrain-dem",
layout: {visibility: hillshadeVis},
paint: {
"hillshade-shadow-color": "#000000",
"hillshade-illumination-anchor": "viewport",
"hillshade-exaggeration": 0.3,
},
});
// Contour lines from on-the-fly generation.
const isImperial = scaleUnit === "imperial";
const contourUrl = demSource.contourProtocolUrl({
overzoom: 1,
contourLayer: "contours",
elevationKey: "ele",
levelKey: "level",
multiplier: isImperial ? 3.28084 : 1, // meters to feet conversion
thresholds: isImperial ? {
// [minor, major] contour intervals in feet per zoom level.
4: [1000, 5000],
5: [500, 2500],
6: [200, 1000],
7: [200, 1000],
8: [100, 500],
} : {
// [minor, major] contour intervals in meters per zoom level.
4: [500, 2500],
5: [200, 1000],
6: [100, 500],
7: [100, 500],
8: [50, 200],
},
});
const elevUnit = isImperial ? "ft" : "m";
styleSources["contours"] = {
type: "vector",
tiles: [contourUrl],
maxzoom: 8,
};
allLayers.push(
{
id: "contour-lines",
type: "line",
source: "contours",
"source-layer": "contours",
filter: ["!=", ["get", "level"], 1],
layout: {visibility: contourVis},
paint: {"line-color": "rgba(150,100,50,0.3)", "line-width": 0.5},
},
{
id: "contour-lines-major",
type: "line",
source: "contours",
"source-layer": "contours",
filter: ["==", ["get", "level"], 1],
layout: {visibility: contourVis},
paint: {"line-color": "rgba(150,100,50,0.5)", "line-width": 1},
},
{
id: "contour-labels",
type: "symbol",
source: "contours",
"source-layer": "contours",
filter: ["==", ["get", "level"], 1],
layout: {
visibility: contourVis,
"symbol-placement": "line",
"text-field": ["concat", ["get", "ele"], elevUnit],
"text-size": 10,
},
paint: {
"text-color": flavor === "dark" ? "rgba(210,180,140,0.9)" : "rgba(150,100,50,0.8)",
"text-halo-color": flavor === "dark" ? "rgba(0,0,0,0.8)" : "rgba(255,255,255,0.8)",
"text-halo-width": 1,
},
},
);
}
return {
version: 8,
glyphs: "/map-assets/fonts/{fontstack}/{range}.pbf",
sprite: `${window.location.origin}/map-assets/sprites/${flavor}`,
sources: styleSources,
layers: allLayers,
};
}
// Groups that start hidden by default (used when no saved state exists).
const DEFAULT_HIDDEN = new Set(["Hillshade", "Contours"]);
const STORAGE_KEY_LAYERS = "wrolpi-map-layers";
const STORAGE_KEY_SCALE = "wrolpi-map-scale";
function getInitialVisibility() {
try {
const saved = localStorage.getItem(STORAGE_KEY_LAYERS);
if (saved) return JSON.parse(saved);
} catch (e) { /* ignore */ }
const v = {};
for (const g of Object.keys(LAYER_GROUPS)) v[g] = !DEFAULT_HIDDEN.has(g);
return v;
}
function LayerControl({map, scaleUnit, onScaleUnitChange, visibilityRef}) {
const [visibility, setVisibility] = useState(() => {
const v = getInitialVisibility();
if (visibilityRef) visibilityRef.current = v;
return v;
});
const [collapsed, setCollapsed] = useState(true);
const toggleGroup = useCallback((groupName, checked) => {
if (!map) return;
const prefixes = LAYER_GROUPS[groupName];
const allMapLayers = map.getStyle()?.layers || [];
for (const layer of allMapLayers) {
// Match both plain IDs and prefixed IDs (e.g., "water" and "file.pmtiles:water").
const baseId = layer.id.includes(":") ? layer.id.split(":").slice(1).join(":") : layer.id;
if (prefixes.some(p => baseId.includes(p))) {
map.setLayoutProperty(layer.id, "visibility", checked ? "visible" : "none");
}
}
setVisibility(prev => {
const next = {...prev, [groupName]: checked};
if (visibilityRef) visibilityRef.current = next;
try { localStorage.setItem(STORAGE_KEY_LAYERS, JSON.stringify(next)); } catch (e) { /* ignore */ }
return next;
});
}, [map, visibilityRef]);
const panelStyle = {
position: "absolute",
top: 10,
left: 10,
zIndex: 1000,
background: "white",
borderRadius: 8,
boxShadow: "0 2px 8px rgba(0,0,0,0.2)",
maxHeight: "calc(100vh - 120px)",
overflowY: "auto",
minWidth: 200,
fontSize: 13,
};
return <div style={panelStyle}>
<div
style={{
padding: "8px 12px", cursor: "pointer", fontWeight: 600,
display: "flex", justifyContent: "space-between", alignItems: "center",
borderBottom: collapsed ? "none" : "1px solid #eee", userSelect: "none",
}}
onClick={() => setCollapsed(c => !c)}
>
<span>Layers</span>
<Icon name={collapsed ? "chevron right" : "chevron down"} size="small"/>
</div>
{!collapsed && <div style={{padding: "4px 12px 8px"}}>
{Object.keys(LAYER_GROUPS).map(name =>
<div key={name} style={{padding: "2px 0"}}>
<Checkbox
label={name}
checked={visibility[name]}
onChange={(e, {checked}) => toggleGroup(name, checked)}
/>
</div>
)}
<div style={{borderTop: "1px solid #eee", marginTop: 6, paddingTop: 6}}>
<Checkbox
toggle
label={scaleUnit === "imperial" ? "Imperial" : "Metric"}
checked={scaleUnit === "imperial"}
onChange={(e, {checked}) => onScaleUnitChange(checked ? "imperial" : "metric")}
/>
</div>
</div>}
</div>;
}
const PIN_COLORS = ["red", "blue", "green", "yellow", "orange", "purple"];
function AddPinDialog({lat, lon, onSubmit, onCancel}) {
const [label, setLabel] = useState("");
const [color, setColor] = useState("red");
return <div style={{
position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)",
zIndex: 1002, background: "white", borderRadius: 8, boxShadow: "0 4px 16px rgba(0,0,0,0.3)",
padding: 16, minWidth: 250,
}}>
<div style={{fontWeight: 600, marginBottom: 8}}>Add Pin</div>
<div style={{fontSize: 12, color: "#666", marginBottom: 8}}>{lat.toFixed(4)}, {lon.toFixed(4)}</div>
<input
type="text"
placeholder="Label"
value={label}
onChange={e => setLabel(e.target.value)}
autoFocus
onKeyDown={e => e.key === "Enter" && label.trim() && onSubmit(label.trim(), color)}
style={{width: "100%", padding: "6px 8px", marginBottom: 8, border: "1px solid #ccc", borderRadius: 4}}
/>
<div style={{display: "flex", gap: 6, marginBottom: 12}}>
{PIN_COLORS.map(c =>
<div
key={c}
onClick={() => setColor(c)}
style={{
width: 24, height: 24, borderRadius: "50%", background: c, cursor: "pointer",
border: color === c ? "3px solid #333" : "2px solid #ccc",
}}
/>
)}
</div>
<div style={{display: "flex", gap: 8, justifyContent: "flex-end"}}>
<button onClick={onCancel} style={{padding: "4px 12px", cursor: "pointer"}}>Cancel</button>
<button
onClick={() => label.trim() && onSubmit(label.trim(), color)}
disabled={!label.trim()}
style={{padding: "4px 12px", cursor: "pointer", background: "#6435c9", color: "white", border: "none", borderRadius: 4}}
>
Add
</button>
</div>
</div>;
}
export default function MapViewer() {
const mapContainer = useRef(null);
const mapRef = useRef(null);
const scaleControlRef = useRef(null);
const activeFilesRef = useRef([]);
const hasTerrainRef = useRef(false);
const layerVisibilityRef = useRef(null);
const [mapReady, setMapReady] = useState(false);
const [error, setError] = useState(null);
const [contextMenu, setContextMenu] = useState(null);
const [addingPin, setAddingPin] = useState(null); // {lat, lon} when pin dialog is open
const markersRef = useRef([]);
const pinsVisibleRef = useRef(true);
const [scaleUnit, setScaleUnit] = useState(() => {
try { return localStorage.getItem(STORAGE_KEY_SCALE) || "metric"; } catch (e) { return "metric"; }
});
const [searchParams, setSearchParams] = useSearchParams();
const {theme} = useContext(ThemeContext);
// Parse initial coordinates from URL.
const initialLat = parseFloat(searchParams.get("lat")) || 0;
const initialLon = parseFloat(searchParams.get("lon")) || 0;
const initialZoom = parseFloat(searchParams.get("z")) || 2;
useEffect(() => {
if (!mapContainer.current) return;
let map;
let destroyed = false;
const init = async () => {
const mapSources = [];
// Fetch user's PMTiles files first to determine what base layer is needed.
let hasTerrain = false;
let terrainFileName = null;
let planetFile = null;
try {
const data = await getMapFiles();
if (data?.files) {
const regionFiles = [];
for (const f of data.files) {
if (f.name.startsWith(TERRAIN_PREFIX) && f.name.endsWith('.pmtiles')) {
hasTerrain = true;
terrainFileName = f.name;
} else if (isPlanetFile(f.name)) {
if (!planetFile || f.size > planetFile.size) {
planetFile = f;
}
} else {
regionFiles.push(f);
}
}
if (planetFile) {
// Planet covers everything — sole vector source, no overview needed.
mapSources.push({name: planetFile.name, url: `pmtiles:///media/map/${planetFile.name}`});
} else {
// Use regional extracts.
for (const f of regionFiles) {
mapSources.push({name: f.name, url: `pmtiles:///media/map/${f.name}`});
}
// Add planet overview blob as low-zoom base layer (if available).
try {
const resp = await fetch(MAP_OVERVIEW_URL, {method: "HEAD"});
if (resp.ok) {
mapSources.unshift({name: "map-overview", url: `pmtiles://${MAP_OVERVIEW_URL}`});
}
} catch (e) {
console.debug("Planet overview not available:", e);
}
}
}
} catch (e) {
console.error("Failed to fetch map files:", e);
}
if (destroyed) return;
activeFilesRef.current = mapSources;
hasTerrainRef.current = hasTerrain;
// Initialize contour source if terrain data is available.
if (hasTerrain) {
initContourSource(terrainFileName);
}
try {
map = new maplibregl.Map({
container: mapContainer.current,
style: buildStyle(mapSources, theme, hasTerrain, scaleUnit),
center: [initialLon, initialLat],
zoom: initialZoom,
attributionControl: true,
preserveDrawingBuffer: true,
});
map.addControl(new maplibregl.NavigationControl(), "top-right");
map.addControl(new maplibregl.FullscreenControl(), "top-right");
const sc = new maplibregl.ScaleControl({maxWidth: 200, unit: scaleUnit});
map.addControl(sc, "bottom-left");
scaleControlRef.current = sc;
map.addControl(new maplibregl.GeolocateControl({
positionOptions: {enableHighAccuracy: true},
trackUserLocation: true,
showUserHeading: true,
showAccuracyCircle: true,
}), "top-right");
// Pin toggle button.
const pinToggle = document.createElement("button");
pinToggle.type = "button";
pinToggle.title = "Toggle pins";
pinToggle.textContent = "📍";
pinToggle.style.cssText = "font-size:18px;width:29px;height:29px;border:none;cursor:pointer;background:white;border-radius:4px;display:flex;align-items:center;justify-content:center;";
pinToggle.addEventListener("click", () => {
pinsVisibleRef.current = !pinsVisibleRef.current;
const display = pinsVisibleRef.current ? "" : "none";
pinToggle.style.opacity = pinsVisibleRef.current ? "1" : "0.5";
for (const m of markersRef.current) {
m.getElement().style.display = display;
}
});
const pinControl = {
onAdd: () => {
const container = document.createElement("div");
container.className = "maplibregl-ctrl maplibregl-ctrl-group";
container.appendChild(pinToggle);
return container;
},
onRemove: () => {},
};
map.addControl(pinControl, "top-right");
// Right-click context menu (desktop).
map.on("contextmenu", (e) => {
if (destroyed) return;
setContextMenu({
x: e.point.x,
y: e.point.y,
lat: e.lngLat.lat,
lon: e.lngLat.lng,
});
});
map.on("click", () => setContextMenu(null));
map.on("movestart", () => setContextMenu(null));
// Long-press context menu (mobile).
let longPressTimer = null;
let touchStartPos = null;
const canvas = map.getCanvas();
canvas.addEventListener("touchstart", (e) => {
if (e.touches.length !== 1) return;
touchStartPos = {x: e.touches[0].clientX, y: e.touches[0].clientY};
longPressTimer = setTimeout(() => {
const rect = canvas.getBoundingClientRect();
const point = {x: touchStartPos.x - rect.left, y: touchStartPos.y - rect.top};
const lngLat = map.unproject(point);
setContextMenu({x: point.x, y: point.y, lat: lngLat.lat, lon: lngLat.lng});
}, 500);
}, {passive: true});
canvas.addEventListener("touchmove", (e) => {
if (longPressTimer && touchStartPos) {
const dx = e.touches[0].clientX - touchStartPos.x;
const dy = e.touches[0].clientY - touchStartPos.y;
if (Math.abs(dx) > 10 || Math.abs(dy) > 10) {
clearTimeout(longPressTimer);
longPressTimer = null;
}
}
});
canvas.addEventListener("touchend", () => {
clearTimeout(longPressTimer);
longPressTimer = null;
});
// Update URL on pan/zoom (only while mounted).
map.on("moveend", () => {
if (destroyed) return;
const center = map.getCenter();
const zoom = map.getZoom();
window.history.replaceState(null, '',
`${window.location.pathname}?lat=${center.lat.toFixed(4)}&lon=${center.lng.toFixed(4)}&z=${zoom.toFixed(1)}`
);
});
map.on("load", () => {
if (!destroyed) {
mapRef.current = map;
// Apply saved layer visibility on initial load.
const savedVis = getInitialVisibility();
const allMapLayers = map.getStyle()?.layers || [];
for (const [groupName, visible] of Object.entries(savedVis)) {
const prefixes = LAYER_GROUPS[groupName];
if (!prefixes) continue;
for (const layer of allMapLayers) {
const baseId = layer.id.includes(":") ? layer.id.split(":").slice(1).join(":") : layer.id;
if (prefixes.some(p => baseId.includes(p))) {
map.setLayoutProperty(layer.id, "visibility", visible ? "visible" : "none");
}
}
}
setMapReady(true);
}
});
} catch (e) {
console.error("MapLibre failed to initialize:", e);
if (!destroyed) setError(e.message);
}
};
init();
return () => {
destroyed = true;
if (map) {
map.remove();
}
mapRef.current = null;
setMapReady(false);
// Clean up map params from URL so they don't leak to other pages.
const url = new URL(window.location);
url.searchParams.delete("lat");
url.searchParams.delete("lon");
url.searchParams.delete("z");
window.history.replaceState(null, '', url.pathname + url.search);
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
// Rebuild style when theme changes.
useEffect(() => {
const map = mapRef.current;
if (!map || !mapReady) return;
const center = map.getCenter();
const zoom = map.getZoom();
map.setStyle(buildStyle(activeFilesRef.current, theme, hasTerrainRef.current, scaleUnit));
map.once("style.load", () => {
map.setCenter(center);
map.setZoom(zoom);
// Re-apply layer visibility state after style rebuild.
const vis = layerVisibilityRef.current;
if (vis) {
const allMapLayers = map.getStyle()?.layers || [];
for (const [groupName, visible] of Object.entries(vis)) {
const prefixes = LAYER_GROUPS[groupName];
if (!prefixes) continue;
for (const layer of allMapLayers) {
const baseId = layer.id.includes(":") ? layer.id.split(":").slice(1).join(":") : layer.id;
if (prefixes.some(p => baseId.includes(p))) {
map.setLayoutProperty(layer.id, "visibility", visible ? "visible" : "none");
}
}
}
}
});
}, [theme, mapReady, scaleUnit]);
const handleScaleUnitChange = useCallback((unit) => {
const map = mapRef.current;
const sc = scaleControlRef.current;
if (map && sc) {
map.removeControl(sc);
const newSc = new maplibregl.ScaleControl({maxWidth: 200, unit});
map.addControl(newSc, "bottom-left");
scaleControlRef.current = newSc;
}
try { localStorage.setItem(STORAGE_KEY_SCALE, unit); } catch (e) { /* ignore */ }
setScaleUnit(unit);
}, []);
const handleCopyCoords = useCallback(() => {
if (!contextMenu) return;
// Match decimal precision to current zoom level so pasting into search doesn't over-zoom.
const map = mapRef.current;
const zoom = map ? map.getZoom() : 10;
const decimals = zoom < 4 ? 1 : zoom < 8 ? 2 : zoom < 12 ? 3 : 4;
const text = `${contextMenu.lat.toFixed(decimals)}, ${contextMenu.lon.toFixed(decimals)}`;
navigator.clipboard.writeText(text).catch(() => {
window.prompt("Copy coordinates:", text);
});
setContextMenu(null);
}, [contextMenu]);
const handleExportPng = useCallback(() => {
const map = mapRef.current;
if (!map) return;
setContextMenu(null);
// Force a fresh render, then capture.
map.once("render", function() {
const c = map.getCenter();
const z = map.getZoom();
const filename = `wrolpi-map_${c.lat.toFixed(4)}_${c.lng.toFixed(4)}_z${z.toFixed(0)}.png`;
map.getCanvas().toBlob(function(blob) {
if (!blob) return;
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
});
});
map.triggerRepaint();
}, []);
// --- Pins ---
const loadPins = useCallback(async () => {
const map = mapRef.current;
if (!map) return;
// Remove existing markers.
for (const m of markersRef.current) m.remove();
markersRef.current = [];
const data = await getMapPins();
if (!data?.pins) return;
data.pins.forEach((pin, index) => {
const el = document.createElement("div");
el.style.width = "24px";
el.style.height = "24px";
el.style.borderRadius = "50% 50% 50% 0";
el.style.background = pin.color || "red";
el.style.border = "2px solid white";
el.style.boxShadow = "0 1px 4px rgba(0,0,0,0.4)";
el.style.transform = "rotate(-45deg)";
el.style.cursor = "pointer";
const popup = new maplibregl.Popup({offset: 15}).setHTML(
`<div style="font-size:13px">` +
`<strong>${pin.label || "Pin"}</strong><br/>` +
`<small>${pin.lat.toFixed(4)}, ${pin.lon.toFixed(4)}</small><br/>` +
`<button onclick="window.__deleteMapPin(${pin.id})" ` +
`style="margin-top:4px;padding:2px 8px;cursor:pointer;color:red;border:1px solid red;background:none;border-radius:3px;">` +
`Delete</button></div>`
);
const marker = new maplibregl.Marker({element: el})
.setLngLat([pin.lon, pin.lat])
.setPopup(popup)
.addTo(map);
if (!pinsVisibleRef.current) {
marker.getElement().style.display = "none";
}
markersRef.current.push(marker);
});
}, []);
// Global callback for popup delete buttons.
useEffect(() => {
window.__deleteMapPin = async (pinId) => {
await deleteMapPin(pinId);
await loadPins();
};
return () => { delete window.__deleteMapPin; };
}, [loadPins]);
// Load pins when map is ready.
useEffect(() => {
if (mapReady) loadPins();
}, [mapReady, loadPins]);
const handleAddPin = useCallback(() => {
if (!contextMenu) return;
setAddingPin({lat: contextMenu.lat, lon: contextMenu.lon});
setContextMenu(null);
}, [contextMenu]);
const handleSubmitPin = useCallback(async (label, color) => {
if (!addingPin) return;
const {lat, lon} = addingPin;
setAddingPin(null); // Prevent double-submit.
await addMapPin(lat, lon, label, color);
await loadPins();
}, [addingPin, loadPins]);
if (error) {
return <Segment>
<Header as="h3">Map failed to load</Header>
<p>Your browser may not support WebGL. You can access the standalone map viewer
at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
<p>Error: {error}</p>
</Segment>;
}
return <div ref={mapContainer} style={{position: "relative", width: "100%", height: "85vh"}}>
{mapReady && <LayerControl map={mapRef.current} scaleUnit={scaleUnit} onScaleUnitChange={handleScaleUnitChange} visibilityRef={layerVisibilityRef}/>}
{contextMenu && <div
style={{
position: "absolute",
left: contextMenu.x,
top: contextMenu.y,
zIndex: 1001,
background: "white",
borderRadius: 6,
boxShadow: "0 2px 8px rgba(0,0,0,0.3)",
padding: "4px 0",
fontSize: 13,
minWidth: 180,
}}
>
<div style={{padding: "6px 12px", color: "#666", fontSize: 12, borderBottom: "1px solid #eee"}}>
{(() => {
const map = mapRef.current;
const zoom = map ? map.getZoom() : 10;
const d = zoom < 4 ? 1 : zoom < 8 ? 2 : zoom < 12 ? 3 : 4;
return `${contextMenu.lat.toFixed(d)}, ${contextMenu.lon.toFixed(d)}`;
})()}
</div>
<div
style={{padding: "8px 12px", cursor: "pointer", userSelect: "none"}}
onMouseEnter={e => e.target.style.background = "#f0f0f0"}
onMouseLeave={e => e.target.style.background = "transparent"}
onClick={handleCopyCoords}
>
Copy GPS coordinates
</div>
<div
style={{padding: "8px 12px", cursor: "pointer", userSelect: "none"}}
onMouseEnter={e => e.target.style.background = "#f0f0f0"}
onMouseLeave={e => e.target.style.background = "transparent"}
onClick={handleExportPng}
>
Export as PNG
</div>
<div
style={{padding: "8px 12px", cursor: "pointer", userSelect: "none"}}
onMouseEnter={e => e.target.style.background = "#f0f0f0"}
onMouseLeave={e => e.target.style.background = "transparent"}
onClick={handleAddPin}
>
Add Pin Here
</div>
</div>}
{addingPin && <AddPinDialog
lat={addingPin.lat}
lon={addingPin.lon}
onSubmit={handleSubmitPin}
onCancel={() => setAddingPin(null)}
/>}
</div>;
}

View file

@ -224,8 +224,6 @@ export function NavBar() {
} else {
processingLink = '/files';
}
} else if (status.flags.map_importing) {
processingLink = '/map/manage';
}
}
const processingIcon = processingLink &&

View file

@ -325,6 +325,31 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames, anyTag)
results.apps = {name: 'Apps', results: matchingApps.slice(0, 5)};
}
// Detect coordinates (e.g., "40.76, -111.89" or "40.76 -111.89").
const coordMatch = searchStr && searchStr.trim().match(
/^(-?\d+\.?\d*)[,\s]+(-?\d+\.?\d*)$/
);
if (coordMatch) {
const lat = parseFloat(coordMatch[1]);
const lon = parseFloat(coordMatch[2]);
if (lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180) {
// Derive zoom from decimal precision: 0dp=3, 1dp=7, 2dp=10, 3dp=13, 4dp=16, 5+=18
const maxDecimals = Math.max(
(coordMatch[1].split('.')[1] || '').length,
(coordMatch[2].split('.')[1] || '').length,
);
const zoom = Math.min([3, 7, 10, 13, 16, 18][maxDecimals] || 18, 18);
results.map = {
name: 'Map', results: [{
type: 'map',
title: `${lat}, ${lon}`,
description: 'View on map',
location: `/map?lat=${lat}&lon=${lon}&z=${zoom}`,
}]
};
}
}
setSuggestionsResults(results);
setSuggestionsSums({
fileGroups: newSuggestions.fileGroups,

View file

@ -127,6 +127,8 @@ export const Downloaders = {
File: 'file',
KiwixCatalog: 'kiwix_catalog',
KiwixZim: 'kiwix_zim',
MapCatalog: 'map_catalog',
MapExtract: 'map_extract',
RSS: 'rss',
ScrapeHtml: 'scrape_html',
Video: 'video',

View file

@ -243,7 +243,8 @@ function RecurringDownloadRow({download, fetchDownloads, onDelete}) {
</Modal.Actions>
</Modal>;
const editButton = <Button icon='edit' onClick={handleEditOpen}/>;
const hideEdit = downloader === Downloaders.MapCatalog || downloader === Downloaders.MapExtract;
const editButton = hideEdit ? null : <Button icon='edit' onClick={handleEditOpen}/>;
const restartButton = <APIButton
color='green'