Merge develop

This commit is contained in:
Pieter Vander Vennet 2024-12-11 02:39:31 +01:00
commit a178de3e03
109 changed files with 2202 additions and 2032 deletions

View file

@ -1,4 +1,4 @@
import { Feature } from "geojson"
import { Feature, Geometry } from "geojson"
import { UpdatableFeatureSource } from "../FeatureSource"
import { ImmutableStore, Store, UIEventSource } from "../../UIEventSource"
import LayerConfig from "../../../Models/ThemeConfig/LayerConfig"
@ -7,6 +7,9 @@ import { Overpass } from "../../Osm/Overpass"
import { Utils } from "../../../Utils"
import { TagsFilter } from "../../Tags/TagsFilter"
import { BBox } from "../../BBox"
import { FeatureCollection } from "@turf/turf"
import { OsmTags } from "../../../Models/OsmFeature"
"use strict";
/**
* A wrapper around the 'Overpass'-object.
@ -56,14 +59,13 @@ export default class OverpassFeatureSource implements UpdatableFeatureSource {
this.state = state
this._isActive = options?.isActive ?? new ImmutableStore(true)
this.padToZoomLevel = options?.padToTiles
const self = this
this._layersToDownload = options?.ignoreZoom
? new ImmutableStore(state.layers)
: state.zoom.map((zoom) => this.layersToDownload(zoom))
state.bounds.mapD(
(_) => {
self.updateAsyncIfNeeded()
() => {
this.updateAsyncIfNeeded()
},
[this._layersToDownload]
)
@ -104,10 +106,11 @@ export default class OverpassFeatureSource implements UpdatableFeatureSource {
/**
* Download the relevant data from overpass. Attempt to use a different server if one fails; only downloads the relevant layers
* Will always attempt to download, even is 'options.isActive.data' is 'false', the zoom level is incorrect, ...
* @private
*/
public async updateAsync(overrideBounds?: BBox): Promise<void> {
let data: any = undefined
let data: FeatureCollection<Geometry, OsmTags> = undefined
let lastUsed = 0
const start = new Date()
const layersToDownload = this._layersToDownload.data
@ -116,8 +119,7 @@ export default class OverpassFeatureSource implements UpdatableFeatureSource {
return
}
const self = this
const overpassUrls = self.state.overpassUrl.data
const overpassUrls = this.state.overpassUrl.data
if (overpassUrls === undefined || overpassUrls.length === 0) {
throw "Panic: overpassFeatureSource didn't receive any overpassUrls"
}
@ -140,10 +142,11 @@ export default class OverpassFeatureSource implements UpdatableFeatureSource {
return undefined
}
this.runningQuery.setData(true)
console.trace("Overpass feature source: querying geojson")
data = (await overpass.queryGeoJson(bounds))[0]
} catch (e) {
self.retries.data++
self.retries.ping()
this.retries.data++
this.retries.ping()
console.error(`QUERY FAILED due to`, e)
await Utils.waitFor(1000)
@ -153,12 +156,12 @@ export default class OverpassFeatureSource implements UpdatableFeatureSource {
console.log("Trying next time with", overpassUrls[lastUsed])
} else {
lastUsed = 0
self.timeout.setData(self.retries.data * 5)
this.timeout.setData(this.retries.data * 5)
while (self.timeout.data > 0) {
while (this.timeout.data > 0) {
await Utils.waitFor(1000)
self.timeout.data--
self.timeout.ping()
this.timeout.data--
this.timeout.ping()
}
}
}
@ -180,14 +183,14 @@ export default class OverpassFeatureSource implements UpdatableFeatureSource {
timeNeeded,
"seconds"
)
self.features.setData(data.features)
this.features.setData(data.features)
this._lastQueryBBox = bounds
this._lastRequestedLayers = layersToDownload
} catch (e) {
console.error("Got the overpass response, but could not process it: ", e, e.stack)
} finally {
self.retries.setData(0)
self.runningQuery.setData(false)
this.retries.setData(0)
this.runningQuery.setData(false)
}
}

View file

