mapcomplete/Logic/Osm/Overpass.ts

70 lines
2.6 KiB
TypeScript
Raw Normal View History

2020-07-30 00:59:08 +02:00
import * as OsmToGeoJson from "osmtogeojson";
2021-01-03 00:19:42 +01:00
import Bounds from "../../Models/Bounds";
2021-04-18 14:24:30 +02:00
import {TagsFilter} from "../Tags/TagsFilter";
import ExtractRelations from "./ExtractRelations";
2021-07-03 22:24:12 +02:00
import {Utils} from "../../Utils";
import {UIEventSource} from "../UIEventSource";
2020-07-30 00:59:08 +02:00
/**
* Interfaces overpass to get all the latest data
*/
2020-06-24 00:35:19 +02:00
export class Overpass {
public static testUrl: string = null
private _filter: TagsFilter
private readonly _interpreterUrl: UIEventSource<string>;
private readonly _timeout: UIEventSource<number>;
private readonly _extraScripts: string[];
private _includeMeta: boolean;
constructor(filter: TagsFilter, extraScripts: string[],
interpreterUrl: UIEventSource<string>,
timeout: UIEventSource<number>,
includeMeta = true) {
this._timeout = timeout;
this._interpreterUrl = interpreterUrl;
this._filter = filter
this._extraScripts = extraScripts;
this._includeMeta = includeMeta;
2020-06-24 00:35:19 +02:00
}
2021-01-03 00:19:42 +01:00
queryGeoJson(bounds: Bounds, continuation: ((any, date: Date) => void), onFail: ((reason) => void)): void {
2020-07-20 20:15:21 +02:00
2020-10-12 01:25:27 +02:00
let query = this.buildQuery("[bbox:" + bounds.south + "," + bounds.west + "," + bounds.north + "," + bounds.east + "]")
if (Overpass.testUrl !== null) {
2020-06-24 00:35:19 +02:00
console.log("Using testing URL")
query = Overpass.testUrl;
}
2021-07-03 22:24:12 +02:00
Utils.downloadJson(query)
.then(json => {
2021-08-24 10:48:44 +02:00
if (json.elements === [] && ((json.remarks ?? json.remark).indexOf("runtime error") >= 0)) {
2020-07-01 21:21:29 +02:00
console.log("Timeout or other runtime error");
onFail("Runtime error (timeout)")
2020-07-01 21:21:29 +02:00
return;
}
2021-04-18 14:24:30 +02:00
ExtractRelations.RegisterRelations(json)
2020-06-24 00:35:19 +02:00
// @ts-ignore
const geojson = OsmToGeoJson.default(json);
2021-01-03 00:19:42 +01:00
const osmTime = new Date(json.osm3s.timestamp_osm_base);
2021-01-03 00:19:42 +01:00
continuation(geojson, osmTime);
2021-07-03 22:24:12 +02:00
}).catch(onFail)
2020-06-24 00:35:19 +02:00
}
buildQuery(bbox: string): string {
const filters = this._filter.asOverpass()
let filter = ""
for (const filterOr of filters) {
filter += 'nwr' + filterOr + ';'
}
for (const extraScript of this._extraScripts) {
filter += '(' + extraScript + ');';
}
const query =
`[out:json][timeout:${this._timeout.data}]${bbox};(${filter});out body;${this._includeMeta ? 'out meta;' : ''}>;out skel qt;`
return `${this._interpreterUrl.data}?data=${encodeURIComponent(query)}`
}
}