Map search added to global search. Preview cards are displayed for all results in new Map tab.
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run

Map viewer has simple search.

Map search databases can be downloaded from CDN, or built locally. Map searches can be built offline, but will not have enriched things like state names downloaded from Wikidata.
This commit is contained in:
Roland 2026-04-11 20:09:30 -06:00
parent aaa3c0aff7
commit c726654de9
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
21 changed files with 1831 additions and 62 deletions

View file

@ -13,7 +13,7 @@ import {
import {Route, Routes, useNavigate} from "react-router";
import {
deleteMapFile, deleteMapPin, fetchMapSubscriptions, getMapFiles, getMapPins,
mapSubscribe, mapUnsubscribe, updateMapPin
mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, updateMapPin
} from "../api";
import {
Button,
@ -25,7 +25,7 @@ import {
import {SortableTable} from "./SortableTable";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {Header} from "./Theme";
import {Media} from "../contexts/contexts";
import {Media, StatusContext} from "../contexts/contexts";
import {MAP_VIEWER_URI} from "./Vars";
import {Modal} from "./Theme";
import MapViewer from "./MapViewer";
@ -265,6 +265,8 @@ function ManageMap() {
const [catalog, setCatalog] = useState([]);
const [subscriptions, setSubscriptions] = useState([]);
const [allRegionsOpen, setAllRegionsOpen] = useState(false);
const {status} = React.useContext(StatusContext);
const searchBuilding = status?.flags?.map_search_building;
const fetchFiles = async () => {
try {
@ -306,13 +308,31 @@ function ManageMap() {
const fileHeaders = [
{key: 'name', text: 'File', sortBy: i => i.name.toLowerCase()},
{key: 'size', text: 'Size', sortBy: i => i.size || 0},
{key: 'search', text: 'Search', sortBy: null},
{key: 'actions', text: '', sortBy: null},
];
const handleBuildSearch = async (filename) => {
await rebuildMapSearchIndex(filename);
await fetchFiles();
};
const fileRowFunc = (file) => {
return <TableRow key={file.name}>
<TableCell>{file.name}</TableCell>
<TableCell>{humanFileSize(file.size)}</TableCell>
<TableCell collapsing>
{file.name.startsWith('terrain')
? null
: file.has_search_index
? <Button size='tiny' icon='check' content='Built' disabled color='green'/>
: <APIButton size='tiny' icon='search'
content={searchBuilding ? 'Building...' : 'Build'}
disabled={searchBuilding}
loading={searchBuilding}
onClick={() => handleBuildSearch(file.name)}/>
}
</TableCell>
<TableCell collapsing>
<APIButton
color='red'
@ -328,7 +348,7 @@ function ManageMap() {
};
const emptyRow = <TableRow>
<TableCell colSpan={3}>No PMTiles map files were found in <b>map/</b></TableCell>
<TableCell colSpan={4}>No PMTiles map files were found in <b>map/</b></TableCell>
</TableRow>;
// --- Catalog table ---

View file

@ -0,0 +1,133 @@
import React, {useEffect, useState} from "react";
import {Link, useNavigate} from "react-router";
import {CardContent, CardDescription, CardGroup, CardHeader, CardMeta} from "semantic-ui-react";
import {getMapSearchStatus, searchMap} from "../api";
import {Card, Header, Loader, Segment} from "./Theme";
import {Paginator} from "./Common";
import {useLatestRequest, usePages} from "../hooks/customHooks";
import {QueryContext, ThemeContext} from "../contexts/contexts";
import {MAP_VIEWER_URI} from "./Vars";
function formatPopulation(pop) {
if (!pop) return null;
if (pop >= 1_000_000) return `${(pop / 1_000_000).toFixed(1)}M`;
if (pop >= 1_000) return `${Math.round(pop / 1_000)}K`;
return `${pop}`;
}
function MapPlaceCard({place, index}) {
const navigate = useNavigate();
const {s} = React.useContext(ThemeContext);
const [iframeSrc, setIframeSrc] = useState(null);
const zoom = place.min_zoom ? Math.max(8, Math.round(13 - place.min_zoom / 3)) : 11;
const embedSrc = `${MAP_VIEWER_URI}/embed.html#${place.lat},${place.lon},${zoom}`;
// Stagger iframe loading to avoid overwhelming the map viewer with simultaneous requests.
useEffect(() => {
const timer = setTimeout(() => setIframeSrc(embedSrc), 100 + index * 200);
return () => clearTimeout(timer);
}, [embedSrc, index]);
const handleClick = () => {
navigate(`/map?lat=${place.lat}&lon=${place.lon}&z=${zoom}`);
};
const subtitle = [];
if (place.region) subtitle.push(place.region);
const detail = place.kind_detail || place.kind || "";
if (detail && !place.region) subtitle.push(detail.replace(/_/g, " "));
const pop = formatPopulation(place.population);
if (pop) subtitle.push(`pop. ${pop}`);
return <Card onClick={handleClick} style={{cursor: "pointer"}}>
<div style={{height: 150, overflow: "hidden", position: "relative", background: "#1a1a2e"}}>
{iframeSrc && <iframe
src={iframeSrc}
title={place.name}
loading="lazy"
style={{
width: "100%",
height: "100%",
border: "none",
pointerEvents: "none",
}}
/>}
</div>
<CardContent {...s}>
<CardHeader {...s}>{place.name}</CardHeader>
{subtitle.length > 0 && <CardMeta {...s}>{subtitle.join(" \u00b7 ")}</CardMeta>}
<CardDescription {...s}>
{place.lat.toFixed(4)}, {place.lon.toFixed(4)}
</CardDescription>
</CardContent>
</Card>;
}
export function MapSearchView() {
const {searchParams} = React.useContext(QueryContext);
const searchStr = searchParams.get("q") || "";
const {offset, limit, activePage, setPage, totalPages, setTotal} = usePages(12);
// useLatestRequest discards stale responses and catches errors, so rapid pagination
// can't show out-of-order results and a network failure can't leave the spinner stuck.
const {data, sendRequest, loading} = useLatestRequest(300);
const [hasMaps, setHasMaps] = useState(null);
useEffect(() => {
let cancelled = false;
(async () => {
const status = await getMapSearchStatus();
if (!cancelled) {
const installed = (status.indexed || []).length + (status.missing || []).length;
setHasMaps(installed > 0);
}
})();
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
if (!searchStr || searchStr.length < 2) {
setTotal(0);
return;
}
sendRequest(async () => await searchMap(searchStr, limit, offset));
}, [searchStr, offset, limit, sendRequest]);
const results = (data && data.results) || [];
useEffect(() => {
setTotal((data && data.total) || 0);
}, [data, setTotal]);
if (hasMaps === false) {
return <Segment>
<Header as="h4">No maps are installed.</Header>
<p>Subscribe to a map region to search for places.</p>
<Link to="/map/manage">Go to Map Manager</Link>
</Segment>;
}
if (loading) {
return <Segment><Loader active inline="centered"/></Segment>;
}
if (!searchStr) {
return <Segment><Header as="h4">Enter a search query to find map locations.</Header></Segment>;
}
if (results.length === 0) {
return <Segment><Header as="h4">No map locations found for "{searchStr}".</Header></Segment>;
}
return <React.Fragment>
<CardGroup itemsPerRow={3} stackable style={{marginTop: "1em"}}>
{results.map((place, i) =>
<MapPlaceCard key={`${place.name}-${place.lat}-${place.lon}-${i}`} place={place} index={i}/>
)}
</CardGroup>
<center style={{marginTop: '2em'}}>
<Paginator activePage={activePage} totalPages={totalPages} onPageChange={setPage}/>
</center>
</React.Fragment>;
}

View file

@ -5,7 +5,7 @@ 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, setMapDefaultLocation} from "../api";
import {addMapPin, deleteMapPin, getMapFiles, getMapPins, searchMap, setMapDefaultLocation} from "../api";
import {MAP_VIEWER_URI} from "./Vars";
import {Checkbox, Icon, Segment} from "semantic-ui-react";
import {Header} from "./Theme";
@ -221,6 +221,21 @@ function LayerControl({map, scaleUnit, onScaleUnitChange, visibilityRef}) {
return v;
});
const [collapsed, setCollapsed] = useState(true);
const [isMobile, setIsMobile] = useState(
() => typeof window !== "undefined" && window.matchMedia("(max-width: 768px)").matches
);
useEffect(() => {
if (typeof window === "undefined") return;
const mq = window.matchMedia("(max-width: 768px)");
const handler = (e) => setIsMobile(e.matches);
mq.addEventListener ? mq.addEventListener("change", handler) : mq.addListener(handler);
return () => {
mq.removeEventListener ? mq.removeEventListener("change", handler) : mq.removeListener(handler);
};
}, []);
const iconOnly = isMobile && collapsed;
const toggleGroup = useCallback((groupName, checked) => {
if (!map) return;
@ -251,21 +266,35 @@ function LayerControl({map, scaleUnit, onScaleUnitChange, visibilityRef}) {
boxShadow: "0 2px 8px rgba(0,0,0,0.2)",
maxHeight: "calc(100vh - 120px)",
overflowY: "auto",
minWidth: 200,
minWidth: iconOnly ? 0 : 200,
fontSize: 13,
};
const headerStyle = iconOnly
? {
padding: 0, cursor: "pointer", userSelect: "none",
display: "flex", alignItems: "center", justifyContent: "center",
width: 40, height: 40,
}
: {
padding: "8px 12px", cursor: "pointer", fontWeight: 600,
display: "flex", justifyContent: "space-between", alignItems: "center",
borderBottom: collapsed ? "none" : "1px solid #eee", userSelect: "none",
};
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",
}}
style={headerStyle}
onClick={() => setCollapsed(c => !c)}
title="Layers"
aria-label="Layers"
>
<span>Layers</span>
<Icon name={collapsed ? "chevron right" : "chevron down"} size="small"/>
{iconOnly
? <Icon name="map outline" size="large" style={{margin: 0}}/>
: <>
<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 =>
@ -336,6 +365,150 @@ function AddPinDialog({lat, lon, onSubmit, onCancel}) {
</div>;
}
// Coordinate regex: "45.5, -122.6" or "45.5 -122.6"
const COORD_REGEX = /^\s*(-?\d+\.?\d*)\s*[,\s]\s*(-?\d+\.?\d*)\s*$/;
function MapSearch({map}) {
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
const [showResults, setShowResults] = useState(false);
const [searchMarker, setSearchMarker] = useState(null);
const debounceRef = useRef(null);
const containerRef = useRef(null);
// Close results when clicking outside.
useEffect(() => {
const handler = (e) => {
if (containerRef.current && !containerRef.current.contains(e.target)) {
setShowResults(false);
}
};
document.addEventListener("click", handler);
return () => document.removeEventListener("click", handler);
}, []);
const doSearch = useCallback((q) => {
if (!q || q.length < 2) {
setResults([]);
setShowResults(false);
return;
}
// Check for coordinate input first.
const coordMatch = q.match(COORD_REGEX);
if (coordMatch) {
const lat = parseFloat(coordMatch[1]);
const lon = parseFloat(coordMatch[2]);
if (lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180) {
setResults([{name: `${lat}, ${lon}`, kind: "coordinates", lat, lon, min_zoom: 0, source: "input"}]);
setShowResults(true);
return;
}
}
// Get current map center for proximity bias.
let lat = null, lon = null;
if (map) {
const center = map.getCenter();
lat = center.lat;
lon = center.lng;
}
searchMap(q, 8, 0, lat, lon).then(data => {
setResults(data.results || []);
setShowResults((data.results || []).length > 0);
});
}, [map]);
const handleInput = useCallback((e) => {
const q = e.target.value;
setQuery(q);
clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => doSearch(q), 300);
}, [doSearch]);
const handleSelect = useCallback((result) => {
if (!map) return;
// Remove old search marker.
if (searchMarker) {
searchMarker.remove();
}
const zoom = result.kind === "coordinates" ? 14 : Math.max(map.getZoom(), 12);
map.flyTo({center: [result.lon, result.lat], zoom});
const marker = new maplibregl.Marker({color: "#6435c9"})
.setLngLat([result.lon, result.lat])
.setPopup(new maplibregl.Popup({offset: 25}).setText(result.name))
.addTo(map);
marker.togglePopup();
setSearchMarker(marker);
setShowResults(false);
setQuery(result.name);
}, [map, searchMarker]);
const handleKeyDown = useCallback((e) => {
if (e.key === "Escape") {
setShowResults(false);
e.target.blur();
}
}, []);
const formatPopulation = (pop) => {
if (!pop) return "";
if (pop >= 1_000_000) return `${(pop / 1_000_000).toFixed(1)}M`;
if (pop >= 1_000) return `${(pop / 1_000).toFixed(0)}K`;
return `${pop}`;
};
const resultSubtext = (r) => {
if (r.kind === "coordinates") return "";
const parts = [];
if (r.region) parts.push(r.region);
const detail = r.kind_detail || r.kind || "";
if (detail && !r.region) parts.push(detail.replace(/_/g, " "));
const pop = formatPopulation(r.population);
if (pop) parts.push(`pop. ${pop}`);
return parts.join(" \u00b7 ");
};
return <div ref={containerRef} style={{
position: "absolute", top: 10, left: "50%", transform: "translateX(-50%)",
zIndex: 5, width: 320, maxWidth: "calc(100% - 100px)",
}}>
<input
type="text"
placeholder="Search places..."
value={query}
onChange={handleInput}
onFocus={() => results.length > 0 && setShowResults(true)}
onKeyDown={handleKeyDown}
style={{
width: "100%", padding: "8px 12px", border: "1px solid #ccc", borderRadius: 4,
fontSize: 14, boxShadow: "0 2px 6px rgba(0,0,0,0.2)", background: "white",
}}
/>
{showResults && results.length > 0 && <div style={{
background: "white", border: "1px solid #ccc", borderTop: "none",
borderRadius: "0 0 4px 4px", maxHeight: 300, overflowY: "auto",
boxShadow: "0 4px 8px rgba(0,0,0,0.2)",
}}>
{results.map((r, i) => <div
key={i}
onClick={() => handleSelect(r)}
onMouseEnter={e => e.target.style.background = "#f0f0f0"}
onMouseLeave={e => e.target.style.background = "transparent"}
style={{padding: "8px 12px", cursor: "pointer", borderBottom: "1px solid #eee"}}
>
<div style={{fontWeight: 500}}>{r.name}</div>
{resultSubtext(r) && <div style={{fontSize: 11, color: "#888"}}>{resultSubtext(r)}</div>}
</div>)}
</div>}
</div>;
}
export default function MapViewer() {
const mapContainer = useRef(null);
const mapRef = useRef(null);
@ -742,6 +915,7 @@ export default function MapViewer() {
}
return <div ref={mapContainer} style={{position: "relative", width: "100%", height: "85vh"}}>
{mapReady && <MapSearch map={mapRef.current}/>}
{mapReady && <LayerControl map={mapRef.current} scaleUnit={scaleUnit} onScaleUnitChange={handleScaleUnitChange} visibilityRef={layerVisibilityRef}/>}
{contextMenu && <div
style={{

View file

@ -4,7 +4,8 @@ import {FilesSearchView} from "./Files";
import {useLatestRequest, usePages, useSearchChannels, useSearchDate, useSearchFilter} from "../hooks/customHooks";
import {ShortcutHint} from "./ShortcutHint";
import {ZimSearchView} from "./Zim";
import {searchEstimateFiles, searchEstimateOthers, searchEstimateZims, searchSuggestions} from "../api";
import {MapSearchView} from "./MapSearchView";
import {searchEstimateFiles, searchEstimateMap, searchEstimateOthers, searchEstimateZims, searchSuggestions} from "../api";
import {filterToMimetypes, fuzzyMatch, normalizeEstimate, SearchResultsInput, TabLinks} from "./Common";
import _ from "lodash";
import {TagsContext} from "../Tags";
@ -133,6 +134,7 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
// Zims are slow, so they are separate.
const {data: zimData, sendRequest: sendZimRequest, loading: zimLoading} = useLatestRequest(500);
const {data: otherData, sendRequest: sendOtherRequest, loading: otherLoading} = useLatestRequest(500);
const {data: mapData, sendRequest: sendMapRequest, loading: mapLoading} = useLatestRequest(500);
React.useEffect(() => {
if (searchStr || (tagNames && tagNames.length > 0)) {
@ -141,6 +143,7 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
if (searchStr && searchStr.length > 0) {
// We can't search Channels/Domains without some string to filter by.
sendGeneralReqeust(async () => await searchSuggestions(searchStr));
sendMapRequest(async () => await searchEstimateMap(searchStr));
}
sendFilesRequest(async () => await searchEstimateFiles(searchStr, tagNames, mimetypes, months, dateRange, anyTag));
sendZimRequest(async () => await searchEstimateZims(searchStr, tagNames));
@ -195,6 +198,14 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
}
}, [setSuggestions, otherData]);
React.useEffect(() => {
if (!_.isEmpty(mapData)) {
setSuggestions((prevState) => {
return {...prevState, mapPlaces: mapData.mapPlaces}
});
}
}, [setSuggestions, mapData]);
return {suggestions, loading: generalLoading || zimLoading || filesLoading}
}
@ -329,6 +340,18 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames, anyTag)
const coordMatch = searchStr && searchStr.trim().match(
/^(-?\d+\.?\d*)[,\s]+(-?\d+\.?\d*)$/
);
// Map places suggestion in dropdown.
if (newSuggestions.mapPlaces > 0) {
results['map places'] = {
name: 'Map Places', results: [{
type: 'search',
title: `Map: ${newSuggestions.mapPlaces} places`,
description: 'Search map locations',
location: `/search/map?q=${encodeURIComponent(searchStr)}`,
}]
};
}
if (coordMatch) {
const lat = parseFloat(coordMatch[1]);
const lon = parseFloat(coordMatch[2]);
@ -355,6 +378,7 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames, anyTag)
fileGroups: newSuggestions.fileGroups,
zims: zimSum,
otherSum: otherSum,
mapPlaces: newSuggestions.mapPlaces || 0,
channels: newSuggestions.channels.length,
domains: newSuggestions.domains.length,
authors: newSuggestions.authors?.length,
@ -441,11 +465,13 @@ export function SearchView({suggestions, suggestionsSums, loading}) {
const filesTabName = <span>Files <Label>{normalizeEstimate(suggestionsSums?.fileGroups)}</Label></span>;
const zimsTabName = <span>Zims <Label>{normalizeEstimate(suggestionsSums?.zims)}</Label></span>;
const mapTabName = <span>Map <Label>{normalizeEstimate(suggestionsSums?.mapPlaces)}</Label></span>;
const othersTabName = <span>Other <Label>{normalizeEstimate(suggestionsSums?.otherSum)}</Label></span>;
const links = [
{text: filesTabName, to: `/search${search}`, key: 'filesSearch_', end: true},
{text: zimsTabName, to: `/search/zim${search}`, key: 'zimsSearch'},
{text: mapTabName, to: `/search/map${search}`, key: 'mapSearch'},
{text: othersTabName, to: `/search/other${search}`, key: 'othersSearch'},
];
@ -454,6 +480,7 @@ export function SearchView({suggestions, suggestionsSums, loading}) {
<Routes>
<Route path='/*' element={<FilesSearchView/>}/>
<Route path='/zim' exact element={<ZimSearchView suggestions={suggestions} loading={loading}/>}/>
<Route path='/map' exact element={<MapSearchView/>}/>
<Route path='/other' exact element={<OtherSearchView loading={loading}/>}/>
</Routes>
</React.Fragment>