@ -24,8 +24,6 @@ export default class ThemeSource extends FeatureSourceMerger {
*/
public readonly isLoading: Store<boolean>
private readonly supportsForceDownload: UpdatableFeatureSource[]
public static readonly fromCacheZoomLevel = 15
/**
@ -44,8 +42,6 @@ export default class ThemeSource extends FeatureSourceMerger {
mvtAvailableLayers: Set<string>,
fullNodeDatabaseSource?: FullNodeDatabaseSource
) {
const supportsForceDownload: UpdatableFeatureSource[] = []
const { bounds, zoom } = mapProperties
// remove all 'special' layers
layers = layers.filter((layer) => layer.source !== null && layer.source !== undefined)
@ -95,7 +91,6 @@ export default class ThemeSource extends FeatureSourceMerger {
)
overpassSource = ThemeSource.setupOverpass(osmLayers, bounds, zoom, featureSwitches)
nonMvtSources.push(overpassSource)
supportsForceDownload.push(overpassSource)
}
function setIsLoading() {
@ -110,7 +105,6 @@ export default class ThemeSource extends FeatureSourceMerger {
ThemeSource.setupGeojsonSource(l, mapProperties, isDisplayed(l.id))
)
const downloadAllBounds: UIEventSource<BBox> = new UIEventSource<BBox>(undefined)
const downloadAll = new OverpassFeatureSource(
{
layers: layers.filter((l) => l.isNormal()),
@ -123,6 +117,7 @@ export default class ThemeSource extends FeatureSourceMerger {
},
{
ignoreZoom: true,
isActive: new ImmutableStore(false)
}
)
@ -135,13 +130,8 @@ export default class ThemeSource extends FeatureSourceMerger {
)
this.isLoading = isLoading
supportsForceDownload.push(...geojsonSources)
supportsForceDownload.push(...mvtSources) // Non-mvt sources are handled by overpass
this._mapBounds = mapProperties.bounds
this._downloadAll = downloadAll
this.supportsForceDownload = supportsForceDownload
this._mapBounds = mapProperties.bounds
}
private static setupMvtSource(

View file

@ -1,20 +1,22 @@
import { BBox } from "./BBox"
import * as turf from "@turf/turf"
import { AllGeoJSON, booleanWithin, Coord, Lines } from "@turf/turf"
import { AllGeoJSON, booleanWithin, Coord } from "@turf/turf"
import {
Feature,
FeatureCollection,
GeoJSON,
Geometry,
LineString,
MultiLineString,
MultiPolygon,
Point,
Polygon,
Position,
Position
} from "geojson"
import { Tiles } from "../Models/TileRange"
import { Utils } from "../Utils"
import { NearestPointOnLine } from "@turf/nearest-point-on-line"
"use strict"
export class GeoOperations {
private static readonly _earthRadius = 6378137
@ -28,7 +30,7 @@ export class GeoOperations {
"behind",
"sharp_left",
"left",
"slight_left",
"slight_left"
] as const
private static reverseBearing = {
N: 0,
@ -46,21 +48,21 @@ export class GeoOperations {
W: 270,
WNW: 292.5,
NW: 315,
NNW: 337.5,
NNW: 337.5
}
/**
* Create a union between two features
*/
public static union(f0: Feature, f1: Feature): Feature<Polygon | MultiPolygon> | null {
return turf.union(<any>f0, <any>f1)
public static union(f0: Feature<Polygon | MultiPolygon>, f1: Feature<Polygon | MultiPolygon>): Feature<Polygon | MultiPolygon> | null {
return turf.union(f0, f1)
}
public static intersect(f0: Feature, f1: Feature): Feature<Polygon | MultiPolygon> | null {
return turf.intersect(<any>f0, <any>f1)
public static intersect(f0: Feature<Polygon | MultiPolygon>, f1: Feature<Polygon | MultiPolygon>): Feature<Polygon | MultiPolygon> | null {
return turf.intersect(f0, f1)
}
static surfaceAreaInSqMeters(feature: any) {
static surfaceAreaInSqMeters(feature: Feature<Polygon | MultiPolygon>): number {
return turf.area(feature)
}
@ -68,8 +70,8 @@ export class GeoOperations {
* Converts a GeoJson feature to a point GeoJson feature
* @param feature
*/
static centerpoint(feature: any): Feature<Point> {
const newFeature: Feature<Point> = turf.center(feature)
static centerpoint(feature: Feature): Feature<Point> {
const newFeature: Feature<Point> = turf.center(<turf.Feature>feature)
newFeature.properties = feature.properties
newFeature.id = feature.id
return newFeature
@ -83,12 +85,12 @@ export class GeoOperations {
*/
static centerpointCoordinates(feature: undefined | null): undefined ;
static centerpointCoordinates(feature: AllGeoJSON | GeoJSON | undefined): [number, number] | undefined;
static centerpointCoordinates(feature: NonNullable< AllGeoJSON> | NonNullable<GeoJSON>): NonNullable<[number, number]>;
static centerpointCoordinates(feature: NonNullable<AllGeoJSON> | NonNullable<GeoJSON>): NonNullable<[number, number]>;
static centerpointCoordinates(feature: AllGeoJSON | GeoJSON): [number, number] {
if(feature === undefined || feature === null){
if (feature === undefined || feature === null) {
return undefined
}
return <[number, number]>turf.center(<any>feature).geometry.coordinates
return <[number, number]>turf.center(<turf.Feature>feature).geometry.coordinates
}
/**
@ -140,11 +142,12 @@ export class GeoOperations {
* const overlap0 = GeoOperations.calculateOverlap(line0, [polygon]);
* overlap.length // => 1
*/
static calculateOverlap(feature: any, otherFeatures: any[]): { feat: any; overlap: number }[] {
static calculateOverlap(feature: Feature, otherFeatures: Feature[]):
{ feat: Feature; overlap: number }[] {
const featureBBox = BBox.get(feature)
const result: { feat: any; overlap: number }[] = []
const result: { feat: Feature; overlap: number }[] = []
if (feature.geometry.type === "Point") {
const coor = feature.geometry.coordinates
const coor = <[number,number]> feature.geometry.coordinates
for (const otherFeature of otherFeatures) {
if (
feature.properties.id !== undefined &&
@ -197,7 +200,7 @@ export class GeoOperations {
}
if (otherFeature.geometry.type === "Point") {
if (this.inside(otherFeature, feature)) {
if (this.inside(<Feature<Point>> otherFeature, feature)) {
result.push({ feat: otherFeature, overlap: undefined })
}
continue
@ -263,9 +266,8 @@ export class GeoOperations {
const y: number = pointCoordinate[1]
if (feature.geometry.type === "MultiPolygon") {
const coordinatess = feature.geometry.coordinates
const coordinatess: [number, number][][][] = <[number, number][][][]>feature.geometry.coordinates
for (const coordinates of coordinatess) {
// @ts-ignore
const inThisPolygon = GeoOperations.pointInPolygonCoordinates(x, y, coordinates)
if (inThisPolygon) {
return true
@ -275,24 +277,23 @@ export class GeoOperations {
}
if (feature.geometry.type === "Polygon") {
// @ts-ignore
return GeoOperations.pointInPolygonCoordinates(x, y, feature.geometry.coordinates)
return GeoOperations.pointInPolygonCoordinates(x, y, <[number, number][][]>feature.geometry.coordinates)
}
throw "GeoOperations.inside: unsupported geometry type " + feature.geometry.type
}
static lengthInMeters(feature: any) {
static lengthInMeters(feature: Feature): number {
return turf.length(feature) * 1000
}
static buffer(feature: any, bufferSizeInMeter: number) {
static buffer(feature: Feature, bufferSizeInMeter: number): Feature<Polygon | MultiPolygon> | FeatureCollection<Polygon | MultiPolygon> {
return turf.buffer(feature, bufferSizeInMeter / 1000, {
units: "kilometers",
units: "kilometers"
})
}
static bbox(feature: Feature | FeatureCollection): Feature<LineString, {}> {
static bbox(feature: Feature | FeatureCollection): Feature<LineString> {
const [lon, lat, lon0, lat0] = turf.bbox(feature)
return {
type: "Feature",
@ -304,9 +305,9 @@ export class GeoOperations {
[lon0, lat],
[lon0, lat0],
[lon, lat0],
[lon, lat],
],
},
[lon, lat]
]
}
}
}
@ -324,17 +325,8 @@ export class GeoOperations {
public static nearestPoint(
way: Feature<LineString>,
point: [number, number]
): Feature<
Point,
{
index: number
dist: number
location: number
}
> {
return <any>(
turf.nearestPointOnLine(<Feature<LineString>>way, point, { units: "kilometers" })
)
): NearestPointOnLine {
return turf.nearestPointOnLine(<Feature<LineString>>way, point, { units: "kilometers" })
}
/**
@ -352,18 +344,30 @@ export class GeoOperations {
way: Feature<LineString | MultiLineString | Polygon | MultiPolygon>
): Feature<LineString | MultiLineString> {
if (way.geometry.type === "Polygon") {
way = { ...way }
way.geometry = { ...way.geometry }
way.geometry.type = "LineString"
way.geometry.coordinates = (<Polygon>way.geometry).coordinates[0]
} else if (way.geometry.type === "MultiPolygon") {
way = { ...way }
way.geometry = { ...way.geometry }
way.geometry.type = "MultiLineString"
way.geometry.coordinates = (<MultiPolygon>way.geometry).coordinates[0]
return <Feature<LineString>>{
geometry: {
type: "LineString",
coordinates: way.geometry.coordinates[0]
},
properties: way.properties
}
}
return <any>way
if (way.geometry.type === "MultiPolygon") {
return <Feature<MultiLineString>>{
geometry: {
type: "MultiLineString",
coordinates: way.geometry.coordinates[0]
},
properties: way.properties
}
}
if (way.geometry.type === "LineString") {
return <Feature<LineString>> way
}
if (way.geometry.type === "MultiLineString") {
return <Feature<MultiLineString>> way
}
throw "Invalid geometry to create a way from this"
}
public static toCSV(
@ -402,9 +406,6 @@ export class GeoOperations {
for (const feature of _features) {
const properties = feature.properties
for (const key in properties) {
if (!properties.hasOwnProperty(key)) {
continue
}
addH(key)
}
}
@ -535,8 +536,8 @@ export class GeoOperations {
properties: {},
geometry: {
type: "Point",
coordinates: p,
},
coordinates: p
}
}
)
}
@ -552,7 +553,7 @@ export class GeoOperations {
trackPoints.push(trkpt)
}
const header =
'<gpx version="1.1" creator="mapcomplete.org" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">'
"<gpx version=\"1.1\" creator=\"mapcomplete.org\" xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">"
return (
header +
"\n<name>" +
@ -591,7 +592,7 @@ export class GeoOperations {
trackPoints.push(trkpt)
}
const header =
'<gpx version="1.1" creator="mapcomplete.org" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">'
"<gpx version=\"1.1\" creator=\"mapcomplete.org\" xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">"
return (
header +
"\n<name>" +
@ -610,21 +611,21 @@ export class GeoOperations {
* const copy = GeoOperations.removeOvernoding(feature)
* expect(copy.geometry.coordinates[0]).deep.equal([[4.477944199999975,51.02783550000022],[4.477987899999996,51.027818800000034],[4.478004500000021,51.02783399999988],[4.478025499999962,51.02782489999994],[4.478079099999993,51.027873899999896],[4.47801040000006,51.027903799999955],[4.477944199999975,51.02783550000022]])
*/
static removeOvernoding(feature: any) {
static removeOvernoding(feature: Feature<LineString | Polygon>) {
if (feature.geometry.type !== "LineString" && feature.geometry.type !== "Polygon") {
throw "Overnode removal is only supported on linestrings and polygons"
}
const copy = {
...feature,
geometry: { ...feature.geometry },
geometry: { ...feature.geometry }
}
let coordinates: [number, number][]
if (feature.geometry.type === "LineString") {
coordinates = [...feature.geometry.coordinates]
coordinates = <[number,number][]> [...feature.geometry.coordinates]
copy.geometry.coordinates = coordinates
} else {
coordinates = [...feature.geometry.coordinates[0]]
coordinates = <[number,number][]> [...feature.geometry.coordinates[0]]
copy.geometry.coordinates[0] = coordinates
}
@ -671,12 +672,12 @@ export class GeoOperations {
public static along(a: Coord, b: Coord, distanceMeter: number): Coord {
return turf.along(
<any>{
<Feature<LineString>>{
type: "Feature",
geometry: {
type: "LineString",
coordinates: [a, b],
},
coordinates: [a, b]
}
},
distanceMeter,
{ units: "meters" }
@ -713,8 +714,8 @@ export class GeoOperations {
* GeoOperations.completelyWithin(park, pond) // => false
*/
static completelyWithin(
feature: Feature<Geometry, any>,
possiblyEnclosingFeature: Feature<Polygon | MultiPolygon, any>
feature: Feature,
possiblyEnclosingFeature: Feature<Polygon | MultiPolygon>
): boolean {
return booleanWithin(feature, possiblyEnclosingFeature)
}
@ -882,8 +883,8 @@ export class GeoOperations {
properties: p.properties,
geometry: {
type: "LineString",
coordinates: p.geometry.coordinates[0],
},
coordinates: p.geometry.coordinates[0]
}
}
}
@ -911,7 +912,7 @@ export class GeoOperations {
console.debug("SPlitting way", feature.properties.id)
result.push({
...feature,
geometry: { ...feature.geometry, coordinates: coors.slice(i + 1) },
geometry: { ...feature.geometry, coordinates: coors.slice(i + 1) }
})
coors = coors.slice(0, i + 1)
break
@ -920,7 +921,7 @@ export class GeoOperations {
}
result.push({
...feature,
geometry: { ...feature.geometry, coordinates: coors },
geometry: { ...feature.geometry, coordinates: coors }
})
}
}
@ -1094,8 +1095,8 @@ export class GeoOperations {
properties: multiLineStringFeature.properties,
geometry: {
type: "LineString",
coordinates: coors[0],
},
coordinates: coors[0]
}
}
}
return {
@ -1103,8 +1104,8 @@ export class GeoOperations {
properties: multiLineStringFeature.properties,
geometry: {
type: "MultiLineString",
coordinates: coors,
},
coordinates: coors
}
}
}
@ -1177,7 +1178,7 @@ export class GeoOperations {
// Calculate the length of the intersection
let intersectionPoints = turf.lineIntersect(feature, otherFeature)
const intersectionPoints = turf.lineIntersect(feature, otherFeature)
if (intersectionPoints.features.length == 0) {
// No intersections.
// If one point is inside of the polygon, all points are
@ -1190,7 +1191,7 @@ export class GeoOperations {
return null
}
let intersectionPointsArray = intersectionPoints.features.map((d) => {
const intersectionPointsArray = intersectionPoints.features.map((d) => {
return d.geometry.coordinates
})
@ -1212,7 +1213,7 @@ export class GeoOperations {
}
}
let intersection = turf.lineSlice(
const intersection = turf.lineSlice(
turf.point(intersectionPointsArray[0]),
turf.point(intersectionPointsArray[1]),
feature

View file

@ -85,7 +85,7 @@ export class ImageUploadManager {
uploadFinished: this.getCounterFor(this._uploadFinished, featureId),
retried: this.getCounterFor(this._uploadRetried, featureId),
failed: this.getCounterFor(this._uploadFailed, featureId),
retrySuccess: this.getCounterFor(this._uploadRetriedSuccess, featureId),
retrySuccess: this.getCounterFor(this._uploadRetriedSuccess, featureId)
}
}
@ -94,7 +94,7 @@ export class ImageUploadManager {
if (sizeInBytes > this._uploader.maxFileSizeInMegabytes * 1000000) {
const error = Translations.t.image.toBig.Subs({
actual_size: Math.floor(sizeInBytes / 1000000) + "MB",
max_size: this._uploader.maxFileSizeInMegabytes + "MB",
max_size: this._uploader.maxFileSizeInMegabytes + "MB"
})
return { error }
}
@ -144,7 +144,7 @@ export class ImageUploadManager {
properties,
{
theme: tags?.data?.["_orig_theme"] ?? this._theme.id,
changeType: "add-image",
changeType: "add-image"
}
)
@ -168,15 +168,22 @@ export class ImageUploadManager {
if (this._gps.data && !ignoreGps) {
location = [this._gps.data.longitude, this._gps.data.latitude]
}
if (location === undefined || location?.some((l) => l === undefined)) {
{
feature ??= this._indexedFeatures.featuresById.data.get(featureId)
if(feature === undefined){
if (feature === undefined) {
throw "ImageUploadManager: no feature given and no feature found in the indexedFeature. Cannot upload this image"
}
location = GeoOperations.centerpointCoordinates(feature)
const featureCenterpoint = GeoOperations.centerpointCoordinates(feature)
if (location === undefined || location?.some((l) => l === undefined) ||
GeoOperations.distanceBetween(location, featureCenterpoint) > 150) {
/* GPS location is either unknown or very far away from the photographed location.
* Default to the centerpoint
*/
location = featureCenterpoint
}
}
try {
;({ key, value, absoluteUrl } = await this._uploader.uploadImage(
({ key, value, absoluteUrl } = await this._uploader.uploadImage(
blob,
location,
author,
@ -186,7 +193,7 @@ export class ImageUploadManager {
this.increaseCountFor(this._uploadRetried, featureId)
console.error("Could not upload image, trying again:", e)
try {
;({ key, value, absoluteUrl } = await this._uploader.uploadImage(
({ key, value, absoluteUrl } = await this._uploader.uploadImage(
blob,
location,
author,
@ -202,7 +209,7 @@ export class ImageUploadManager {
ctx: "While uploading an image in the Image Upload Manager",
featureId,
author,
targetKey,
targetKey
})
)
return undefined

View file

@ -12,7 +12,7 @@ import Panoramax_bw from "../../assets/svg/Panoramax_bw.svelte"
import Link from "../../UI/Base/Link"
export default class PanoramaxImageProvider extends ImageProvider {
public static readonly singleton = new PanoramaxImageProvider()
public static readonly singleton: PanoramaxImageProvider = new PanoramaxImageProvider()
private static readonly xyz = new PanoramaxXYZ()
private static defaultPanoramax = new AuthorizedPanoramax(
Constants.panoramax.url,
@ -126,7 +126,11 @@ export default class PanoramaxImageProvider extends ImageProvider {
if (!Panoramax.isId(value)) {
return undefined
}
return [await this.getInfoFor(value).then((r) => this.featureToImage(<any>r))]
return [await this.getInfo(value)]
}
public async getInfo(hash: string): Promise<ProvidedImage> {
return await this.getInfoFor(hash).then((r) => this.featureToImage(<any>r))
}
getRelevantUrls(tags: Record<string, string>, prefixes: string[]): Store<ProvidedImage[]> {
@ -230,8 +234,14 @@ export class PanoramaxUploader implements ImageUploader {
) {
lat = exifLat
lon = exifLon
if(tags?.GPSLatitudeRef?.value?.[0] === "S"){
lat *= -1
}
if(tags?.GPSLongitudeRef?.value?.[0] === "W"){
lon *= -1
}
}
const [date, time] = tags.DateTime.value[0].split(" ")
const [date, time] =( tags.DateTime.value[0] ?? tags.DateTimeOriginal.value[0] ?? tags.GPSDateStamp ?? tags["Date Created"]).split(" ")
const exifDatetime = new Date(date.replaceAll(":", "-") + "T" + time)
if (exifDatetime.getFullYear() === 1970) {
// The data probably got reset to the epoch

View file

@ -532,7 +532,7 @@ export class OsmConnection {
this.auth = new osmAuth({
client_id: this._oauth_config.oauth_client_id,
url: this._oauth_config.url,
scope: "read_prefs write_prefs write_api write_gpx write_notes openid",
scope: "read_prefs write_prefs write_api write_gpx write_notes",
redirect_uri: Utils.runningFromConsole
? "https://mapcomplete.org/land.html"
: window.location.protocol + "//" + window.location.host + "/land.html",

View file

@ -14,7 +14,7 @@ export default class OsmObjectDownloader {
readonly isUploading: Store<boolean>
}
private readonly backend: string
private historyCache = new Map<string, UIEventSource<OsmObject[]>>()
private historyCache = new Map<string, Promise<OsmObject[]>>()
constructor(
backend: string = "https://api.openstreetmap.org",
@ -75,49 +75,51 @@ export default class OsmObjectDownloader {
return await this.applyPendingChanges(obj)
}
public DownloadHistory(id: NodeId): UIEventSource<OsmNode[]>
public DownloadHistory(id: WayId): UIEventSource<OsmWay[]>
public DownloadHistory(id: RelationId): UIEventSource<OsmRelation[]>
public DownloadHistory(id: OsmId): UIEventSource<OsmObject[]>
public DownloadHistory(id: string): UIEventSource<OsmObject[]> {
if (this.historyCache.has(id)) {
return this.historyCache.get(id)
}
private async _downloadHistoryUncached(id: string): Promise<OsmObject[]> {
const splitted = id.split("/")
const type = splitted[0]
const idN = Number(splitted[1])
const src = new UIEventSource<OsmObject[]>([])
this.historyCache.set(id, src)
Utils.downloadJsonCached(
const data = await Utils.downloadJsonCached(
`${this.backend}api/0.6/${type}/${idN}/history`,
10 * 60 * 1000
).then((data) => {
const elements: any[] = data.elements
const osmObjects: OsmObject[] = []
for (const element of elements) {
let osmObject: OsmObject = null
element.nodes = []
switch (type) {
case "node":
osmObject = new OsmNode(idN, element)
break
case "way":
osmObject = new OsmWay(idN, element)
break
case "relation":
osmObject = new OsmRelation(idN, element)
break
}
osmObject?.SaveExtraData(element, [])
osmObjects.push(osmObject)
)
const elements: [] = data["elements"]
const osmObjects: OsmObject[] = []
for (const element of elements) {
let osmObject: OsmObject = null
element["nodes"] = []
switch (type) {
case "node":
osmObject = new OsmNode(idN, element)
break
case "way":
osmObject = new OsmWay(idN, element)
break
case "relation":
osmObject = new OsmRelation(idN, element)
break
}
src.setData(osmObjects)
})
return src
osmObject?.SaveExtraData(element, [])
osmObjects.push(osmObject)
}
return osmObjects
}
public downloadHistory(id: NodeId): Promise<OsmNode[]>
public downloadHistory(id: WayId): Promise<OsmWay[]>
public downloadHistory(id: RelationId): Promise<OsmRelation[]>
public downloadHistory(id: OsmId): Promise<OsmObject[]>
public async downloadHistory(id: string): Promise<OsmObject[]> {
if (this.historyCache.has(id)) {
return this.historyCache.get(id)
}
const promise = this._downloadHistoryUncached(id)
this.historyCache.set(id, promise)
return promise
}
/**

View file

@ -26,7 +26,10 @@ export class Overpass {
) {
this._timeout = timeout ?? new ImmutableStore<number>(90)
this._interpreterUrl = interpreterUrl
const optimized = filter.optimize()
if (filter === undefined && !extraScripts) {
throw "Filter is undefined. This is probably a bug. Alternatively, pass an 'extraScript'"
}
const optimized = filter?.optimize()
if (optimized === true || optimized === false) {
throw "Invalid filter: optimizes to true of false"
}
@ -85,7 +88,7 @@ export class Overpass {
* new Overpass(new Tag("key","value"), [], "").buildScript("{{bbox}}") // => `[out:json][timeout:90]{{bbox}};(nwr["key"="value"];);out body;out meta;>;out skel qt;`
*/
public buildScript(bbox: string, postCall: string = "", pretty = false): string {
const filters = this._filter.asOverpass()
const filters = this._filter?.asOverpass() ?? []
let filter = ""
for (const filterOr of filters) {
if (pretty) {
@ -97,12 +100,13 @@ export class Overpass {
}
}
for (const extraScript of this._extraScripts) {
filter += "(" + extraScript + ");"
filter += extraScript
}
return `[out:json][timeout:${this._timeout.data}]${bbox};(${filter});out body;${
this._includeMeta ? "out meta;" : ""
}>;out skel qt;`
}
/**
* Constructs the actual script to execute on Overpass with geocoding
* 'PostCall' can be used to set an extra range, see 'AsOverpassTurboLink'

View file

@ -1,10 +1,5 @@
import { Store, Stores, UIEventSource } from "../UIEventSource"
import GeocodingProvider, {
GeocodeResult,
GeocodingOptions,
ReverseGeocodingProvider,
ReverseGeocodingResult,
} from "./GeocodingProvider"
import { Store, Stores } from "../UIEventSource"
import GeocodingProvider, { GeocodeResult, GeocodingOptions } from "./GeocodingProvider"
import { decode as pluscode_decode } from "pluscodes"
export default class OpenLocationCodeSearch implements GeocodingProvider {

View file

@ -1,42 +1,14 @@
import { Utils } from "../../Utils"
/** This code is autogenerated - do not edit. Edit ./assets/layers/usersettings/usersettings.json instead */
export class ThemeMetaTagging {
public static readonly themeName = "usersettings"
public static readonly themeName = "usersettings"
public metaTaggging_for_usersettings(feat: { properties: Record<string, string> }) {
Utils.AddLazyProperty(feat.properties, "_mastodon_candidate_md", () =>
feat.properties._description
.match(/\[[^\]]*\]\((.*(mastodon|en.osm.town).*)\).*/)
?.at(1)
)
Utils.AddLazyProperty(
feat.properties,
"_d",
() => feat.properties._description?.replace(/&lt;/g, "<")?.replace(/&gt;/g, ">") ?? ""
)
Utils.AddLazyProperty(feat.properties, "_mastodon_candidate_a", () =>
((feat) => {
const e = document.createElement("div")
e.innerHTML = feat.properties._d
return Array.from(e.getElementsByTagName("a")).filter(
(a) => a.href.match(/mastodon|en.osm.town/) !== null
)[0]?.href
})(feat)
)
Utils.AddLazyProperty(feat.properties, "_mastodon_link", () =>
((feat) => {
const e = document.createElement("div")
e.innerHTML = feat.properties._d
return Array.from(e.getElementsByTagName("a")).filter(
(a) => a.getAttribute("rel")?.indexOf("me") >= 0
)[0]?.href
})(feat)
)
Utils.AddLazyProperty(
feat.properties,
"_mastodon_candidate",
() => feat.properties._mastodon_candidate_md ?? feat.properties._mastodon_candidate_a
)
feat.properties["__current_backgroun"] = "initial_value"
}
}
public metaTaggging_for_usersettings(feat: {properties: Record<string, string>}) {
Utils.AddLazyProperty(feat.properties, '_mastodon_candidate_md', () => feat.properties._description.match(/\[[^\]]*\]\((.*(mastodon|en.osm.town).*)\).*/)?.at(1) )
Utils.AddLazyProperty(feat.properties, '_d', () => feat.properties._description?.replace(/&lt;/g,'<')?.replace(/&gt;/g,'>') ?? '' )
Utils.AddLazyProperty(feat.properties, '_mastodon_candidate_a', () => (feat => {const e = document.createElement('div');e.innerHTML = feat.properties._d;return Array.from(e.getElementsByTagName("a")).filter(a => a.href.match(/mastodon|en.osm.town/) !== null)[0]?.href }) (feat) )
Utils.AddLazyProperty(feat.properties, '_mastodon_link', () => (feat => {const e = document.createElement('div');e.innerHTML = feat.properties._d;return Array.from(e.getElementsByTagName("a")).filter(a => a.getAttribute("rel")?.indexOf('me') >= 0)[0]?.href})(feat) )
Utils.AddLazyProperty(feat.properties, '_mastodon_candidate', () => feat.properties._mastodon_candidate_md ?? feat.properties._mastodon_candidate_a )
feat.properties['__current_backgroun'] = 'initial_value'
}
}

View file

@ -1,6 +1,5 @@
import { Utils } from "../Utils"
import { Readable, Subscriber, Unsubscriber, Updater, Writable } from "svelte/store"
/**
* Various static utils
*/
@ -727,6 +726,7 @@ export class UIEventSource<T> extends Store<T> implements Writable<T> {
}
/**
* Parse the number and round to the nearest int
*
* @param source
* UIEventSource.asInt(new UIEventSource("123")).data // => 123
@ -951,15 +951,14 @@ export class UIEventSource<T> extends Store<T> implements Writable<T> {
g: (j: J, t: T) => T,
allowUnregister = false
): UIEventSource<J> {
const self = this
const stack = new Error().stack.split("\n")
const callee = stack[1]
const newSource = new UIEventSource<J>(f(this.data), "map(" + this.tag + ")@" + callee)
const update = function () {
newSource.setData(f(self.data))
const update =() => {
newSource.setData(f(this.data))
return allowUnregister && newSource._callbacks.length() === 0
}
@ -970,7 +969,7 @@ export class UIEventSource<T> extends Store<T> implements Writable<T> {
if (g !== undefined) {
newSource.addCallback((latest) => {
self.setData(g(latest, self.data))
this.setData(g(latest, this.data))
})
}
@ -979,8 +978,7 @@ export class UIEventSource<T> extends Store<T> implements Writable<T> {
public syncWith(otherSource: UIEventSource<T>, reverseOverride = false): UIEventSource<T> {
this.addCallback((latest) => otherSource.setData(latest))
const self = this
otherSource.addCallback((latest) => self.setData(latest))
otherSource.addCallback((latest) => this.setData(latest))
if (reverseOverride) {
if (otherSource.data !== undefined) {
this.setData(otherSource.data)