Open Infrastructure Map, a view of infrastructure data in OpenStreetMap
New search control
Russ Garrett2d5d704f3e56
diff --git a/web/locales/en/translation.json b/web/locales/en/translation.jsonindex 47f2b77..08d768e 100644--- a/web/locales/en/translation.json+++ b/web/locales/en/translation.json@@ -101,7 +101,8 @@"gasification": "Gasification","anaerobic-digestion": "Anaerobic digestion"},- "other-pumping-station": "Other pumping station"+ "other-pumping-station": "Other pumping station",+ "place": "Place"},"info": {"name": "Name",@@ -208,5 +209,9 @@"osmose-power": "Osmose (Power)"},"construction": "under construction",- "disused": "disused"+ "disused": "disused",+ "search": {+ "clear": "Clear search",+ "no-results": "No results found"+ }}diff --git a/web/src/index.css b/web/src/index.cssindex 3c73630..1db32cc 100644--- a/web/src/index.css+++ b/web/src/index.css@@ -1,18 +1,12 @@@import 'maplibre-gl/dist/maplibre-gl.css';:root {- --aa-search-input-height: 33px !important;- --aa-input-icon-size: 20px !important;- --aa-primary-color-rgb: 100, 100, 100 !important;- --aa-input-background-color-rgb: 250, 250, 250 !important;- --aa-input-background-color-alpha: 0.8 !important;---oim-font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;- --oim-font-family-monospace: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono',- 'Oxygen Mono', 'Ubuntu Mono', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Consolas', 'Courier New',- monospace;+ --oim-font-family-monospace:+ ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono',+ 'Ubuntu Mono', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Consolas', 'Courier New', monospace;- --oim-content-background: #fcfcfc;+ --oim-content-background: rgb(252, 252, 252);--oim-text-color: #333;--oim-text-color-light: #666;--oim-text-color-dark: #000;@@ -26,6 +20,9 @@--oim-popup-header-info-background: #e0f6f6;--oim-popup-header-validation-background: #f9e2e4;++ --oim-drop-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);+ --oim-blur: blur(3px) saturate(80%);}* {@@ -69,7 +66,7 @@ header {position: absolute;display: block;font-size: 13px;- backdrop-filter: blur(3px) saturate(80%);+ backdrop-filter: var(--oim-blur);}nav ul {diff --git a/web/src/key/key.css b/web/src/key/key.cssindex bf90e64..d300021 100644--- a/web/src/key/key.css+++ b/web/src/key/key.css@@ -19,7 +19,7 @@min-width: 220px;min-height: 300px;margin: 0px 0px 8px 0px !important;- box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);+ box-shadow: var(--oim-drop-shadow);}.oim-key-panel.visible {diff --git a/web/src/l10n.ts b/web/src/l10n.tsindex 34b9f58..41bcd05 100644--- a/web/src/l10n.ts+++ b/web/src/l10n.ts@@ -1,9 +1,9 @@-import i18next from 'i18next'+import i18next, { t } from 'i18next'/* List of supported languages in the OpenInfraMap layer.* This should be kept up to date with the list in tegola/layers.yml.*/-const layer_supported_languages: string[] = [+export const layer_supported_languages: string[] = ['en','es','el',@@ -20,7 +20,7 @@ const layer_supported_languages: string[] = []/* List of name tags to check, in order */-function local_name_tags(): string[] {+export function local_name_tags(): string[] {const lang = i18next.language.split('-')[0]if (layer_supported_languages.includes(lang)) {return [`name_${lang}`, 'name']@@ -28,4 +28,43 @@ function local_name_tags(): string[] {return ['name']}-export { layer_supported_languages, local_name_tags }+export function formatVoltage(value: number | number[]): string {+ if (!Array.isArray(value)) {+ value = [value]+ }++ const formatter = new Intl.NumberFormat(i18next.language, { maximumFractionDigits: 2 })++ let text = [...value]+ .sort((a, b) => a - b)+ .reverse()+ .map((val) => formatter.format(val))+ .join('/')+ text += ' ' + t('units.kV', 'kV')+ return text+}++export function formatFrequency(value: number | number[]): string {+ if (!Array.isArray(value)) {+ value = [value]+ }++ const formatter = new Intl.NumberFormat(i18next.language, { maximumFractionDigits: 2 })++ let text = [...value]+ .sort((a, b) => a - b)+ .reverse()+ .map((val) => formatter.format(val))+ .join('/')+ text += ' ' + t('units.Hz', 'Hz')+ return text+}++export function formatPower(value: number): string {+ const formatter = new Intl.NumberFormat(i18next.language, { maximumFractionDigits: 2 })+ if (value < 1) {+ return formatter.format(value * 1000) + ' ' + t('units.kW', 'kW')+ } else {+ return formatter.format(value) + ' ' + t('units.MW', 'MW')+ }+}diff --git a/web/src/openinframap.ts b/web/src/openinframap.tsindex 9501c23..fba120b 100644--- a/web/src/openinframap.ts+++ b/web/src/openinframap.ts@@ -8,7 +8,7 @@ import EditButton from './edit-control.js'import InfoPopup from './popup/infopopup.js'import KeyControl from './key/key.js'import WarningBox from './warning-box/warning-box.js'-import OpenInfraMapGeocoder from './geocoder.js'+import OIMSearch from './search/search.ts'import { getStyle, getLayers } from './style/style.js'@@ -123,7 +123,7 @@ export default class OpenInfraMap {map.addControl(new KeyControl(), 'top-right')map.addControl(layer_switcher, 'top-right')map.addControl(new EditButton(), 'bottom-right')- map.addControl(new OpenInfraMapGeocoder(), 'top-left')+ map.addControl(new OIMSearch(), 'top-left')new InfoPopup(getLayers().map((layer: { [x: string]: any }) => layer['id']),6diff --git a/web/src/popup/infopopup.ts b/web/src/popup/infopopup.tsindex 8dbd70a..debad80 100644--- a/web/src/popup/infopopup.ts+++ b/web/src/popup/infopopup.ts@@ -3,7 +3,7 @@ import './infopopup.css'import i18next, { t } from 'i18next'import maplibregl, { LngLat, MapGeoJSONFeature, Popup } from 'maplibre-gl'import { titleCase } from 'title-case'-import { local_name_tags } from '../l10n.ts'+import { local_name_tags, formatVoltage, formatFrequency, formatPower } from '../l10n.ts'import friendlyNames from '../friendlynames.ts'import friendlyIcons from '../friendlyicons.ts'import { el, mount, setChildren, RedomElement } from 'redom'@@ -151,47 +151,6 @@ function truncateUrl(urlString: string, length: number): string {return [parsed.host, ...pathPartsReturnValue.reverse()].join('/')}-function formatVoltage(value: number | number[]): string {- if (!Array.isArray(value)) {- value = [value]- }-- const formatter = new Intl.NumberFormat(i18next.language, { maximumFractionDigits: 2 })-- let text = [...value]- .sort((a, b) => a - b)- .reverse()- .map((val) => formatter.format(val))- .join('/')- text += ' ' + t('units.kV', 'kV')- return text-}--function formatFrequency(value: number | number[]): string {- if (!Array.isArray(value)) {- value = [value]- }-- const formatter = new Intl.NumberFormat(i18next.language, { maximumFractionDigits: 2 })-- let text = [...value]- .sort((a, b) => a - b)- .reverse()- .map((val) => formatter.format(val))- .join('/')- text += ' ' + t('units.Hz', 'Hz')- return text-}--function formatPower(value: number): string {- const formatter = new Intl.NumberFormat(i18next.language, { maximumFractionDigits: 2 })- if (value < 1) {- return formatter.format(value * 1000) + ' ' + t('units.kW', 'kW')- } else {- return formatter.format(value) + ' ' + t('units.MW', 'MW')- }-}-class InfoPopup {layers: string[]min_zoom: anydiff --git a/web/src/search/assets/search.svg b/web/src/search/assets/search.svgnew file mode 100644index 0000000..9640853--- /dev/null+++ b/web/src/search/assets/search.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path style="fill: #777" d="M10.25 2a8.25 8.25 0 0 1 6.34 13.53l5.69 5.69a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215l-5.69-5.69A8.25 8.25 0 1 1 10.25 2ZM3.5 10.25a6.75 6.75 0 1 0 13.5 0 6.75 6.75 0 0 0-13.5 0Z"></path></svg>\ No newline at end of filediff --git a/web/src/search/coordinates.ts b/web/src/search/coordinates.tsnew file mode 100644index 0000000..643dc74--- /dev/null+++ b/web/src/search/coordinates.ts@@ -0,0 +1,27 @@+/*+ * Coordinates search provider - detects if the user has entered lat/lon coordinates+ * and returns them as the most relevant search result.+ */+import { convert as convert_coords } from 'geo-coordinates-parser'+import { SearchResult, ISearchProvider } from './search'++export default class CoordinatesSearch implements ISearchProvider {+ async search(query: string, _limit: number = 5): Promise<SearchResult[]> {+ let coords+ try {+ coords = convert_coords(query)+ } catch (error) {+ return []+ }++ return [+ {+ latitude: parseFloat(coords.decimalLatitude.toFixed(5)),+ longitude: parseFloat(coords.decimalLongitude.toFixed(5)),+ name: query,+ score: 1,+ description: 'Coordinates'+ }+ ]+ }+}diff --git a/web/src/search/opencage.ts b/web/src/search/opencage.tsnew file mode 100644index 0000000..345cbd3--- /dev/null+++ b/web/src/search/opencage.ts@@ -0,0 +1,66 @@+/*+ * Search provider for OpenCage+ */+import { SearchResult, ISearchProvider } from './search'+import { t } from 'i18next'++type OpenCageResult = {+ formatted: string+ name: string+ geometry: {+ lat: string+ lng: string+ }+}++type OpenCageResponse = {+ results: OpenCageResult[]+ total_results: number+ status: {+ message: string+ code: string+ }+}++export default class OpenCageSearch implements ISearchProvider {+ apiKey: string+ language: string+ baseScore: number = 0.8+ url = 'https://api.opencagedata.com/geosearch'++ constructor(apiKey: string, language: string = 'en') {+ this.apiKey = apiKey+ this.language = language+ }++ async search(query: string, limit: number = 5): Promise<SearchResult[]> {+ const searchParams = new URLSearchParams({+ q: query,+ limit: limit.toString(),+ language: this.language+ })++ const result = await fetch(`${this.url}?${searchParams.toString()}`, {+ method: 'GET',+ headers: { 'OpenCage-Geosearch-Key': this.apiKey }+ })++ if (!result.ok) {+ throw new Error('Failed to fetch OpenCage results')+ }++ const data = (await result.json()) as OpenCageResponse++ if (data.results.length === 0) {+ return []+ }++ return data.results.map((result: OpenCageResult, index: number) => ({+ latitude: parseFloat(result.geometry.lat),+ longitude: parseFloat(result.geometry.lng),+ name: result.formatted,+ score: this.baseScore - index * 0.1,+ description: t('names.place')+ }))+ }+}diff --git a/web/src/search/openinframap.ts b/web/src/search/openinframap.tsnew file mode 100644index 0000000..87e137c--- /dev/null+++ b/web/src/search/openinframap.ts@@ -0,0 +1,83 @@+/*+ * Open Infrastructure Map search provider+ */+import { SearchResult, ISearchProvider } from './search'+import { formatVoltage, formatPower } from '../l10n'+import { t } from 'i18next'++type OIMResult = {+ name: string+ type: string+ operator?: string+ voltage?: number+ output?: number+ source?: string+ country: string+ geometry: {+ coordinates: number[]+ }+}++type OIMResponse = {+ results: OIMResult[]+}++export default class OIMSearchProvider implements ISearchProvider {+ url = 'https://openinframap.org/search/typeahead'+ baseScore: number = 0.9+ language: string+ regionNames: Intl.DisplayNames++ constructor(language: string = 'en') {+ this.language = language+ this.regionNames = new Intl.DisplayNames([language], { type: 'region' })+ }++ async search(query: string, _limit: number = 5): Promise<SearchResult[]> {+ const searchParams = new URLSearchParams({+ q: query,+ lang: this.language,+ v: '2'+ })++ const result = await fetch(`${this.url}?${searchParams.toString()}`, {+ method: 'GET'+ })++ if (!result.ok) {+ throw new Error('Failed to fetch OIM search results')+ }++ const data = (await result.json()) as OIMResponse++ if (data.results.length === 0) {+ return []+ }++ return data.results.map((result: OIMResult, index: number) => ({+ latitude: result.geometry.coordinates[1],+ longitude: result.geometry.coordinates[0],+ name: result.name,+ description: this.description(result),+ score: this.baseScore - index * 0.1+ }))+ }++ description(result: OIMResult): string {+ var description = ''+ if (result.type === 'substation' && result.voltage) {+ description += `${t('names.power.substation')} (${formatVoltage(result.voltage / 1000)})`+ } else if (result.type === 'plant' && result.output) {+ description += `${t('names.power.plant')} (${formatPower(result.output / 1e6)})`+ } else {+ description += `${result.type}`+ }+ if (result.country) {+ const country = this.regionNames.of(result.country)+ if (country) {+ description += `, ${country}`+ }+ }+ return description+ }+}diff --git a/web/src/search/search.css b/web/src/search/search.cssnew file mode 100644index 0000000..3716aa1--- /dev/null+++ b/web/src/search/search.css@@ -0,0 +1,107 @@+.oim-search-control {+ position: relative;+ display: flex;+ align-items: center;+ max-width: min(50vw, 15em);++ input {+ color: var(--oim-text-color);++ background-color: rgba(252, 252, 252, 0.6);+ background-image: url(./assets/search.svg);+ background-repeat: no-repeat;+ background-size: 1.2em;+ background-position-y: center;+ background-position-x: 5px;++ border: 1px solid var(--oim-grey);+ border-radius: var(--oim-radius-large);+ height: 2.2rem;+ font-size: 1.2rem;+ padding: 0.5em 25px 0.5em 2em;+ width: 100%;+ backdrop-filter: var(--oim-blur);+ }++ input:focus {+ background-color: var(--oim-content-background);+ }+}++.oim-search-dropdown {+ background-color: var(--oim-content-background);+ border-radius: var(--oim-radius-small);+ box-shadow: var(--oim-drop-shadow);+ max-height: 80vh;+ max-width: min(70vw, 30em);+ overflow-y: hidden;+ margin-top: 0.1em;++ ol {+ padding: 0;+ margin: 0;+ }++ li {+ list-style: none;+ cursor: pointer;+ }++ li:hover {+ background-color: #f0f0f0;+ color: #333;+ }++ li.selected {+ background-color: #e0e0e0;+ }++ li,+ .oim-search-footer {+ padding: 0.3rem 1rem;+ }+}++.oim-search-clear {+ position: absolute;+ right: 5px;+ top: 50%;+ transform: translateY(-50%);+ background: none;+ border: none;+ font-size: 20px;+ line-height: 1;+ cursor: pointer;+ padding: 0 5px;+ color: #999;+}++.oim-search-clear:hover {+ color: #333;+}++.oim-search-status,+.oim-search-empty {+ color: var(--oim-text-color-light);+ display: flex;+ justify-content: center;+ padding: 1rem 0;+}++.oim-search-status {+ font-size: 1.5em;+}++.oim-search-footer {+ color: var(--oim-text-color-light);+ background-color: var(--oim-light-grey);+ font-size: 0.8em;+ a {+ color: var(--oim-text-color-light);+ }+}++.oim-search-description {+ font-size: 0.9em;+ color: var(--oim-text-color-light);+}diff --git a/web/src/search/search.ts b/web/src/search/search.tsnew file mode 100644index 0000000..7af8e2c--- /dev/null+++ b/web/src/search/search.ts@@ -0,0 +1,258 @@+import './search.css'+import i18next, { t } from 'i18next'+import { el } from 'redom'+import { IControl } from 'maplibre-gl'+import OpenCageSearch from './opencage'+import CoordinatesSearch from './coordinates'+import OIMSearchProvider from './openinframap'++export type SearchResult = {+ latitude: number+ longitude: number+ name: string+ score: number+ description?: string+}++export interface ISearchProvider {+ search(query: string, limit?: number): Promise<SearchResult[]>+}++export default class OIMSearch implements IControl {+ map?: maplibregl.Map+ container: HTMLElement+ input: HTMLInputElement+ dropdown: HTMLElement+ clearButton: HTMLElement+ selectedIndex: number = -1+ debounceTimer?: number+ isLoading: boolean = false+ currentResults: SearchResult[] = []+ searchProviders: ISearchProvider[]+ currentQuery: string = ''++ constructor() {+ this.searchProviders = [+ new CoordinatesSearch(),+ // OpenCage API key will only work on openinframap.org or localhost. Thanks to OpenCage for sponsoring!+ new OpenCageSearch('oc_gs_a595f2059dee41d6b7073647aec5c303', i18next.language),+ new OIMSearchProvider(i18next.language)+ ]++ this.input = el('input', {+ type: 'text',+ className: 'oim-search-input'+ }) as HTMLInputElement++ this.clearButton = el(+ 'button',+ {+ className: 'oim-search-clear',+ type: 'button',+ title: t('search.clear'),+ style: { display: 'none' }+ },+ '×'+ )++ this.dropdown = el('div', { className: 'oim-search-dropdown' })+ this.container = el(+ 'div',+ { className: 'maplibregl-ctrl oim-search' },+ el('div', { className: 'oim-search-control' }, this.input, this.clearButton),+ this.dropdown+ )++ this.input.addEventListener('input', this.onInput.bind(this))+ this.input.addEventListener('keydown', this.onKeyDown.bind(this))+ this.clearButton.addEventListener('click', this.clearSearch.bind(this))+ this.dropdown.addEventListener('click', this.onDropdownClick.bind(this))+ }++ onAdd(map: maplibregl.Map): HTMLElement {+ this.map = map+ this.map.on('move', () => {+ this.clearSearch()+ })+ return this.container+ }++ onRemove(): void {+ this.container.parentNode?.removeChild(this.container)+ this.map = undefined+ }++ async onInput(event: Event): Promise<void> {+ const query = (event.target as HTMLInputElement).value.trim()++ this.clearButton.style.display = query ? 'block' : 'none'++ if (this.currentQuery === query) {+ return+ }++ this.currentQuery = query++ if (!query || query.length < 3) {+ this.clearDropdown()+ return+ }++ if (this.debounceTimer) {+ clearTimeout(this.debounceTimer)+ this.debounceTimer = undefined+ }++ this.isLoading = true+ this.showLoadingIndicator()++ this.debounceTimer = window.setTimeout(async () => {+ try {+ const results = await this.search(query)+ if (this.currentQuery !== query) {+ return+ }+ this.isLoading = false+ this.currentResults = results+ this.updateDropdown(results)++ if (results.length > 0) {+ this.selectedIndex = 0+ this.highlightSelected()+ }+ } catch (error) {+ this.isLoading = false+ this.currentResults = []+ console.error('Search error:', error)+ }+ }, 300)+ }++ onKeyDown(event: KeyboardEvent): void {+ if (event.key == 'Escape') {+ event.preventDefault()+ this.clearSearch()+ return+ }++ if (this.currentResults.length === 0) return++ switch (event.key) {+ case 'ArrowDown':+ event.preventDefault()+ this.selectedIndex = Math.min(this.selectedIndex + 1, this.currentResults.length - 1)+ this.highlightSelected()+ break+ case 'ArrowUp':+ event.preventDefault()+ this.selectedIndex = Math.max(this.selectedIndex - 1, -1)+ this.highlightSelected()+ break+ case 'Enter':+ event.preventDefault()+ if (this.selectedIndex >= 0 && this.selectedIndex < this.currentResults.length) {+ this.selectItem(this.currentResults[this.selectedIndex])+ }+ break+ }+ }++ highlightSelected(): void {+ const items = this.dropdown.querySelectorAll('.oim-search-item')+ items.forEach((item) => {+ item.classList.remove('selected')+ })++ if (this.selectedIndex >= 0) {+ items[this.selectedIndex].classList.add('selected')+ }+ }++ selectItem(result: SearchResult): void {+ if (result) {+ this.map!.flyTo({ center: [result.longitude, result.latitude], zoom: 14 })+ this.input.value = result.name+ this.clearDropdown()+ }+ }++ onDropdownClick(event: MouseEvent): void {+ const target = event.target as HTMLElement+ const item = target.closest('.oim-search-item') as HTMLElement+ if (item && item.dataset.index) {+ const index = parseInt(item.dataset.index, 10)+ if (!isNaN(index) && index >= 0 && index < this.currentResults.length) {+ this.selectItem(this.currentResults[index])+ }+ }+ }++ clearSearch(): void {+ this.input.value = ''+ this.clearDropdown()+ this.clearButton.style.display = 'none'+ this.input.blur()+ }++ clearDropdown(): void {+ this.dropdown.innerHTML = ''+ this.selectedIndex = -1+ this.isLoading = false+ this.currentResults = []+ }++ showLoadingIndicator(): void {+ this.clearDropdown()+ const loadingEl = el('div.oim-search-status', '...')+ this.dropdown.appendChild(loadingEl)+ }++ updateDropdown(results: SearchResult[]): void {+ this.clearDropdown()+ this.currentResults = results++ if (results.length === 0) {+ const noResultsEl = el('div.oim-search-empty', t('search.no-results'))+ this.dropdown.appendChild(noResultsEl)+ return+ }++ const list = el('ol', { className: 'oim-search-list' })+ results.forEach((result, index) => {+ const item = el(+ 'li',+ {+ className: 'oim-search-item',+ dataset: {+ index: index.toString()+ }+ },+ el('span.search-result-name', result.name),+ el('div', { className: 'oim-search-description' }, result.description || '')+ )+ list.appendChild(item)+ })++ this.dropdown.appendChild(list)+ this.dropdown.appendChild(+ el(+ 'div',+ { className: 'oim-search-footer' },+ el('a', 'Place search powered by OpenCage', {+ href: 'https://opencagedata.com',+ target: '_blank',+ rel: 'noopener noreferrer'+ })+ )+ )+ }++ async search(query: string): Promise<SearchResult[]> {+ const results = await Promise.all(this.searchProviders.map((provider) => provider.search(query, 5)))++ return results+ .flat()+ .sort((a, b) => b.score - a.score)+ .slice(0, 10)+ }+}