Full code cleanup

This commit is contained in:
pietervdvn 2021-11-07 16:34:51 +01:00
parent 8e6ee8c87f
commit bd21212eba
246 changed files with 19418 additions and 11729 deletions

View file

@ -37,34 +37,34 @@ jobs:
# Learn more about CodeQL language support at https://git.io/codeql-language-support # Learn more about CodeQL language support at https://git.io/codeql-language-support
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v2 uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v1 uses: github/codeql-action/init@v1
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file. # If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file. # By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file. # Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main # queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below) # If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild - name: Autobuild
uses: github/codeql-action/autobuild@v1 uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell. # Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl # 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project # and modify them (or add more) to build your code if your project
# uses a compiled language # uses a compiled language
#- run: | #- run: |
# make bootstrap # make bootstrap
# make release # make release
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1 uses: github/codeql-action/analyze@v1

View file

@ -9,16 +9,16 @@ export class AllKnownLayouts {
public static allKnownLayouts: Map<string, LayoutConfig> = AllKnownLayouts.AllLayouts(); public static allKnownLayouts: Map<string, LayoutConfig> = AllKnownLayouts.AllLayouts();
public static layoutsList: LayoutConfig[] = AllKnownLayouts.GenerateOrderedList(AllKnownLayouts.allKnownLayouts); public static layoutsList: LayoutConfig[] = AllKnownLayouts.GenerateOrderedList(AllKnownLayouts.allKnownLayouts);
public static AllPublicLayers(){ public static AllPublicLayers() {
const allLayers : LayerConfig[] = [] const allLayers: LayerConfig[] = []
const seendIds = new Set<string>() const seendIds = new Set<string>()
const publicLayouts = AllKnownLayouts.layoutsList.filter(l => !l.hideFromOverview) const publicLayouts = AllKnownLayouts.layoutsList.filter(l => !l.hideFromOverview)
for (const layout of publicLayouts) { for (const layout of publicLayouts) {
if(layout.hideFromOverview){ if (layout.hideFromOverview) {
continue continue
} }
for (const layer of layout.layers) { for (const layer of layout.layers) {
if(seendIds.has(layer.id)){ if (seendIds.has(layer.id)) {
continue continue
} }
seendIds.add(layer.id) seendIds.add(layer.id)

View file

@ -15,7 +15,7 @@ export default class SharedTagRenderings {
const d = new Map<string, TagRenderingConfig>() const d = new Map<string, TagRenderingConfig>()
for (const key of Array.from(configJsons.keys())) { for (const key of Array.from(configJsons.keys())) {
try { try {
d.set(key, new TagRenderingConfig(configJsons.get(key), `SharedTagRenderings.${key}`)) d.set(key, new TagRenderingConfig(configJsons.get(key), `SharedTagRenderings.${key}`))
} catch (e) { } catch (e) {
if (!Utils.runningFromConsole) { if (!Utils.runningFromConsole) {
console.error("BUG: could not parse", key, " from questions.json or icons.json - this error happened during the build step of the SharedTagRenderings", e) console.error("BUG: could not parse", key, " from questions.json or icons.json - this error happened during the build step of the SharedTagRenderings", e)

View file

@ -1,144 +1,103 @@
Metatags
Metatags
========== ==========
Metatags are extra tags available, in order to display more data or to give better questions. Metatags are extra tags available, in order to display more data or to give better questions.
The are calculated automatically on every feature when the data arrives in the webbrowser. This document gives an overview of the available metatags. The are calculated automatically on every feature when the data arrives in the webbrowser. This document gives an
overview of the available metatags.
**Hint:** when using metatags, add the [query parameter](URL_Parameters.md) `debug=true` to the URL. This will include a box in the popup for features which shows all the properties of the object **Hint:** when using metatags, add the [query parameter](URL_Parameters.md) `debug=true` to the URL. This will include a
box in the popup for features which shows all the properties of the object
Metatags calculated by MapComplete Metatags calculated by MapComplete
------------------------------------ ------------------------------------
The following values are always calculated, by default, by MapComplete and are available automatically on all elements in every theme The following values are always calculated, by default, by MapComplete and are available automatically on all elements
in every theme
### _lat, _lon ### _lat, _lon
The latitude and longitude of the point (or centerpoint in the case of a way/area) The latitude and longitude of the point (or centerpoint in the case of a way/area)
### _layer ### _layer
The layer-id to which this feature belongs. Note that this might be return any applicable if `passAllFeatures` is
defined.
The layer-id to which this feature belongs. Note that this might be return any applicable if `passAllFeatures` is defined.
### _surface, _surface:ha ### _surface, _surface:ha
The surface area of the feature, in square meters and in hectare. Not set on points and ways The surface area of the feature, in square meters and in hectare. Not set on points and ways
This is a lazy metatag and is only calculated when needed This is a lazy metatag and is only calculated when needed
### _length, _length:km ### _length, _length:km
The total length of a feature in meters (and in kilometers, rounded to one decimal for '_length:km'). For a surface, the
length of the perimeter
The total length of a feature in meters (and in kilometers, rounded to one decimal for '_length:km'). For a surface, the length of the perimeter
### Theme-defined keys ### Theme-defined keys
If 'units' is defined in the layoutConfig, then this metatagger will rewrite the specified keys to have the canonical
form (e.g. `1meter` will be rewritten to `1m`)
If 'units' is defined in the layoutConfig, then this metatagger will rewrite the specified keys to have the canonical form (e.g. `1meter` will be rewritten to `1m`)
### _country ### _country
The country code of the property (with latlon2country) The country code of the property (with latlon2country)
### _isOpen, _isOpen:description ### _isOpen, _isOpen:description
If 'opening_hours' is present, it will add the current state of the feature (being 'yes' or 'no') If 'opening_hours' is present, it will add the current state of the feature (being 'yes' or 'no')
This is a lazy metatag and is only calculated when needed This is a lazy metatag and is only calculated when needed
### _direction:numerical, _direction:leftright ### _direction:numerical, _direction:leftright
_direction:numerical is a normalized, numerical direction based on 'camera:direction' or on 'direction'; it is only
present if a valid direction is found (e.g. 38.5 or NE). _direction:leftright is either 'left' or 'right', which is
_direction:numerical is a normalized, numerical direction based on 'camera:direction' or on 'direction'; it is only present if a valid direction is found (e.g. 38.5 or NE). _direction:leftright is either 'left' or 'right', which is left-looking on the map or 'right-looking' on the map left-looking on the map or 'right-looking' on the map
### _now:date, _now:datetime, _loaded:date, _loaded:_datetime ### _now:date, _now:datetime, _loaded:date, _loaded:_datetime
Adds the time that the data got loaded - pretty much the time of downloading from overpass. The format is YYYY-MM-DD hh:
mm, aka 'sortable' aka ISO-8601-but-not-entirely
Adds the time that the data got loaded - pretty much the time of downloading from overpass. The format is YYYY-MM-DD hh:mm, aka 'sortable' aka ISO-8601-but-not-entirely
### _last_edit:contributor, _last_edit:contributor:uid, _last_edit:changeset, _last_edit:timestamp, _version_number, _backend ### _last_edit:contributor, _last_edit:contributor:uid, _last_edit:changeset, _last_edit:timestamp, _version_number, _backend
Information about the last edit of this object. Information about the last edit of this object.
### sidewalk:left, sidewalk:right, generic_key:left:property, generic_key:right:property ### sidewalk:left, sidewalk:right, generic_key:left:property, generic_key:right:property
Rewrites tags from 'generic_key:both:property' as 'generic_key:left:property' and 'generic_key:right:property' (and
similar for sidewalk tagging). Note that this rewritten tags _will be reuploaded on a change_. To prevent to much
Rewrites tags from 'generic_key:both:property' as 'generic_key:left:property' and 'generic_key:right:property' (and similar for sidewalk tagging). Note that this rewritten tags _will be reuploaded on a change_. To prevent to much unrelated retagging, this is only enabled if the layer has at least some lineRenderings with offset defined unrelated retagging, this is only enabled if the layer has at least some lineRenderings with offset defined
Calculating tags with Javascript Calculating tags with Javascript
---------------------------------- ----------------------------------
In some cases, it is useful to have some tags calculated based on other properties. Some useful tags are available by default (e.g. `lat`, `lon`, `_country`), as detailed above. In some cases, it is useful to have some tags calculated based on other properties. Some useful tags are available by
default (e.g. `lat`, `lon`, `_country`), as detailed above.
It is also possible to calculate your own tags - but this requires some javascript knowledge. It is also possible to calculate your own tags - but this requires some javascript knowledge.
Before proceeding, some warnings: Before proceeding, some warnings:
- DO NOT DO THIS AS BEGINNER
- **Only do this if all other techniques fail** This should _not_ be done to create a rendering effect, only to
calculate a specific value
- **THIS MIGHT BE DISABLED WITHOUT ANY NOTICE ON UNOFFICIAL THEMES** As unofficial themes might be loaded from the
internet, this is the equivalent of injecting arbitrary code into the client. It'll be disabled if abuse occurs.
To enable this feature, add a field `calculatedTags` in the layer object, e.g.:
- DO NOT DO THIS AS BEGINNER
- **Only do this if all other techniques fail** This should _not_ be done to create a rendering effect, only to calculate a specific value
- **THIS MIGHT BE DISABLED WITHOUT ANY NOTICE ON UNOFFICIAL THEMES** As unofficial themes might be loaded from the internet, this is the equivalent of injecting arbitrary code into the client. It'll be disabled if abuse occurs.
To enable this feature, add a field `calculatedTags` in the layer object, e.g.:
```` ````
@ -154,71 +113,75 @@ To enable this feature, add a field `calculatedTags` in the layer object, e.g.:
```` ````
The above code will be executed for every feature in the layer. The feature is accessible as `feat` and is an amended
geojson object:
- `area` contains the surface area (in square meters) of the object
The above code will be executed for every feature in the layer. The feature is accessible as `feat` and is an amended geojson object: - `lat` and `lon` contain the latitude and longitude
- `area` contains the surface area (in square meters) of the object
- `lat` and `lon` contain the latitude and longitude
Some advanced functions are available on **feat** as well: Some advanced functions are available on **feat** as well:
- [distanceTo](#distanceTo) - [distanceTo](#distanceTo)
- [overlapWith](#overlapWith) - [overlapWith](#overlapWith)
- [closest](#closest) - [closest](#closest)
- [closestn](#closestn) - [closestn](#closestn)
- [memberships](#memberships) - [memberships](#memberships)
- [get](#get) - [get](#get)
### distanceTo ### distanceTo
Calculates the distance between the feature and a specified point in kilometer. The input should either be a pair of coordinates, a geojson feature or the ID of an object Calculates the distance between the feature and a specified point in kilometer. The input should either be a pair of
coordinates, a geojson feature or the ID of an object
0. feature OR featureID OR longitude 0. feature OR featureID OR longitude
1. undefined OR latitude 1. undefined OR latitude
### overlapWith ### overlapWith
Gives a list of features from the specified layer which this feature (partly) overlaps with. A point which is embedded in the feature is detected as well.If the current feature is a point, all features that this point is embeded in are given. Gives a list of features from the specified layer which this feature (partly) overlaps with. A point which is embedded
in the feature is detected as well.If the current feature is a point, all features that this point is embeded in are
given.
The returned value is `{ feat: GeoJSONFeature, overlap: number}[]` where `overlap` is the overlapping surface are (in m²) for areas, the overlapping length (in meter) if the current feature is a line or `undefined` if the current feature is a point. The returned value is `{ feat: GeoJSONFeature, overlap: number}[]` where `overlap` is the overlapping surface are (in
The resulting list is sorted in descending order by overlap. The feature with the most overlap will thus be the first in the list m²) for areas, the overlapping length (in meter) if the current feature is a line or `undefined` if the current feature
is a point. The resulting list is sorted in descending order by overlap. The feature with the most overlap will thus be
the first in the list
For example to get all objects which overlap or embed from a layer, use `_contained_climbing_routes_properties=feat.overlapWith('climbing_route')` For example to get all objects which overlap or embed from a layer,
use `_contained_climbing_routes_properties=feat.overlapWith('climbing_route')`
0. ...layerIds - one or more layer ids of the layer from which every feature is checked for overlap) 0. ...layerIds - one or more layer ids of the layer from which every feature is checked for overlap)
### closest ### closest
Given either a list of geojson features or a single layer name, gives the single object which is nearest to the feature. In the case of ways/polygons, only the centerpoint is considered. Returns a single geojson feature or undefined if nothing is found (or not yet laoded) Given either a list of geojson features or a single layer name, gives the single object which is nearest to the feature.
In the case of ways/polygons, only the centerpoint is considered. Returns a single geojson feature or undefined if
nothing is found (or not yet laoded)
0. list of features or a layer name or '*' to get all features 0. list of features or a layer name or '*' to get all features
### closestn ### closestn
Given either a list of geojson features or a single layer name, gives the n closest objects which are nearest to the feature (excluding the feature itself). In the case of ways/polygons, only the centerpoint is considered. Returns a list of `{feat: geojson, distance:number}` the empty list if nothing is found (or not yet loaded) Given either a list of geojson features or a single layer name, gives the n closest objects which are nearest to the
feature (excluding the feature itself). In the case of ways/polygons, only the centerpoint is considered. Returns a list
of `{feat: geojson, distance:number}` the empty list if nothing is found (or not yet loaded)
If a 'unique tag key' is given, the tag with this key will only appear once (e.g. if 'name' is given, all features will have a different name) If a 'unique tag key' is given, the tag with this key will only appear once (e.g. if 'name' is given, all features will
have a different name)
0. list of features or layer name or '*' to get all features 0. list of features or layer name or '*' to get all features
1. amount of features 1. amount of features
2. unique tag key (optional) 2. unique tag key (optional)
3. maxDistanceInMeters (optional) 3. maxDistanceInMeters (optional)
### memberships ### memberships
Gives a list of `{role: string, relation: Relation}`-objects, containing all the relations that this feature is part of. Gives a list of `{role: string, relation: Relation}`-objects, containing all the relations that this feature is part of.
For example: `_part_of_walking_routes=feat.memberships().map(r => r.relation.tags.name).join(';')` For example: `_part_of_walking_routes=feat.memberships().map(r => r.relation.tags.name).join(';')`
### get ### get
Gets the property of the feature, parses it (as JSON) and returns it. Might return 'undefined' if not defined, null, ... Gets the property of the feature, parses it (as JSON) and returns it. Might return 'undefined' if not defined, null, ...
0. key 0. key Generated from SimpleMetaTagger, ExtraFunction
Generated from SimpleMetaTagger, ExtraFunction

View file

@ -1,32 +1,42 @@
Rights of contributors
Rights of contributors ======================
======================
If a contributor is quite active within MapComplete, this contributor might be granted access to the main repository. If a contributor is quite active within MapComplete, this contributor might be granted access to the main repository.
If you have access to the repository, you can make a fork of an already existing branch and push this new branch to github. If you have access to the repository, you can make a fork of an already existing branch and push this new branch to
This means that this branch will be _automatically built_ and be **deployed** to `https://pietervdvn.github.io/mc/<branchname>`. You can see the deploy process on [Github Actions](https://github.com/pietervdvn/MapComplete/actions). github. This means that this branch will be _automatically built_ and be **deployed**
Don't worry about pushing too much. These deploys are free and totally automatic. They might fail if something is wrong, but this will hinder no-one. to `https://pietervdvn.github.io/mc/<branchname>`. You can see the deploy process
on [Github Actions](https://github.com/pietervdvn/MapComplete/actions). Don't worry about pushing too much. These
deploys are free and totally automatic. They might fail if something is wrong, but this will hinder no-one.
Additionaly, some other maintainer might step in and merge the latest develop with your branch, making later pull requests easier. Additionaly, some other maintainer might step in and merge the latest develop with your branch, making later pull
requests easier.
Don't worry about bugs Don't worry about bugs
---------------------- ----------------------
As a non-admin contributor, you can _not_ make changes to the `master` nor to the `develop` branch. This is because, as soon as master is changed, this is built and deployed on `mapcomplete.osm.be`, which a lot of people use. An error there will cause a lot of grieve. As a non-admin contributor, you can _not_ make changes to the `master` nor to the `develop` branch. This is because, as
soon as master is changed, this is built and deployed on `mapcomplete.osm.be`, which a lot of people use. An error there
will cause a lot of grieve.
A push on `develop` is automatically deployed to [pietervdvn.github.io/mc/develop] and is used by quite some people to. People using this version should know that this is a testing ground for new features and might contain a bug every now and then. A push on `develop` is automatically deployed to [pietervdvn.github.io/mc/develop] and is used by quite some people to.
People using this version should know that this is a testing ground for new features and might contain a bug every now
and then.
In other words, to get your theme deployed on the main instances, you'll still have to create a pull request. The maintainers will then doublecheck and pull it in. In other words, to get your theme deployed on the main instances, you'll still have to create a pull request. The
maintainers will then doublecheck and pull it in.
If you have a local repository If you have a local repository
------------------------------ ------------------------------
If you have made a fork earlier and have received contributor rights, you need to tell your local git repository that pushing to the main repository is possible. If you have made a fork earlier and have received contributor rights, you need to tell your local git repository that
pushing to the main repository is possible.
To do this: To do this:
1. type `git remote add upstream git@github.com:pietervdvn/MapComplete` 1. type `git remote add upstream git@github.com:pietervdvn/MapComplete`
2. Run `git push upstream` to push your latest changes to the main repo (and not your fork). Running `git push` will push to your fork. 2. Run `git push upstream` to push your latest changes to the main repo (and not your fork). Running `git push` will
push to your fork.
Alternatively, if you don't have any unmerged changes, you can remove your local copy and clone `pietervdvn/MapComplete` again to start fresh. Alternatively, if you don't have any unmerged changes, you can remove your local copy and clone `pietervdvn/MapComplete`
again to start fresh.

View file

@ -28,14 +28,15 @@ To develop and build MapComplete, you
0. Make a fork and clone the repository. 0. Make a fork and clone the repository.
0. Install the nodejs version specified in [.tool-versions](./.tool-versions) 0. Install the nodejs version specified in [.tool-versions](./.tool-versions)
- On linux: install npm first `sudo apt install npm`, then install `n` using npm: ` npm install -g n`, which can then install node with `n install <node-version>` - On linux: install npm first `sudo apt install npm`, then install `n` using npm: ` npm install -g n`, which can
- You can [use asdf to manage your runtime versions](https://asdf-vm.com/). then install node with `n install <node-version>`
- You can [use asdf to manage your runtime versions](https://asdf-vm.com/).
0. Install `npm`. Linux: `sudo apt install npm` (or your favourite package manager), Windows: install 0. Install `npm`. Linux: `sudo apt install npm` (or your favourite package manager), Windows: install
nodeJS: https://nodejs.org/en/download/ nodeJS: https://nodejs.org/en/download/
0. On iOS, install `wget` (`brew install wget`) 0. On iOS, install `wget` (`brew install wget`)
0. Run `npm run init` which … 0. Run `npm run init` which …
- runs `npm install` - runs `npm install`
- generates some additional dependencies and files - generates some additional dependencies and files
0. Run `npm run start` to host a local testversion at http://localhost:1234/index.html 0. Run `npm run start` to host a local testversion at http://localhost:1234/index.html
0. By default, a landing page with available themes is served. In order to load a single theme, use `layout=themename` 0. By default, a landing page with available themes is served. In order to load a single theme, use `layout=themename`
or `userlayout=true#<layout configuration>` as [Query parameter](URL_Parameters.md). Note that the shorter URLs ( or `userlayout=true#<layout configuration>` as [Query parameter](URL_Parameters.md). Note that the shorter URLs (
@ -106,7 +107,8 @@ Try removing `node_modules`, `package-lock.json` and `.cache`
Misc setup Misc setup
---------- ----------
The json-git-merger is used to quickly merge translation files, [documentation here](https://github.com/jonatanpedersen/git-json-merge#single-project--directory) The json-git-merger is used to quickly merge translation
files, [documentation here](https://github.com/jonatanpedersen/git-json-merge#single-project--directory)
Overview of package.json-scripts Overview of package.json-scripts
-------------------------------- --------------------------------

View file

@ -1,145 +1,181 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.43.0 (0) <!-- Generated by graphviz version 2.43.0 (0)
--> -->
<!-- Title: G Pages: 1 --> <!-- Title: G Pages: 1 -->
<svg width="664pt" height="566pt" <svg width="664pt" height="566pt"
viewBox="0.00 0.00 664.25 566.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> viewBox="0.00 0.00 664.25 566.00" xmlns="http://www.w3.org/2000/svg">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 562)"> <g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 562)">
<title>G</title> <title>G</title>
<polygon fill="white" stroke="transparent" points="-4,4 -4,-562 660.25,-562 660.25,4 -4,4"/> <polygon fill="white" stroke="transparent" points="-4,4 -4,-562 660.25,-562 660.25,4 -4,4"/>
<!-- init --> <!-- init -->
<g id="node1" class="node"> <g id="node1" class="node">
<title>init</title> <title>init</title>
<polygon fill="none" stroke="black" points="242.25,-558 188.25,-558 188.25,-522 242.25,-522 242.25,-558"/> <polygon fill="none" stroke="black" points="242.25,-558 188.25,-558 188.25,-522 242.25,-522 242.25,-558"/>
<text text-anchor="middle" x="215.25" y="-536.3" font-family="Times,serif" font-size="14.00">init</text> <text text-anchor="middle" x="215.25" y="-536.3" font-family="Times,serif" font-size="14.00">init</text>
</g> </g>
<!-- denied --> <!-- denied -->
<g id="node2" class="node"> <g id="node2" class="node">
<title>denied</title> <title>denied</title>
<ellipse fill="none" stroke="black" cx="42.25" cy="-279" rx="42.49" ry="18"/> <ellipse fill="none" stroke="black" cx="42.25" cy="-279" rx="42.49" ry="18"/>
<text text-anchor="middle" x="42.25" y="-275.3" font-family="Times,serif" font-size="14.00">denied</text> <text text-anchor="middle" x="42.25" y="-275.3" font-family="Times,serif" font-size="14.00">denied</text>
</g> </g>
<!-- init&#45;&gt;denied --> <!-- init&#45;&gt;denied -->
<g id="edge1" class="edge"> <g id="edge1" class="edge">
<title>init&#45;&gt;denied</title> <title>init&#45;&gt;denied</title>
<path fill="none" stroke="black" d="M188.23,-531.67C143.21,-517.82 54.16,-483.1 17.25,-417 -2.35,-381.91 14.04,-334.64 27.95,-305.79"/> <path fill="none" stroke="black"
<polygon fill="black" stroke="black" points="31.12,-307.26 32.51,-296.76 24.88,-304.1 31.12,-307.26"/> d="M188.23,-531.67C143.21,-517.82 54.16,-483.1 17.25,-417 -2.35,-381.91 14.04,-334.64 27.95,-305.79"/>
<text text-anchor="middle" x="132.25" y="-405.8" font-family="Times,serif" font-size="14.00">geolocation permanently denied</text> <polygon fill="black" stroke="black" points="31.12,-307.26 32.51,-296.76 24.88,-304.1 31.12,-307.26"/>
</g> <text text-anchor="middle" x="132.25" y="-405.8" font-family="Times,serif" font-size="14.00">geolocation
<!-- getting_location --> permanently denied
<g id="node3" class="node"> </text>
<title>getting_location</title> </g>
<ellipse fill="none" stroke="black" cx="366.25" cy="-279" rx="85.29" ry="18"/> <!-- getting_location -->
<text text-anchor="middle" x="366.25" y="-275.3" font-family="Times,serif" font-size="14.00">getting_location</text> <g id="node3" class="node">
</g> <title>getting_location</title>
<!-- init&#45;&gt;getting_location --> <ellipse fill="none" stroke="black" cx="366.25" cy="-279" rx="85.29" ry="18"/>
<g id="edge2" class="edge"> <text text-anchor="middle" x="366.25" y="-275.3" font-family="Times,serif" font-size="14.00">
<title>init&#45;&gt;getting_location</title> getting_location
<path fill="none" stroke="black" d="M242.41,-538.69C294.16,-537.46 403.84,-531.59 427.25,-504 481.59,-439.95 469.34,-387.69 427.25,-315 424.07,-309.52 419.68,-304.83 414.7,-300.82"/> </text>
<polygon fill="black" stroke="black" points="416.68,-297.93 406.47,-295.09 412.67,-303.68 416.68,-297.93"/> </g>
<text text-anchor="middle" x="559.75" y="-405.8" font-family="Times,serif" font-size="14.00">previously granted flag set</text> <!-- init&#45;&gt;getting_location -->
</g> <g id="edge2" class="edge">
<!-- idle --> <title>init&#45;&gt;getting_location</title>
<g id="node4" class="node"> <path fill="none" stroke="black"
<title>idle</title> d="M242.41,-538.69C294.16,-537.46 403.84,-531.59 427.25,-504 481.59,-439.95 469.34,-387.69 427.25,-315 424.07,-309.52 419.68,-304.83 414.7,-300.82"/>
<ellipse fill="none" stroke="black" cx="255.25" cy="-453" rx="27.9" ry="18"/> <polygon fill="black" stroke="black" points="416.68,-297.93 406.47,-295.09 412.67,-303.68 416.68,-297.93"/>
<text text-anchor="middle" x="255.25" y="-449.3" font-family="Times,serif" font-size="14.00">idle</text> <text text-anchor="middle" x="559.75" y="-405.8" font-family="Times,serif" font-size="14.00">previously
</g> granted flag set
<!-- init&#45;&gt;idle --> </text>
<g id="edge3" class="edge"> </g>
<title>init&#45;&gt;idle</title> <!-- idle -->
<path fill="none" stroke="black" d="M212.27,-521.58C211.37,-511.6 211.62,-499.1 216.25,-489 218.98,-483.03 223.28,-477.64 228.03,-472.99"/> <g id="node4" class="node">
<polygon fill="black" stroke="black" points="230.48,-475.49 235.73,-466.29 225.89,-470.21 230.48,-475.49"/> <title>idle</title>
<text text-anchor="middle" x="321.75" y="-492.8" font-family="Times,serif" font-size="14.00">previously granted flag unset</text> <ellipse fill="none" stroke="black" cx="255.25" cy="-453" rx="27.9" ry="18"/>
</g> <text text-anchor="middle" x="255.25" y="-449.3" font-family="Times,serif" font-size="14.00">idle</text>
<!-- location_found --> </g>
<g id="node6" class="node"> <!-- init&#45;&gt;idle -->
<title>location_found</title> <g id="edge3" class="edge">
<ellipse fill="none" stroke="black" cx="366.25" cy="-192" rx="77.99" ry="18"/> <title>init&#45;&gt;idle</title>
<text text-anchor="middle" x="366.25" y="-188.3" font-family="Times,serif" font-size="14.00">location_found</text> <path fill="none" stroke="black"
</g> d="M212.27,-521.58C211.37,-511.6 211.62,-499.1 216.25,-489 218.98,-483.03 223.28,-477.64 228.03,-472.99"/>
<!-- getting_location&#45;&gt;location_found --> <polygon fill="black" stroke="black" points="230.48,-475.49 235.73,-466.29 225.89,-470.21 230.48,-475.49"/>
<g id="edge8" class="edge"> <text text-anchor="middle" x="321.75" y="-492.8" font-family="Times,serif" font-size="14.00">previously
<title>getting_location&#45;&gt;location_found</title> granted flag unset
<path fill="none" stroke="black" d="M366.25,-260.8C366.25,-249.16 366.25,-233.55 366.25,-220.24"/> </text>
<polygon fill="black" stroke="black" points="369.75,-220.18 366.25,-210.18 362.75,-220.18 369.75,-220.18"/> </g>
<text text-anchor="middle" x="417.25" y="-231.8" font-family="Times,serif" font-size="14.00">location found</text> <!-- location_found -->
</g> <g id="node6" class="node">
<!-- request_permission --> <title>location_found</title>
<g id="node5" class="node"> <ellipse fill="none" stroke="black" cx="366.25" cy="-192" rx="77.99" ry="18"/>
<title>request_permission</title> <text text-anchor="middle" x="366.25" y="-188.3" font-family="Times,serif" font-size="14.00">
<ellipse fill="none" stroke="black" cx="264.25" cy="-366" rx="102.08" ry="18"/> location_found
<text text-anchor="middle" x="264.25" y="-362.3" font-family="Times,serif" font-size="14.00">request_permission</text> </text>
</g> </g>
<!-- idle&#45;&gt;request_permission --> <!-- getting_location&#45;&gt;location_found -->
<g id="edge4" class="edge"> <g id="edge8" class="edge">
<title>idle&#45;&gt;request_permission</title> <title>getting_location&#45;&gt;location_found</title>
<path fill="none" stroke="black" d="M282.79,-448.82C302.7,-444.93 328.29,-436.26 341.25,-417 349.95,-404.06 340.76,-393.72 326.08,-385.86"/> <path fill="none" stroke="black" d="M366.25,-260.8C366.25,-249.16 366.25,-233.55 366.25,-220.24"/>
<polygon fill="black" stroke="black" points="327.44,-382.63 316.9,-381.53 324.45,-388.96 327.44,-382.63"/> <polygon fill="black" stroke="black" points="369.75,-220.18 366.25,-210.18 362.75,-220.18 369.75,-220.18"/>
<text text-anchor="middle" x="371.75" y="-405.8" font-family="Times,serif" font-size="14.00">on click</text> <text text-anchor="middle" x="417.25" y="-231.8" font-family="Times,serif" font-size="14.00">location
</g> found
<!-- request_permission&#45;&gt;denied --> </text>
<g id="edge7" class="edge"> </g>
<title>request_permission&#45;&gt;denied</title> <!-- request_permission -->
<path fill="none" stroke="black" d="M202.76,-351.6C180.78,-345.99 156.06,-338.72 134.25,-330 113.26,-321.61 90.96,-309.57 73.57,-299.42"/> <g id="node5" class="node">
<polygon fill="black" stroke="black" points="75.34,-296.4 64.96,-294.3 71.77,-302.42 75.34,-296.4"/> <title>request_permission</title>
<text text-anchor="middle" x="206.25" y="-318.8" font-family="Times,serif" font-size="14.00">permanently denied</text> <ellipse fill="none" stroke="black" cx="264.25" cy="-366" rx="102.08" ry="18"/>
</g> <text text-anchor="middle" x="264.25" y="-362.3" font-family="Times,serif" font-size="14.00">
<!-- request_permission&#45;&gt;getting_location --> request_permission
<g id="edge5" class="edge"> </text>
<title>request_permission&#45;&gt;getting_location</title> </g>
<path fill="none" stroke="black" d="M271.38,-348C276.49,-337.43 284.24,-324.16 294.25,-315 300.73,-309.07 308.39,-303.93 316.27,-299.56"/> <!-- idle&#45;&gt;request_permission -->
<polygon fill="black" stroke="black" points="317.92,-302.64 325.2,-294.94 314.71,-296.43 317.92,-302.64"/> <g id="edge4" class="edge">
<text text-anchor="middle" x="360.75" y="-318.8" font-family="Times,serif" font-size="14.00">granted (sets flag)</text> <title>idle&#45;&gt;request_permission</title>
</g> <path fill="none" stroke="black"
<!-- request_permission&#45;&gt;idle --> d="M282.79,-448.82C302.7,-444.93 328.29,-436.26 341.25,-417 349.95,-404.06 340.76,-393.72 326.08,-385.86"/>
<g id="edge6" class="edge"> <polygon fill="black" stroke="black" points="327.44,-382.63 316.9,-381.53 324.45,-388.96 327.44,-382.63"/>
<title>request_permission&#45;&gt;idle</title> <text text-anchor="middle" x="371.75" y="-405.8" font-family="Times,serif" font-size="14.00">on click</text>
<path fill="none" stroke="black" d="M257.1,-384.15C255.12,-389.74 253.24,-396.04 252.25,-402 251.02,-409.35 250.95,-417.37 251.4,-424.8"/> </g>
<polygon fill="black" stroke="black" points="247.92,-425.14 252.32,-434.78 254.89,-424.5 247.92,-425.14"/> <!-- request_permission&#45;&gt;denied -->
<text text-anchor="middle" x="294.75" y="-405.8" font-family="Times,serif" font-size="14.00">not granted</text> <g id="edge7" class="edge">
</g> <title>request_permission&#45;&gt;denied</title>
<!-- open_lock --> <path fill="none" stroke="black"
<g id="node7" class="node"> d="M202.76,-351.6C180.78,-345.99 156.06,-338.72 134.25,-330 113.26,-321.61 90.96,-309.57 73.57,-299.42"/>
<title>open_lock</title> <polygon fill="black" stroke="black" points="75.34,-296.4 64.96,-294.3 71.77,-302.42 75.34,-296.4"/>
<ellipse fill="none" stroke="black" cx="333.25" cy="-105" rx="55.79" ry="18"/> <text text-anchor="middle" x="206.25" y="-318.8" font-family="Times,serif" font-size="14.00">permanently
<text text-anchor="middle" x="333.25" y="-101.3" font-family="Times,serif" font-size="14.00">open_lock</text> denied
</g> </text>
<!-- location_found&#45;&gt;open_lock --> </g>
<g id="edge9" class="edge"> <!-- request_permission&#45;&gt;getting_location -->
<title>location_found&#45;&gt;open_lock</title> <g id="edge5" class="edge">
<path fill="none" stroke="black" d="M359.57,-173.8C354.98,-161.97 348.79,-146.03 343.56,-132.58"/> <title>request_permission&#45;&gt;getting_location</title>
<polygon fill="black" stroke="black" points="346.68,-130.94 339.8,-122.89 340.16,-133.47 346.68,-130.94"/> <path fill="none" stroke="black"
<text text-anchor="middle" x="448.25" y="-144.8" font-family="Times,serif" font-size="14.00">on click (zooms to location)</text> d="M271.38,-348C276.49,-337.43 284.24,-324.16 294.25,-315 300.73,-309.07 308.39,-303.93 316.27,-299.56"/>
</g> <polygon fill="black" stroke="black" points="317.92,-302.64 325.2,-294.94 314.71,-296.43 317.92,-302.64"/>
<!-- open_lock&#45;&gt;location_found --> <text text-anchor="middle" x="360.75" y="-318.8" font-family="Times,serif" font-size="14.00">granted (sets
<g id="edge10" class="edge"> flag)
<title>open_lock&#45;&gt;location_found</title> </text>
<path fill="none" stroke="black" d="M295.44,-118.33C275.01,-127.12 256.04,-140.15 267.25,-156 273.92,-165.44 283.37,-172.35 293.8,-177.41"/> </g>
<polygon fill="black" stroke="black" points="292.6,-180.7 303.17,-181.39 295.34,-174.26 292.6,-180.7"/> <!-- request_permission&#45;&gt;idle -->
<text text-anchor="middle" x="305.25" y="-144.8" font-family="Times,serif" font-size="14.00">after 3 sec</text> <g id="edge6" class="edge">
</g> <title>request_permission&#45;&gt;idle</title>
<!-- closed_lock --> <path fill="none" stroke="black"
<g id="node8" class="node"> d="M257.1,-384.15C255.12,-389.74 253.24,-396.04 252.25,-402 251.02,-409.35 250.95,-417.37 251.4,-424.8"/>
<title>closed_lock</title> <polygon fill="black" stroke="black" points="247.92,-425.14 252.32,-434.78 254.89,-424.5 247.92,-425.14"/>
<ellipse fill="none" stroke="black" cx="454.25" cy="-18" rx="63.09" ry="18"/> <text text-anchor="middle" x="294.75" y="-405.8" font-family="Times,serif" font-size="14.00">not granted
<text text-anchor="middle" x="454.25" y="-14.3" font-family="Times,serif" font-size="14.00">closed_lock</text> </text>
</g> </g>
<!-- open_lock&#45;&gt;closed_lock --> <!-- open_lock -->
<g id="edge11" class="edge"> <g id="node7" class="node">
<title>open_lock&#45;&gt;closed_lock</title> <title>open_lock</title>
<path fill="none" stroke="black" d="M328.89,-87.05C327.23,-76.5 327.17,-63.24 334.25,-54 346.04,-38.59 364.24,-29.68 382.92,-24.6"/> <ellipse fill="none" stroke="black" cx="333.25" cy="-105" rx="55.79" ry="18"/>
<polygon fill="black" stroke="black" points="383.78,-28 392.71,-22.28 382.17,-21.18 383.78,-28"/> <text text-anchor="middle" x="333.25" y="-101.3" font-family="Times,serif" font-size="14.00">open_lock
<text text-anchor="middle" x="447.75" y="-57.8" font-family="Times,serif" font-size="14.00">on click (locks zoom to location)</text> </text>
</g> </g>
<!-- closed_lock&#45;&gt;location_found --> <!-- location_found&#45;&gt;open_lock -->
<g id="edge12" class="edge"> <g id="edge9" class="edge">
<title>closed_lock&#45;&gt;location_found</title> <title>location_found&#45;&gt;open_lock</title>
<path fill="none" stroke="black" d="M513.08,-24.74C531.5,-29.64 549.95,-38.41 561.25,-54 588.04,-90.95 580.67,-122.9 549.25,-156 535.31,-170.68 491.24,-179.37 449.85,-184.42"/> <path fill="none" stroke="black" d="M359.57,-173.8C354.98,-161.97 348.79,-146.03 343.56,-132.58"/>
<polygon fill="black" stroke="black" points="449.22,-180.97 439.68,-185.6 450.02,-187.93 449.22,-180.97"/> <polygon fill="black" stroke="black" points="346.68,-130.94 339.8,-122.89 340.16,-133.47 346.68,-130.94"/>
<text text-anchor="middle" x="604.75" y="-101.3" font-family="Times,serif" font-size="14.00">on click</text> <text text-anchor="middle" x="448.25" y="-144.8" font-family="Times,serif" font-size="14.00">on click (zooms
</g> to location)
</g> </text>
</g>
<!-- open_lock&#45;&gt;location_found -->
<g id="edge10" class="edge">
<title>open_lock&#45;&gt;location_found</title>
<path fill="none" stroke="black"
d="M295.44,-118.33C275.01,-127.12 256.04,-140.15 267.25,-156 273.92,-165.44 283.37,-172.35 293.8,-177.41"/>
<polygon fill="black" stroke="black" points="292.6,-180.7 303.17,-181.39 295.34,-174.26 292.6,-180.7"/>
<text text-anchor="middle" x="305.25" y="-144.8" font-family="Times,serif" font-size="14.00">after 3 sec
</text>
</g>
<!-- closed_lock -->
<g id="node8" class="node">
<title>closed_lock</title>
<ellipse fill="none" stroke="black" cx="454.25" cy="-18" rx="63.09" ry="18"/>
<text text-anchor="middle" x="454.25" y="-14.3" font-family="Times,serif" font-size="14.00">closed_lock
</text>
</g>
<!-- open_lock&#45;&gt;closed_lock -->
<g id="edge11" class="edge">
<title>open_lock&#45;&gt;closed_lock</title>
<path fill="none" stroke="black"
d="M328.89,-87.05C327.23,-76.5 327.17,-63.24 334.25,-54 346.04,-38.59 364.24,-29.68 382.92,-24.6"/>
<polygon fill="black" stroke="black" points="383.78,-28 392.71,-22.28 382.17,-21.18 383.78,-28"/>
<text text-anchor="middle" x="447.75" y="-57.8" font-family="Times,serif" font-size="14.00">on click (locks
zoom to location)
</text>
</g>
<!-- closed_lock&#45;&gt;location_found -->
<g id="edge12" class="edge">
<title>closed_lock&#45;&gt;location_found</title>
<path fill="none" stroke="black"
d="M513.08,-24.74C531.5,-29.64 549.95,-38.41 561.25,-54 588.04,-90.95 580.67,-122.9 549.25,-156 535.31,-170.68 491.24,-179.37 449.85,-184.42"/>
<polygon fill="black" stroke="black" points="449.22,-180.97 439.68,-185.6 450.02,-187.93 449.22,-180.97"/>
<text text-anchor="middle" x="604.75" y="-101.3" font-family="Times,serif" font-size="14.00">on click</text>
</g>
</g>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 8.4 KiB

After

Width:  |  Height:  |  Size: 10 KiB

View file

@ -6,13 +6,15 @@ Some highlights of new releases.
0.10 0.10
---- ----
The 0.10 version contains a lot of refactorings on various core of the application, namely in the rendering stack, the fetching of data and uploading. The 0.10 version contains a lot of refactorings on various core of the application, namely in the rendering stack, the
fetching of data and uploading.
Some highlights are: Some highlights are:
1. The addition of fallback overpass servers 1. The addition of fallback overpass servers
2. Fetching data from OSM directly (especially useful in the personal theme) 2. Fetching data from OSM directly (especially useful in the personal theme)
3. Splitting all the features per tile (with a maximum amount of features per tile, splitting further if needed), making everything a ton faster 3. Splitting all the features per tile (with a maximum amount of features per tile, splitting further if needed), making
everything a ton faster
4. If a tile has too much features, the featuers are not shown. Instead, a rectangle with the feature amount is shown. 4. If a tile has too much features, the featuers are not shown. Instead, a rectangle with the feature amount is shown.
Furthermore, it contains a few new themes and theme updates: Furthermore, it contains a few new themes and theme updates:
@ -31,9 +33,8 @@ Other various small improvements:
0.8 and 0.9 0.8 and 0.9
----------- -----------
Addition of filters per layer Addition of filters per layer Addition of a download-as-pdf for select themes Addition of a download-as-geojson and
Addition of a download-as-pdf for select themes download-as-csv for select themes
Addition of a download-as-geojson and download-as-csv for select themes
... ...

View file

@ -1,10 +1,10 @@
Available types for text fields
Available types for text fields
================================= =================================
The listed types here trigger a special input element. Use them in `tagrendering.freeform.type` of your tagrendering to activate them The listed types here trigger a special input element. Use them in `tagrendering.freeform.type` of your tagrendering to
activate them
## string ## string
@ -24,15 +24,15 @@ A geographical direction, in degrees. 0° is north, 90° is east, ... Will retur
## length ## length
A geographical length in meters (rounded at two points). Will give an extra minimap with a measurement tool. Arguments: [ zoomlevel, preferredBackgroundMapType (comma separated) ], e.g. `["21", "map,photo"] A geographical length in meters (rounded at two points). Will give an extra minimap with a measurement tool.
Arguments: [ zoomlevel, preferredBackgroundMapType (comma separated) ], e.g. `["21", "map,photo"]
## wikidata ## wikidata
A wikidata identifier, e.g. Q42. A wikidata identifier, e.g. Q42.
### Helper arguments ### Helper arguments
name | doc name | doc
------ | ----- ------ | -----
key | the value of this tag will initialize search (default: name) key | the value of this tag will initialize search (default: name)
@ -43,10 +43,10 @@ subarg | doc
removePrefixes | remove these snippets of text from the start of the passed string to search removePrefixes | remove these snippets of text from the start of the passed string to search
removePostfixes | remove these snippets of text from the end of the passed string to search removePostfixes | remove these snippets of text from the end of the passed string to search
### Example usage ### Example usage
The following is the 'freeform'-part of a layer config which will trigger a search for the wikidata item corresponding with the name of the selected feature. It will also remove '-street', '-square', ... if found at the end of the name The following is the 'freeform'-part of a layer config which will trigger a search for the wikidata item corresponding
with the name of the selected feature. It will also remove '-street', '-square', ... if found at the end of the name
``` ```
"freeform": { "freeform": {
@ -102,10 +102,9 @@ A phone number
## opening_hours ## opening_hours
Has extra elements to easily input when a POI is opened. Has extra elements to easily input when a POI is opened.
### Helper arguments ### Helper arguments
name | doc name | doc
------ | ----- ------ | -----
options | A JSON-object of type `{ prefix: string, postfix: string }`. options | A JSON-object of type `{ prefix: string, postfix: string }`.
@ -115,10 +114,9 @@ subarg | doc
prefix | Piece of text that will always be added to the front of the generated opening hours. If the OSM-data does not start with this, it will fail to parse prefix | Piece of text that will always be added to the front of the generated opening hours. If the OSM-data does not start with this, it will fail to parse
postfix | Piece of text that will always be added to the end of the generated opening hours postfix | Piece of text that will always be added to the end of the generated opening hours
### Example usage ### Example usage
To add a conditional (based on time) access restriction: To add a conditional (based on time) access restriction:
``` ```
@ -134,7 +132,8 @@ postfix | Piece of text that will always be added to the end of the generated op
} }
``` ```
*Don't forget to pass the prefix and postfix in the rendering as well*: `{opening_hours_table(opening_hours,yes @ &LPARENS, &RPARENS )` *Don't forget to pass the prefix and postfix in the rendering as
well*: `{opening_hours_table(opening_hours,yes @ &LPARENS, &RPARENS )`
## color ## color

View file

@ -1,43 +1,40 @@
### Special tag renderings ### Special tag renderings
In a tagrendering, some special values are substituted by an advanced UI-element. This allows advanced features and
visualizations to be reused by custom themes or even to query third-party API's.
General usage is `{func_name()}`, `{func_name(arg, someotherarg)}` or `{func_name(args):cssStyle}`. Note that you _do
not_ need to use quotes around your arguments, the comma is enough to separate them. This also implies you cannot use a
comma in your args
In a tagrendering, some special values are substituted by an advanced UI-element. This allows advanced features and visualizations to be reused by custom themes or even to query third-party API's. - [all_tags](#all_tags)
- [image_carousel](#image_carousel)
General usage is `{func_name()}`, `{func_name(arg, someotherarg)}` or `{func_name(args):cssStyle}`. Note that you _do not_ need to use quotes around your arguments, the comma is enough to separate them. This also implies you cannot use a comma in your args - [image_upload](#image_upload)
- [wikipedia](#wikipedia)
- [minimap](#minimap)
- [sided_minimap](#sided_minimap)
- [all_tags](#all_tags) - [reviews](#reviews)
- [image_carousel](#image_carousel) - [opening_hours_table](#opening_hours_table)
- [image_upload](#image_upload) - [live](#live)
- [wikipedia](#wikipedia) - [histogram](#histogram)
- [minimap](#minimap) - [share_link](#share_link)
- [sided_minimap](#sided_minimap) - [canonical](#canonical)
- [reviews](#reviews) - [import_button](#import_button)
- [opening_hours_table](#opening_hours_table) - [multi_apply](#multi_apply)
- [live](#live) - [tag_apply](#tag_apply)
- [histogram](#histogram)
- [share_link](#share_link)
- [canonical](#canonical)
- [import_button](#import_button)
- [multi_apply](#multi_apply)
- [tag_apply](#tag_apply)
### all_tags ### all_tags
Prints all key-value pairs of the object - used for debugging Prints all key-value pairs of the object - used for debugging
#### Example usage #### Example usage
`{all_tags()}` `{all_tags()}`
### image_carousel ### image_carousel
Creates an image carousel for the given sources. An attempt will be made to guess what source is used. Supported: Wikidata identifiers, Wikipedia pages, Wikimedia categories, IMGUR (with attribution, direct links) Creates an image carousel for the given sources. An attempt will be made to guess what source is used. Supported:
Wikidata identifiers, Wikipedia pages, Wikimedia categories, IMGUR (with attribution, direct links)
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
@ -45,12 +42,11 @@ image key/prefix (multiple values allowed if comma-seperated) | image,mapillary,
#### Example usage #### Example usage
`{image_carousel(image,mapillary,image,wikidata,wikimedia_commons,image,image)}` `{image_carousel(image,mapillary,image,wikidata,wikimedia_commons,image,image)}`
### image_upload ### image_upload
Creates a button where a user can upload an image to IMGUR Creates a button where a user can upload an image to IMGUR
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
@ -59,12 +55,11 @@ label | Add image | The text to show on the button
#### Example usage #### Example usage
`{image_upload(image,Add image)}` `{image_upload(image,Add image)}`
### wikipedia ### wikipedia
A box showing the corresponding wikipedia article - based on the wikidata tag A box showing the corresponding wikipedia article - based on the wikidata tag
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
@ -72,12 +67,13 @@ keyToShowWikipediaFor | wikidata | Use the wikidata entry from this key to show
#### Example usage #### Example usage
`{wikipedia()}` is a basic example, `{wikipedia(name:etymology:wikidata)}` to show the wikipedia page of whom the feature was named after. Also remember that these can be styled, e.g. `{wikipedia():max-height: 10rem}` to limit the height `{wikipedia()}` is a basic example, `{wikipedia(name:etymology:wikidata)}` to show the wikipedia page of whom the
feature was named after. Also remember that these can be styled, e.g. `{wikipedia():max-height: 10rem}` to limit the
height
### minimap ### minimap
A small map showing the selected feature. A small map showing the selected feature.
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
@ -86,12 +82,14 @@ idKey | id | (Matches all resting arguments) This argument should be the key of
#### Example usage #### Example usage
`{minimap()}`, `{minimap(17, id, _list_of_embedded_feature_ids_calculated_by_calculated_tag):height:10rem; border: 2px solid black}` `{minimap()}`
, `{minimap(17, id, _list_of_embedded_feature_ids_calculated_by_calculated_tag):height:10rem; border: 2px solid black}`
### sided_minimap ### sided_minimap
A small map showing _only one side_ the selected feature. *This features requires to have linerenderings with offset* as only linerenderings with a postive or negative offset will be shown. Note: in most cases, this map will be automatically introduced A small map showing _only one side_ the selected feature. *This features requires to have linerenderings with offset* as
only linerenderings with a postive or negative offset will be shown. Note: in most cases, this map will be automatically
introduced
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
@ -99,41 +97,48 @@ side | _undefined_ | The side to show, either `left` or `right`
#### Example usage #### Example usage
`{sided_minimap(left)}` `{sided_minimap(left)}`
### reviews ### reviews
Adds an overview of the mangrove-reviews of this object. Mangrove.Reviews needs - in order to identify the reviewed object - a coordinate and a name. By default, the name of the object is given, but this can be overwritten Adds an overview of the mangrove-reviews of this object. Mangrove.Reviews needs - in order to identify the reviewed
object - a coordinate and a name. By default, the name of the object is given, but this can be overwritten
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
subjectKey | name | The key to use to determine the subject. If specified, the subject will be <b>tags[subjectKey]</b> subjectKey | name | The key to use to determine the subject. If specified, the subject will be <b>tags[subjectKey]</b>
fallback | _undefined_ | The identifier to use, if <i>tags[subjectKey]</i> as specified above is not available. This is effectively a fallback value fallback | _
undefined_ | The identifier to use, if <i>tags[subjectKey]</i> as specified above is not available. This is effectively a fallback value
#### Example usage #### Example usage
`{reviews()}` for a vanilla review, `{reviews(name, play_forest)}` to review a play forest. If a name is known, the name will be used as identifier, otherwise 'play_forest' is used `{reviews()}` for a vanilla review, `{reviews(name, play_forest)}` to review a play forest. If a name is known, the name
will be used as identifier, otherwise 'play_forest' is used
### opening_hours_table ### opening_hours_table
Creates an opening-hours table. Usage: {opening_hours_table(opening_hours)} to create a table of the tag 'opening_hours'. Creates an opening-hours table. Usage: {opening_hours_table(opening_hours)} to create a table of the tag '
opening_hours'.
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
key | opening_hours | The tagkey from which the table is constructed. key | opening_hours | The tagkey from which the table is constructed.
prefix | _empty string_ | Remove this string from the start of the value before parsing. __Note: use `&LPARENs` to indicate `(` if needed__ prefix | _empty string_ | Remove this string from the start of the value before parsing. __Note: use `&LPARENs` to
postfix | _empty string_ | Remove this string from the end of the value before parsing. __Note: use `&RPARENs` to indicate `)` if needed__ indicate `(` if needed__
postfix | _empty string_ | Remove this string from the end of the value before parsing. __Note: use `&RPARENs` to
indicate `)` if needed__
#### Example usage #### Example usage
A normal opening hours table can be invoked with `{opening_hours_table()}`. A table for e.g. conditional access with opening hours can be `{opening_hours_table(access:conditional, no @ &LPARENS, &RPARENS)}` A normal opening hours table can be invoked with `{opening_hours_table()}`. A table for e.g. conditional access with
opening hours can be `{opening_hours_table(access:conditional, no @ &LPARENS, &RPARENS)}`
### live ### live
Downloads a JSON from the given URL, e.g. '{live(example.org/data.json, shorthand:x.y.z, other:a.b.c, shorthand)}' will download the given file, will create an object {shorthand: json[x][y][z], other: json[a][b][c] out of it and will return 'other' or 'json[a][b][c]. This is made to use in combination with tags, e.g. {live({url}, {url:format}, needed_value)} Downloads a JSON from the given URL, e.g. '{live(example.org/data.json, shorthand:x.y.z, other:a.b.c, shorthand)}' will
download the given file, will create an object {shorthand: json[x][y][z], other: json[a][b][c] out of it and will
return 'other' or 'json[a][b][c]. This is made to use in combination with tags, e.g. {live({url}, {url:format},
needed_value)}
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
@ -143,28 +148,28 @@ path | _undefined_ | The path (or shorthand) that should be returned
#### Example usage #### Example usage
{live({url},{url:format},hour)} {live(https://data.mobility.brussels/bike/api/counts/?request=live&featureID=CB2105,hour:data.hour_cnt;day:data.day_cnt;year:data.year_cnt,hour)} {live({url},{url:format},hour)}
{live(https://data.mobility.brussels/bike/api/counts/?request=live&featureID=CB2105,hour:data.hour_cnt;day:data.day_cnt;year:data.year_cnt,hour)}
### histogram ### histogram
Create a histogram for a list of given values, read from the properties. Create a histogram for a list of given values, read from the properties.
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
key | _undefined_ | The key to be read and to generate a histogram from key | _undefined_ | The key to be read and to generate a histogram from
title | _empty string_ | The text to put above the given values column title | _empty string_ | The text to put above the given values column
countHeader | _empty string_ | The text to put above the counts countHeader | _empty string_ | The text to put above the counts
colors* | _undefined_ | (Matches all resting arguments - optional) Matches a regex onto a color value, e.g. `3[a-zA-Z+-]*:#33cc33` colors* | _
undefined_ | (Matches all resting arguments - optional) Matches a regex onto a color value, e.g. `3[a-zA-Z+-]*:#33cc33`
#### Example usage #### Example usage
`{histogram('some_key')}` with properties being `{some_key: ['a','b','a','c']} to create a histogram `{histogram('some_key')}` with properties being `{some_key: ['a','b','a','c']} to create a histogram
### share_link ### share_link
Creates a link that (attempts to) open the native 'share'-screen Creates a link that (attempts to) open the native 'share'-screen
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
@ -172,12 +177,11 @@ url | _undefined_ | The url to share (default: current URL)
#### Example usage #### Example usage
{share_link()} to share the current page, {share_link(<some_url>)} to share the given url {share_link()} to share the current page, {share_link(<some_url>)} to share the given url
### canonical ### canonical
Converts a short, canonical value into the long, translated text Converts a short, canonical value into the long, translated text
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
@ -185,12 +189,12 @@ key | _undefined_ | The key of the tag to give the canonical text for
#### Example usage #### Example usage
{canonical(length)} will give 42 metre (in french) {canonical(length)} will give 42 metre (in french)
### import_button ### import_button
This button will copy the data from an external dataset into OpenStreetMap. It is only functional in official themes but can be tested in unofficial themes. This button will copy the data from an external dataset into OpenStreetMap. It is only functional in official themes but
can be tested in unofficial themes.
#### Importing a dataset into OpenStreetMap: requirements #### Importing a dataset into OpenStreetMap: requirements
@ -198,101 +202,113 @@ If you want to import a dataset, make sure that:
1. The dataset to import has a suitable license 1. The dataset to import has a suitable license
2. The community has been informed of the import 2. The community has been informed of the import
3. All other requirements of the [import guidelines](https://wiki.openstreetmap.org/wiki/Import/Guidelines) have been followed 3. All other requirements of the [import guidelines](https://wiki.openstreetmap.org/wiki/Import/Guidelines) have been
followed
There are also some technicalities in your theme to keep in mind: There are also some technicalities in your theme to keep in mind:
1. The new feature will be added and will flow through the program as any other new point as if it came from OSM. 1. The new feature will be added and will flow through the program as any other new point as if it came from OSM. This
This means that there should be a layer which will match the new tags and which will display it. means that there should be a layer which will match the new tags and which will display it.
2. The original feature from your geojson layer will gain the tag '_imported=yes'. 2. The original feature from your geojson layer will gain the tag '_imported=yes'. This should be used to change the
This should be used to change the appearance or even to hide it (eg by changing the icon size to zero) appearance or even to hide it (eg by changing the icon size to zero)
3. There should be a way for the theme to detect previously imported points, even after reloading. 3. There should be a way for the theme to detect previously imported points, even after reloading. A reference number to
A reference number to the original dataset is an excellent way to do this the original dataset is an excellent way to do this
4. When importing ways, the theme creator is also responsible of avoiding overlapping ways. 4. When importing ways, the theme creator is also responsible of avoiding overlapping ways.
#### Disabled in unofficial themes #### Disabled in unofficial themes
The import button can be tested in an unofficial theme by adding `test=true` or `backend=osm-test` as [URL-paramter](URL_Parameters.md). The import button can be tested in an unofficial theme by adding `test=true` or `backend=osm-test`
The import button will show up then. If in testmode, you can read the changeset-XML directly in the web console. as [URL-paramter](URL_Parameters.md). The import button will show up then. If in testmode, you can read the
In the case that MapComplete is pointed to the testing grounds, the edit will be made on https://master.apis.dev.openstreetmap.org changeset-XML directly in the web console. In the case that MapComplete is pointed to the testing grounds, the edit will
be made on https://master.apis.dev.openstreetmap.org
#### Specifying which tags to copy or add #### Specifying which tags to copy or add
The argument `tags` of the import button takes a `;`-seperated list of tags to add. The argument `tags` of the import button takes a `;`-seperated list of tags to add.
These can either be a tag to add, such as `amenity=fast_food` or can use a substitution, e.g. `addr:housenumber=$number`. These can either be a tag to add, such as `amenity=fast_food` or can use a substitution, e.g. `addr:housenumber=$number`
This new point will then have the tags `amenity=fast_food` and `addr:housenumber` with the value that was saved in `number` in the original feature. . This new point will then have the tags `amenity=fast_food` and `addr:housenumber` with the value that was saved
in `number` in the original feature.
If a value to substitute is undefined, empty string will be used instead. If a value to substitute is undefined, empty string will be used instead.
This supports multiple values, e.g. `ref=$source:geometry:type/$source:geometry:ref` This supports multiple values, e.g. `ref=$source:geometry:type/$source:geometry:ref`
Remark that the syntax is slightly different then expected; it uses '$' to note a value to copy, followed by a name (matched with `[a-zA-Z0-9_:]*`). Sadly, delimiting with `{}` as these already mark the boundaries of the special rendering... Remark that the syntax is slightly different then expected; it uses '$' to note a value to copy, followed by a name (
matched with `[a-zA-Z0-9_:]*`). Sadly, delimiting with `{}` as these already mark the boundaries of the special
Note that these values can be prepare with javascript in the theme by using a [calculatedTag](calculatedTags.md#calculating-tags-with-javascript) rendering...
Note that these values can be prepare with javascript in the theme by using
a [calculatedTag](calculatedTags.md#calculating-tags-with-javascript)
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
targetLayer | _undefined_ | The id of the layer where this point should end up. This is not very strict, it will simply result in checking that this layer is shown preventing possible duplicate elements targetLayer | _
undefined_ | The id of the layer where this point should end up. This is not very strict, it will simply result in checking that this layer is shown preventing possible duplicate elements
tags | _undefined_ | The tags to add onto the new object - see specification above tags | _undefined_ | The tags to add onto the new object - see specification above
text | Import this data into OpenStreetMap | The text to show on the button text | Import this data into OpenStreetMap | The text to show on the button
icon | ./assets/svg/addSmall.svg | A nice icon to show in the button icon | ./assets/svg/addSmall.svg | A nice icon to show in the button
minzoom | 18 | How far the contributor must zoom in before being able to import the point minzoom | 18 | How far the contributor must zoom in before being able to import the point
Snap onto layer(s)/replace geometry with this other way | _undefined_ | - If the value corresponding with this key starts with 'way/' and the feature is a LineString or Polygon, the original OSM-way geometry will be changed to match the new geometry Snap onto layer(s)/replace geometry with this other way | _
- If a way of the given layer(s) is closeby, will snap the new point onto this way (similar as preset might snap). To show multiple layers to snap onto, use a `;`-seperated list undefined_ | - If the value corresponding with this key starts with 'way/' and the feature is a LineString or Polygon, the original OSM-way geometry will be changed to match the new geometry
snap max distance | 5 | The maximum distance that this point will move to snap onto a layer (in meters)
- If a way of the given layer(s) is closeby, will snap the new point onto this way (similar as preset might snap). To
show multiple layers to snap onto, use a `;`-seperated list snap max distance | 5 | The maximum distance that this
point will move to snap onto a layer (in meters)
#### Example usage #### Example usage
`{import_button(,,Import this data into OpenStreetMap,./assets/svg/addSmall.svg,18,,5)}` `{import_button(,,Import this data into OpenStreetMap,./assets/svg/addSmall.svg,18,,5)}`
### multi_apply ### multi_apply
A button to apply the tagging of this object onto a list of other features. This is an advanced feature for which you'll need calculatedTags A button to apply the tagging of this object onto a list of other features. This is an advanced feature for which you'll
need calculatedTags
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
feature_ids | _undefined_ | A JSOn-serialized list of IDs of features to apply the tagging on feature_ids | _undefined_ | A JSOn-serialized list of IDs of features to apply the tagging on
keys | _undefined_ | One key (or multiple keys, seperated by ';') of the attribute that should be copied onto the other features. keys | _
undefined_ | One key (or multiple keys, seperated by ';') of the attribute that should be copied onto the other features.
text | _undefined_ | The text to show on the button text | _undefined_ | The text to show on the button
autoapply | _undefined_ | A boolean indicating wether this tagging should be applied automatically if the relevant tags on this object are changed. A visual element indicating the multi_apply is still shown autoapply | _
overwrite | _undefined_ | If set to 'true', the tags on the other objects will always be overwritten. The default behaviour will be to only change the tags on other objects if they are either undefined or had the same value before the change undefined_ | A boolean indicating wether this tagging should be applied automatically if the relevant tags on this object are changed. A visual element indicating the multi_apply is still shown
overwrite | _
undefined_ | If set to 'true', the tags on the other objects will always be overwritten. The default behaviour will be to only change the tags on other objects if they are either undefined or had the same value before the change
#### Example usage #### Example usage
{multi_apply(_features_with_the_same_name_within_100m, name:etymology:wikidata;name:etymology, Apply etymology information on all nearby objects with the same name)} {multi_apply(_features_with_the_same_name_within_100m, name:etymology:wikidata;name:etymology, Apply etymology
information on all nearby objects with the same name)}
### tag_apply ### tag_apply
Shows a big button; clicking this button will apply certain tags onto the feature. Shows a big button; clicking this button will apply certain tags onto the feature.
The first argument takes a specification of which tags to add. The first argument takes a specification of which tags to add. These can either be a tag to add, such
These can either be a tag to add, such as `amenity=fast_food` or can use a substitution, e.g. `addr:housenumber=$number`. as `amenity=fast_food` or can use a substitution, e.g. `addr:housenumber=$number`. This new point will then have the
This new point will then have the tags `amenity=fast_food` and `addr:housenumber` with the value that was saved in `number` in the original feature. tags `amenity=fast_food` and `addr:housenumber` with the value that was saved in `number` in the original feature.
If a value to substitute is undefined, empty string will be used instead. If a value to substitute is undefined, empty string will be used instead.
This supports multiple values, e.g. `ref=$source:geometry:type/$source:geometry:ref` This supports multiple values, e.g. `ref=$source:geometry:type/$source:geometry:ref`
Remark that the syntax is slightly different then expected; it uses '$' to note a value to copy, followed by a name (matched with `[a-zA-Z0-9_:]*`). Sadly, delimiting with `{}` as these already mark the boundaries of the special rendering... Remark that the syntax is slightly different then expected; it uses '$' to note a value to copy, followed by a name (
matched with `[a-zA-Z0-9_:]*`). Sadly, delimiting with `{}` as these already mark the boundaries of the special
Note that these values can be prepare with javascript in the theme by using a [calculatedTag](calculatedTags.md#calculating-tags-with-javascript) rendering...
Note that these values can be prepare with javascript in the theme by using
a [calculatedTag](calculatedTags.md#calculating-tags-with-javascript)
name | default | description name | default | description
------ | --------- | ------------- ------ | --------- | -------------
tags_to_apply | _undefined_ | A specification of the tags to apply tags_to_apply | _undefined_ | A specification of the tags to apply
message | _undefined_ | The text to show to the contributor message | _undefined_ | The text to show to the contributor
image | _undefined_ | An image to show to the contributor on the button image | _undefined_ | An image to show to the contributor on the button
id_of_object_to_apply_this_one | _undefined_ | If specified, applies the the tags onto _another_ object. The id will be read from properties[id_of_object_to_apply_this_one] of the selected object. The tags are still calculated based on the tags of the _selected_ element id_of_object_to_apply_this_one | _undefined_ | If specified, applies the the tags onto _
another_ object. The id will be read from properties[id_of_object_to_apply_this_one] of the selected object. The tags are still calculated based on the tags of the _
selected_ element
#### Example usage #### Example usage
`{tag_apply(survey_date:=$_now:date, Surveyed today!)}` Generated from UI/SpecialVisualisations.ts `{tag_apply(survey_date:=$_now:date, Surveyed today!)}` Generated from UI/SpecialVisualisations.ts

View file

@ -1,7 +1,7 @@
from datetime import datetime
from matplotlib import pyplot
import json import json
import sys import sys
from datetime import datetime
from matplotlib import pyplot
def pyplot_init(): def pyplot_init():
@ -14,20 +14,22 @@ def pyplot_init():
def genKeys(data, type): def genKeys(data, type):
keys = map(lambda kv: kv["key"], data) keys = map(lambda kv: kv["key"], data)
if type == "date": if type == "date":
keys = map(lambda key : datetime.strptime(key, "%Y-%m-%dT%H:%M:%S.000Z"), keys) keys = map(lambda key: datetime.strptime(key, "%Y-%m-%dT%H:%M:%S.000Z"), keys)
return list(keys) return list(keys)
def createPie(options): def createPie(options):
data = options["plot"]["count"] data = options["plot"]["count"]
keys = genKeys(data, options["interpetKeysAs"]) keys = genKeys(data, options["interpetKeysAs"])
values = list(map(lambda kv: kv["value"], data)) values = list(map(lambda kv: kv["value"], data))
total = sum(map(lambda kv : kv["value"], data)) total = sum(map(lambda kv: kv["value"], data))
first_pct = data[0]["value"] / total first_pct = data[0]["value"] / total
pyplot_init() pyplot_init()
pyplot.pie(values, labels=keys, startangle=(90 - 360 * first_pct / 2)) pyplot.pie(values, labels=keys, startangle=(90 - 360 * first_pct / 2))
def createBar(options): def createBar(options):
data = options["plot"]["count"] data = options["plot"]["count"]
keys = genKeys(data, options["interpetKeysAs"]) keys = genKeys(data, options["interpetKeysAs"])
@ -37,26 +39,25 @@ def createBar(options):
pyplot.legend() pyplot.legend()
pyplot_init() pyplot_init()
title = sys.argv[1] title = sys.argv[1]
pyplot.title = title pyplot.title = title
names = [] names = []
while(True): while (True):
line = sys.stdin.readline() line = sys.stdin.readline()
if line == "" or line == "\n": if line == "" or line == "\n":
if(len(names) > 1): if (len(names) > 1):
pyplot.legend(loc="upper left", ncol=3) pyplot.legend(loc="upper left", ncol=3)
pyplot.savefig(title+".png", dpi=400, facecolor='w', edgecolor='w', pyplot.savefig(title + ".png", dpi=400, facecolor='w', edgecolor='w',
bbox_inches='tight') bbox_inches='tight')
break break
options = json.loads(line) options = json.loads(line)
print("Creating "+options["plot"]["type"]+" '"+options["name"]+"'") print("Creating " + options["plot"]["type"] + " '" + options["name"] + "'")
names.append(options["name"]) names.append(options["name"])
if(options["plot"]["type"] == "pie"): if (options["plot"]["type"] == "pie"):
createPie(options) createPie(options)
elif(options["plot"]["type"] == "bar"): elif (options["plot"]["type"] == "bar"):
createBar(options) createBar(options)
else: else:
print("Unkown type: "+options.type) print("Unkown type: " + options.type)

View file

@ -1,4 +1,3 @@
URL-parameters and URL-hash URL-parameters and URL-hash
============================ ============================
@ -9,8 +8,8 @@ What is a URL parameter?
URL-parameters are extra parts of the URL used to set the state. URL-parameters are extra parts of the URL used to set the state.
For example, if the url is `https://mapcomplete.osm.be/cyclofix?lat=51.0&lon=4.3&z=5&test=true#node/1234`, For example, if the url is `https://mapcomplete.osm.be/cyclofix?lat=51.0&lon=4.3&z=5&test=true#node/1234`, the
the URL-parameters are stated in the part between the `?` and the `#`. There are multiple, all separated by `&`, namely: URL-parameters are stated in the part between the `?` and the `#`. There are multiple, all separated by `&`, namely:
- The url-parameter `lat` is `51.0` in this instance - The url-parameter `lat` is `51.0` in this instance
- The url-parameter `lon` is `4.3` in this instance - The url-parameter `lon` is `4.3` in this instance
@ -20,139 +19,145 @@ the URL-parameters are stated in the part between the `?` and the `#`. There are
Finally, the URL-hash is the part after the `#`. It is `node/1234` in this case. Finally, the URL-hash is the part after the `#`. It is `node/1234` in this case.
fs-userbadge fs-userbadge
-------------- --------------
Disables/Enables the user information pill (userbadge) at the top left. Disabling this disables logging in and thus disables editing all together, effectively putting MapComplete into read-only mode. The default value is _true_ Disables/Enables the user information pill (userbadge) at the top left. Disabling this disables logging in and thus
disables editing all together, effectively putting MapComplete into read-only mode. The default value is _true_
fs-search fs-search
----------- -----------
Disables/Enables the search bar The default value is _true_ Disables/Enables the search bar The default value is _true_
fs-background fs-background
--------------- ---------------
Disables/Enables the background layer control The default value is _true_ Disables/Enables the background layer control The default value is _true_
fs-filter fs-filter
----------- -----------
Disables/Enables the filter The default value is _true_ Disables/Enables the filter The default value is _true_
fs-add-new fs-add-new
------------ ------------
Disables/Enables the 'add new feature'-popup. (A theme without presets might not have it in the first place) The default value is _true_ Disables/Enables the 'add new feature'-popup. (A theme without presets might not have it in the first place) The default
value is _true_
fs-welcome-message fs-welcome-message
-------------------- --------------------
Disables/enables the help menu or welcome message The default value is _true_ Disables/enables the help menu or welcome message The default value is _true_
fs-iframe-popout fs-iframe-popout
------------------ ------------------
Disables/Enables the iframe-popout button. If in iframe mode and the welcome message is hidden, a popout button to the full mapcomplete instance is shown instead (unless disabled with this switch) The default value is _true_ Disables/Enables the iframe-popout button. If in iframe mode and the welcome message is hidden, a popout button to the
full mapcomplete instance is shown instead (unless disabled with this switch) The default value is _true_
fs-more-quests fs-more-quests
---------------- ----------------
Disables/Enables the 'More Quests'-tab in the welcome message The default value is _true_ Disables/Enables the 'More Quests'-tab in the welcome message The default value is _true_
fs-share-screen fs-share-screen
----------------- -----------------
Disables/Enables the 'Share-screen'-tab in the welcome message The default value is _true_ Disables/Enables the 'Share-screen'-tab in the welcome message The default value is _true_
fs-geolocation fs-geolocation
---------------- ----------------
Disables/Enables the geolocation button The default value is _true_ Disables/Enables the geolocation button The default value is _true_
fs-all-questions fs-all-questions
------------------ ------------------
Always show all questions The default value is _false_ Always show all questions The default value is _false_
fs-export fs-export
----------- -----------
Enable the export as GeoJSON and CSV button The default value is _false_ Enable the export as GeoJSON and CSV button The default value is _false_
fs-pdf fs-pdf
-------- --------
Enable the PDF download button The default value is _false_ Enable the PDF download button The default value is _false_
backend backend
--------- ---------
The OSM backend to use - can be used to redirect mapcomplete to the testing backend when using 'osm-test' The default value is _osm_ The OSM backend to use - can be used to redirect mapcomplete to the testing backend when using 'osm-test' The default
value is _osm_
test test
------ ------
If true, 'dryrun' mode is activated. The app will behave as normal, except that changes to OSM will be printed onto the console instead of actually uploaded to osm.org The default value is _false_ If true, 'dryrun' mode is activated. The app will behave as normal, except that changes to OSM will be printed onto the
console instead of actually uploaded to osm.org The default value is _false_
debug debug
------- -------
If true, shows some extra debugging help such as all the available tags on every object The default value is _false_ If true, shows some extra debugging help such as all the available tags on every object The default value is _false_
fake-user fake-user
----------- -----------
If true, 'dryrun' mode is activated and a fake user account is loaded The default value is _false_ If true, 'dryrun' mode is activated and a fake user account is loaded The default value is _false_
overpassUrl overpassUrl
------------- -------------
Point mapcomplete to a different overpass-instance. Example: https://overpass-api.de/api/interpreter The default value is _https://overpass-api.de/api/interpreter,https://overpass.kumi.systems/api/interpreter,https://overpass.openstreetmap.ru/cgi/interpreter_ Point mapcomplete to a different overpass-instance. Example: https://overpass-api.de/api/interpreter The default value
is _https://overpass-api.de/api/interpreter,https://overpass.kumi.systems/api/interpreter,https://overpass.openstreetmap.ru/cgi/interpreter_
overpassTimeout overpassTimeout
----------------- -----------------
Set a different timeout (in seconds) for queries in overpass The default value is _30_ Set a different timeout (in seconds) for queries in overpass The default value is _30_
overpassMaxZoom overpassMaxZoom
----------------- -----------------
point to switch between OSM-api and overpass The default value is _17_ point to switch between OSM-api and overpass The default value is _17_
osmApiTileSize osmApiTileSize
---------------- ----------------
Tilesize when the OSM-API is used to fetch data within a BBOX The default value is _18_ Tilesize when the OSM-API is used to fetch data within a BBOX The default value is _18_
background background
------------ ------------
The id of the background layer to start with The default value is _osm_ The id of the background layer to start with The default value is _osm_
layer-<layer-id> layer-<layer-id>
------------------ ------------------
Wether or not the layer with id <layer-id> is shown The default value is _true_ Generated from QueryParameters Wether or not the layer with id <layer-id> is shown The default value is _true_ Generated from QueryParameters

View file

@ -5,8 +5,10 @@ import Loc from "../../Models/Loc";
export interface AvailableBaseLayersObj { export interface AvailableBaseLayersObj {
readonly osmCarto: BaseLayer; readonly osmCarto: BaseLayer;
layerOverview: BaseLayer[]; layerOverview: BaseLayer[];
AvailableLayersAt(location: UIEventSource<Loc>): UIEventSource<BaseLayer[]> AvailableLayersAt(location: UIEventSource<Loc>): UIEventSource<BaseLayer[]>
SelectBestLayerAccordingTo(location: UIEventSource<Loc>, preferedCategory: UIEventSource<string | string[]>): UIEventSource<BaseLayer> ;
SelectBestLayerAccordingTo(location: UIEventSource<Loc>, preferedCategory: UIEventSource<string | string[]>): UIEventSource<BaseLayer>;
} }
@ -31,7 +33,7 @@ export default class AvailableBaseLayers {
} }
public static implement(backend: AvailableBaseLayersObj){ public static implement(backend: AvailableBaseLayersObj) {
AvailableBaseLayers.layerOverview = backend.layerOverview AvailableBaseLayers.layerOverview = backend.layerOverview
AvailableBaseLayers.osmCarto = backend.osmCarto AvailableBaseLayers.osmCarto = backend.osmCarto
AvailableBaseLayers.implementation = backend AvailableBaseLayers.implementation = backend

View file

@ -3,13 +3,13 @@ import {UIEventSource} from "../UIEventSource";
import Loc from "../../Models/Loc"; import Loc from "../../Models/Loc";
import {GeoOperations} from "../GeoOperations"; import {GeoOperations} from "../GeoOperations";
import * as editorlayerindex from "../../assets/editor-layer-index.json"; import * as editorlayerindex from "../../assets/editor-layer-index.json";
import * as L from "leaflet";
import {TileLayer} from "leaflet"; import {TileLayer} from "leaflet";
import * as X from "leaflet-providers"; import * as X from "leaflet-providers";
import * as L from "leaflet";
import {Utils} from "../../Utils"; import {Utils} from "../../Utils";
import {AvailableBaseLayersObj} from "./AvailableBaseLayers"; import {AvailableBaseLayersObj} from "./AvailableBaseLayers";
export default class AvailableBaseLayersImplementation implements AvailableBaseLayersObj{ export default class AvailableBaseLayersImplementation implements AvailableBaseLayersObj {
public readonly osmCarto: BaseLayer = public readonly osmCarto: BaseLayer =
{ {
@ -28,102 +28,6 @@ export default class AvailableBaseLayersImplementation implements AvailableBaseL
public layerOverview = AvailableBaseLayersImplementation.LoadRasterIndex().concat(AvailableBaseLayersImplementation.LoadProviderIndex()); public layerOverview = AvailableBaseLayersImplementation.LoadRasterIndex().concat(AvailableBaseLayersImplementation.LoadProviderIndex());
public AvailableLayersAt(location: UIEventSource<Loc>): UIEventSource<BaseLayer[]> {
const source = location.map(
(currentLocation) => {
if (currentLocation === undefined) {
return this.layerOverview;
}
const currentLayers = source?.data; // A bit unorthodox - I know
const newLayers = this.CalculateAvailableLayersAt(currentLocation?.lon, currentLocation?.lat);
if (currentLayers === undefined) {
return newLayers;
}
if (newLayers.length !== currentLayers.length) {
return newLayers;
}
for (let i = 0; i < newLayers.length; i++) {
if (newLayers[i].name !== currentLayers[i].name) {
return newLayers;
}
}
return currentLayers;
});
return source;
}
public SelectBestLayerAccordingTo(location: UIEventSource<Loc>, preferedCategory: UIEventSource<string | string[]>): UIEventSource<BaseLayer> {
return this.AvailableLayersAt(location).map(available => {
// First float all 'best layers' to the top
available.sort((a, b) => {
if (a.isBest && b.isBest) {
return 0;
}
if (!a.isBest) {
return 1
}
return -1;
}
)
if (preferedCategory.data === undefined) {
return available[0]
}
let prefered: string []
if (typeof preferedCategory.data === "string") {
prefered = [preferedCategory.data]
} else {
prefered = preferedCategory.data;
}
prefered.reverse();
for (const category of prefered) {
//Then sort all 'photo'-layers to the top. Stability of the sorting will force a 'best' photo layer on top
available.sort((a, b) => {
if (a.category === category && b.category === category) {
return 0;
}
if (a.category !== category) {
return 1
}
return -1;
}
)
}
return available[0]
})
}
private CalculateAvailableLayersAt(lon: number, lat: number): BaseLayer[] {
const availableLayers = [this.osmCarto]
const globalLayers = [];
for (const layerOverviewItem of this.layerOverview) {
const layer = layerOverviewItem;
if (layer.feature?.geometry === undefined || layer.feature?.geometry === null) {
globalLayers.push(layer);
continue;
}
if (lon === undefined || lat === undefined) {
continue;
}
if (GeoOperations.inside([lon, lat], layer.feature)) {
availableLayers.push(layer);
}
}
return availableLayers.concat(globalLayers);
}
private static LoadRasterIndex(): BaseLayer[] { private static LoadRasterIndex(): BaseLayer[] {
const layers: BaseLayer[] = [] const layers: BaseLayer[] = []
// @ts-ignore // @ts-ignore
@ -289,4 +193,100 @@ export default class AvailableBaseLayersImplementation implements AvailableBaseL
subdomains: domains subdomains: domains
}); });
} }
public AvailableLayersAt(location: UIEventSource<Loc>): UIEventSource<BaseLayer[]> {
const source = location.map(
(currentLocation) => {
if (currentLocation === undefined) {
return this.layerOverview;
}
const currentLayers = source?.data; // A bit unorthodox - I know
const newLayers = this.CalculateAvailableLayersAt(currentLocation?.lon, currentLocation?.lat);
if (currentLayers === undefined) {
return newLayers;
}
if (newLayers.length !== currentLayers.length) {
return newLayers;
}
for (let i = 0; i < newLayers.length; i++) {
if (newLayers[i].name !== currentLayers[i].name) {
return newLayers;
}
}
return currentLayers;
});
return source;
}
public SelectBestLayerAccordingTo(location: UIEventSource<Loc>, preferedCategory: UIEventSource<string | string[]>): UIEventSource<BaseLayer> {
return this.AvailableLayersAt(location).map(available => {
// First float all 'best layers' to the top
available.sort((a, b) => {
if (a.isBest && b.isBest) {
return 0;
}
if (!a.isBest) {
return 1
}
return -1;
}
)
if (preferedCategory.data === undefined) {
return available[0]
}
let prefered: string []
if (typeof preferedCategory.data === "string") {
prefered = [preferedCategory.data]
} else {
prefered = preferedCategory.data;
}
prefered.reverse();
for (const category of prefered) {
//Then sort all 'photo'-layers to the top. Stability of the sorting will force a 'best' photo layer on top
available.sort((a, b) => {
if (a.category === category && b.category === category) {
return 0;
}
if (a.category !== category) {
return 1
}
return -1;
}
)
}
return available[0]
})
}
private CalculateAvailableLayersAt(lon: number, lat: number): BaseLayer[] {
const availableLayers = [this.osmCarto]
const globalLayers = [];
for (const layerOverviewItem of this.layerOverview) {
const layer = layerOverviewItem;
if (layer.feature?.geometry === undefined || layer.feature?.geometry === null) {
globalLayers.push(layer);
continue;
}
if (lon === undefined || lat === undefined) {
continue;
}
if (GeoOperations.inside([lon, lat], layer.feature)) {
availableLayers.push(layer);
}
}
return availableLayers.concat(globalLayers);
}
} }

View file

@ -14,7 +14,7 @@ export default class BackgroundLayerResetter {
availableLayers: UIEventSource<BaseLayer[]>, availableLayers: UIEventSource<BaseLayer[]>,
defaultLayerId: string = undefined) { defaultLayerId: string = undefined) {
if(Utils.runningFromConsole){ if (Utils.runningFromConsole) {
return return
} }

View file

@ -9,7 +9,7 @@ import StaticFeatureSource from "../FeatureSource/Sources/StaticFeatureSource";
export default class GeoLocationHandler extends VariableUiElement { export default class GeoLocationHandler extends VariableUiElement {
public readonly currentLocation : FeatureSource public readonly currentLocation: FeatureSource
/** /**
* Wether or not the geolocation is active, aka the user requested the current location * Wether or not the geolocation is active, aka the user requested the current location
@ -182,19 +182,19 @@ export default class GeoLocationHandler extends VariableUiElement {
} }
}) })
this.currentLocation = new StaticFeatureSource([], false) this.currentLocation = new StaticFeatureSource([], false)
this._currentGPSLocation.addCallback((location) => { this._currentGPSLocation.addCallback((location) => {
self._previousLocationGrant.setData("granted"); self._previousLocationGrant.setData("granted");
const feature = { const feature = {
"type": "Feature", "type": "Feature",
properties: { properties: {
"user:location":"yes", "user:location": "yes",
"accuracy":location.accuracy, "accuracy": location.accuracy,
"speed":location.speed, "speed": location.speed,
}, },
geometry:{ geometry: {
type:"Point", type: "Point",
coordinates: [location.longitude, location.latitude], coordinates: [location.longitude, location.latitude],
} }
} }

View file

@ -115,7 +115,6 @@ export default class OverpassFeatureSource implements FeatureSource {
let lastUsed = 0; let lastUsed = 0;
const layersToDownload = [] const layersToDownload = []
for (const layer of this.state.layoutToUse.layers) { for (const layer of this.state.layoutToUse.layers) {
@ -137,7 +136,7 @@ export default class OverpassFeatureSource implements FeatureSource {
const self = this; const self = this;
const overpassUrls = self.state.overpassUrl.data const overpassUrls = self.state.overpassUrl.data
let bounds : BBox let bounds: BBox
do { do {
try { try {
@ -182,7 +181,7 @@ export default class OverpassFeatureSource implements FeatureSource {
try { try {
if(data === undefined){ if (data === undefined) {
return undefined return undefined
} }
data.features.forEach(feature => SimpleMetaTagger.objectMetaInfo.applyMetaTagsOnFeature(feature, date, undefined)); data.features.forEach(feature => SimpleMetaTagger.objectMetaInfo.applyMetaTagsOnFeature(feature, date, undefined));

View file

@ -31,7 +31,7 @@ export default class PendingChangesUploader {
} }
}); });
if(Utils.runningFromConsole){ if (Utils.runningFromConsole) {
return; return;
} }

View file

@ -10,7 +10,7 @@ import LayoutConfig from "../../Models/ThemeConfig/LayoutConfig";
* Makes sure the hash shows the selected element and vice-versa. * Makes sure the hash shows the selected element and vice-versa.
*/ */
export default class SelectedFeatureHandler { export default class SelectedFeatureHandler {
private static readonly _no_trigger_on = new Set(["welcome", "copyright", "layers", "new", "filters","", undefined]) private static readonly _no_trigger_on = new Set(["welcome", "copyright", "layers", "new", "filters", "", undefined])
private readonly hash: UIEventSource<string>; private readonly hash: UIEventSource<string>;
private readonly state: { private readonly state: {
selectedElement: UIEventSource<any>, selectedElement: UIEventSource<any>,

View file

@ -81,5 +81,4 @@ export default class StrayClickHandler {
} }
} }

View file

@ -8,7 +8,7 @@ import {ElementStorage} from "../ElementStorage";
import {Utils} from "../../Utils"; import {Utils} from "../../Utils";
export default class TitleHandler { export default class TitleHandler {
constructor(state : { constructor(state: {
selectedElement: UIEventSource<any>, selectedElement: UIEventSource<any>,
layoutToUse: LayoutConfig, layoutToUse: LayoutConfig,
allElements: ElementStorage allElements: ElementStorage
@ -39,7 +39,7 @@ export default class TitleHandler {
currentTitle.addCallbackAndRunD(title => { currentTitle.addCallbackAndRunD(title => {
if(Utils.runningFromConsole){ if (Utils.runningFromConsole) {
return return
} }
document.title = title document.title = title

View file

@ -4,11 +4,11 @@ import {GeoOperations} from "./GeoOperations";
export class BBox { export class BBox {
static global: BBox = new BBox([[-180, -90], [180, 90]]);
readonly maxLat: number; readonly maxLat: number;
readonly maxLon: number; readonly maxLon: number;
readonly minLat: number; readonly minLat: number;
readonly minLon: number; readonly minLon: number;
static global: BBox = new BBox([[-180, -90], [180, 90]]);
constructor(coordinates) { constructor(coordinates) {
this.maxLat = -90; this.maxLat = -90;
@ -45,6 +45,17 @@ export class BBox {
return feature.bbox; return feature.bbox;
} }
static fromTile(z: number, x: number, y: number): BBox {
return new BBox(Tiles.tile_bounds_lon_lat(z, x, y))
}
static fromTileIndex(i: number): BBox {
if (i === 0) {
return BBox.global
}
return BBox.fromTile(...Tiles.tile_from_index(i))
}
/** /**
* Constructs a tilerange which fully contains this bbox (thus might be a bit larger) * Constructs a tilerange which fully contains this bbox (thus might be a bit larger)
* @param zoomlevel * @param zoomlevel
@ -83,24 +94,6 @@ export class BBox {
return true; return true;
} }
private check() {
if (isNaN(this.maxLon) || isNaN(this.maxLat) || isNaN(this.minLon) || isNaN(this.minLat)) {
console.log(this);
throw "BBOX has NAN";
}
}
static fromTile(z: number, x: number, y: number): BBox {
return new BBox(Tiles.tile_bounds_lon_lat(z, x, y))
}
static fromTileIndex(i: number): BBox {
if (i === 0) {
return BBox.global
}
return BBox.fromTile(...Tiles.tile_from_index(i))
}
getEast() { getEast() {
return this.maxLon return this.maxLon
} }
@ -117,9 +110,9 @@ export class BBox {
return this.minLat return this.minLat
} }
contains(lonLat: [number, number]){ contains(lonLat: [number, number]) {
return this.minLat <= lonLat[1] && lonLat[1] <= this.maxLat return this.minLat <= lonLat[1] && lonLat[1] <= this.maxLat
&& this.minLon<= lonLat[0] && lonLat[0] <= this.maxLon && this.minLon <= lonLat[0] && lonLat[0] <= this.maxLon
} }
pad(factor: number, maxIncrease = 2): BBox { pad(factor: number, maxIncrease = 2): BBox {
@ -179,4 +172,11 @@ export class BBox {
} }
private check() {
if (isNaN(this.maxLon) || isNaN(this.maxLat) || isNaN(this.minLon) || isNaN(this.minLat)) {
console.log(this);
throw "BBOX has NAN";
}
}
} }

View file

@ -8,6 +8,7 @@ export default class ContributorCount {
public readonly Contributors: UIEventSource<Map<string, number>> = new UIEventSource<Map<string, number>>(new Map<string, number>()); public readonly Contributors: UIEventSource<Map<string, number>> = new UIEventSource<Map<string, number>>(new Map<string, number>());
private readonly state: { featurePipeline: FeaturePipeline, currentBounds: UIEventSource<BBox>, locationControl: UIEventSource<Loc> }; private readonly state: { featurePipeline: FeaturePipeline, currentBounds: UIEventSource<BBox>, locationControl: UIEventSource<Loc> };
private lastUpdate: Date = undefined;
constructor(state: { featurePipeline: FeaturePipeline, currentBounds: UIEventSource<BBox>, locationControl: UIEventSource<Loc> }) { constructor(state: { featurePipeline: FeaturePipeline, currentBounds: UIEventSource<BBox>, locationControl: UIEventSource<Loc> }) {
this.state = state; this.state = state;
@ -16,15 +17,13 @@ export default class ContributorCount {
self.update(bbox) self.update(bbox)
}) })
state.featurePipeline.runningQuery.addCallbackAndRun( state.featurePipeline.runningQuery.addCallbackAndRun(
_ => self.update(state.currentBounds.data) _ => self.update(state.currentBounds.data)
) )
} }
private lastUpdate: Date = undefined;
private update(bbox: BBox) { private update(bbox: BBox) {
if(bbox === undefined){ if (bbox === undefined) {
return; return;
} }
const now = new Date(); const now = new Date();

View file

@ -65,39 +65,6 @@ export default class DetermineLayout {
return [layoutToUse, undefined] return [layoutToUse, undefined]
} }
private static async LoadRemoteTheme(link: string): Promise<LayoutConfig | null> {
console.log("Downloading map theme from ", link);
new FixedUiElement(`Downloading the theme from the <a href="${link}">link</a>...`)
.AttachTo("centermessage");
try {
const parsed = await Utils.downloadJson(link)
console.log("Got ", parsed)
LegacyJsonConvert.fixThemeConfig(parsed)
try {
parsed.id = link;
return new LayoutConfig(parsed, false).patchImages(link, JSON.stringify(parsed));
} catch (e) {
console.error(e)
DetermineLayout.ShowErrorOnCustomTheme(
`<a href="${link}">${link}</a> is invalid:`,
new FixedUiElement(e)
)
return null;
}
} catch (e) {
console.error(e)
DetermineLayout.ShowErrorOnCustomTheme(
`<a href="${link}">${link}</a> is invalid - probably not found or invalid JSON:`,
new FixedUiElement(e)
)
return null;
}
}
public static LoadLayoutFromHash( public static LoadLayoutFromHash(
userLayoutParam: UIEventSource<string> userLayoutParam: UIEventSource<string>
): [LayoutConfig, string] | null { ): [LayoutConfig, string] | null {
@ -166,4 +133,37 @@ export default class DetermineLayout {
.AttachTo("centermessage"); .AttachTo("centermessage");
} }
private static async LoadRemoteTheme(link: string): Promise<LayoutConfig | null> {
console.log("Downloading map theme from ", link);
new FixedUiElement(`Downloading the theme from the <a href="${link}">link</a>...`)
.AttachTo("centermessage");
try {
const parsed = await Utils.downloadJson(link)
console.log("Got ", parsed)
LegacyJsonConvert.fixThemeConfig(parsed)
try {
parsed.id = link;
return new LayoutConfig(parsed, false).patchImages(link, JSON.stringify(parsed));
} catch (e) {
console.error(e)
DetermineLayout.ShowErrorOnCustomTheme(
`<a href="${link}">${link}</a> is invalid:`,
new FixedUiElement(e)
)
return null;
}
} catch (e) {
console.error(e)
DetermineLayout.ShowErrorOnCustomTheme(
`<a href="${link}">${link}</a> is invalid - probably not found or invalid JSON:`,
new FixedUiElement(e)
)
return null;
}
}
} }

View file

@ -39,10 +39,10 @@ export class ElementStorage {
} }
getEventSourceById(elementId): UIEventSource<any> { getEventSourceById(elementId): UIEventSource<any> {
if(elementId === undefined){ if (elementId === undefined) {
return undefined; return undefined;
} }
return this._elements.get(elementId); return this._elements.get(elementId);
} }
has(id) { has(id) {

View file

@ -64,7 +64,7 @@ export class ExtraFunction {
}, },
(params, feat) => { (params, feat) => {
return (...layerIds: string[]) => { return (...layerIds: string[]) => {
const result : {feat:any, overlap: number}[]= [] const result: { feat: any, overlap: number }[] = []
const bbox = BBox.get(feat) const bbox = BBox.get(feat)
@ -181,7 +181,7 @@ export class ExtraFunction {
} }
try { try {
const parsed = JSON.parse(value) const parsed = JSON.parse(value)
if(parsed === null){ if (parsed === null) {
return undefined; return undefined;
} }
return parsed; return parsed;

View file

@ -39,7 +39,7 @@ export default class SaveTileToLocalStorageActor {
} }
} }
public static poison(layers: string[], lon: number, lat: number) { public static poison(layers: string[], lon: number, lat: number) {
for (let z = 0; z < 25; z++) { for (let z = 0; z < 25; z++) {
const {x, y} = Tiles.embedded_tile(lat, lon, z) const {x, y} = Tiles.embedded_tile(lat, lon, z)

View file

@ -129,7 +129,7 @@ export default class FeaturePipeline {
// This will already contain the merged features for this tile. In other words, this will only be triggered once for every tile // This will already contain the merged features for this tile. In other words, this will only be triggered once for every tile
const srcFiltered = const srcFiltered =
new FilteringFeatureSource(state, src.tileIndex, new FilteringFeatureSource(state, src.tileIndex,
new ChangeGeometryApplicator(src, state.changes) new ChangeGeometryApplicator(src, state.changes)
) )
handleFeatureSource(srcFiltered) handleFeatureSource(srcFiltered)
@ -147,7 +147,7 @@ export default class FeaturePipeline {
this.freshnesses.set(id, new TileFreshnessCalculator()) this.freshnesses.set(id, new TileFreshnessCalculator())
if(id === "type_node"){ if (id === "type_node") {
// Handles by the 'FullNodeDatabaseSource' // Handles by the 'FullNodeDatabaseSource'
continue; continue;
} }
@ -227,14 +227,14 @@ export default class FeaturePipeline {
}) })
}) })
if(state.layoutToUse.trackAllNodes){ if (state.layoutToUse.trackAllNodes) {
const fullNodeDb = new FullNodeDatabaseSource( const fullNodeDb = new FullNodeDatabaseSource(
state.filteredLayers.data.filter(l => l.layerDef.id === "type_node")[0], state.filteredLayers.data.filter(l => l.layerDef.id === "type_node")[0],
tile => { tile => {
new RegisteringAllFromFeatureSourceActor(tile) new RegisteringAllFromFeatureSourceActor(tile)
perLayerHierarchy.get(tile.layer.layerDef.id).registerTile(tile) perLayerHierarchy.get(tile.layer.layerDef.id).registerTile(tile)
tile.features.addCallbackAndRunD(_ => self.newDataLoadedSignal.setData(tile)) tile.features.addCallbackAndRunD(_ => self.newDataLoadedSignal.setData(tile))
}) })
osmFeatureSource.rawDataHandlers.push((osmJson, tileId) => fullNodeDb.handleOsmJson(osmJson, tileId)) osmFeatureSource.rawDataHandlers.push((osmJson, tileId) => fullNodeDb.handleOsmJson(osmJson, tileId))
} }
@ -299,6 +299,34 @@ export default class FeaturePipeline {
} }
public GetAllFeaturesWithin(bbox: BBox): any[][] {
const self = this
const tiles = []
Array.from(this.perLayerHierarchy.keys())
.forEach(key => tiles.push(...self.GetFeaturesWithin(key, bbox)))
return tiles;
}
public GetFeaturesWithin(layerId: string, bbox: BBox): any[][] {
if (layerId === "*") {
return this.GetAllFeaturesWithin(bbox)
}
const requestedHierarchy = this.perLayerHierarchy.get(layerId)
if (requestedHierarchy === undefined) {
console.warn("Layer ", layerId, "is not defined. Try one of ", Array.from(this.perLayerHierarchy.keys()))
return undefined;
}
return TileHierarchyTools.getTiles(requestedHierarchy, bbox)
.filter(featureSource => featureSource.features?.data !== undefined)
.map(featureSource => featureSource.features.data.map(fs => fs.feature))
}
public GetTilesPerLayerWithin(bbox: BBox, handleTile: (tile: FeatureSourceForLayer & Tiled) => void) {
Array.from(this.perLayerHierarchy.values()).forEach(hierarchy => {
TileHierarchyTools.getTiles(hierarchy, bbox).forEach(handleTile)
})
}
private freshnessForVisibleLayers(z: number, x: number, y: number): Date { private freshnessForVisibleLayers(z: number, x: number, y: number): Date {
let oldestDate = undefined; let oldestDate = undefined;
for (const flayer of this.state.filteredLayers.data) { for (const flayer of this.state.filteredLayers.data) {
@ -438,32 +466,4 @@ export default class FeaturePipeline {
} }
public GetAllFeaturesWithin(bbox: BBox): any[][] {
const self = this
const tiles = []
Array.from(this.perLayerHierarchy.keys())
.forEach(key => tiles.push(...self.GetFeaturesWithin(key, bbox)))
return tiles;
}
public GetFeaturesWithin(layerId: string, bbox: BBox): any[][] {
if (layerId === "*") {
return this.GetAllFeaturesWithin(bbox)
}
const requestedHierarchy = this.perLayerHierarchy.get(layerId)
if (requestedHierarchy === undefined) {
console.warn("Layer ", layerId, "is not defined. Try one of ", Array.from(this.perLayerHierarchy.keys()))
return undefined;
}
return TileHierarchyTools.getTiles(requestedHierarchy, bbox)
.filter(featureSource => featureSource.features?.data !== undefined)
.map(featureSource => featureSource.features.data.map(fs => fs.feature))
}
public GetTilesPerLayerWithin(bbox: BBox, handleTile: (tile: FeatureSourceForLayer & Tiled) => void) {
Array.from(this.perLayerHierarchy.values()).forEach(hierarchy => {
TileHierarchyTools.getTiles(hierarchy, bbox).forEach(handleTile)
})
}
} }

View file

@ -1,5 +1,4 @@
import {UIEventSource} from "../UIEventSource"; import {UIEventSource} from "../UIEventSource";
import {Utils} from "../../Utils";
import FilteredLayer from "../../Models/FilteredLayer"; import FilteredLayer from "../../Models/FilteredLayer";
import {BBox} from "../BBox"; import {BBox} from "../BBox";
@ -19,7 +18,7 @@ export interface Tiled {
/** /**
* A feature source which only contains features for the defined layer * A feature source which only contains features for the defined layer
*/ */
export interface FeatureSourceForLayer extends FeatureSource{ export interface FeatureSourceForLayer extends FeatureSource {
readonly layer: FilteredLayer readonly layer: FilteredLayer
} }

View file

@ -14,9 +14,9 @@ export default class PerLayerFeatureSourceSplitter {
constructor(layers: UIEventSource<FilteredLayer[]>, constructor(layers: UIEventSource<FilteredLayer[]>,
handleLayerData: (source: FeatureSourceForLayer & Tiled) => void, handleLayerData: (source: FeatureSourceForLayer & Tiled) => void,
upstream: FeatureSource, upstream: FeatureSource,
options?:{ options?: {
tileIndex?: number, tileIndex?: number,
handleLeftovers?: (featuresWithoutLayer: any[]) => void handleLeftovers?: (featuresWithoutLayer: any[]) => void
}) { }) {
const knownLayers = new Map<string, FeatureSourceForLayer & Tiled>() const knownLayers = new Map<string, FeatureSourceForLayer & Tiled>()
@ -35,6 +35,7 @@ export default class PerLayerFeatureSourceSplitter {
const featuresPerLayer = new Map<string, { feature, freshness } []>(); const featuresPerLayer = new Map<string, { feature, freshness } []>();
const noLayerFound = [] const noLayerFound = []
function addTo(layer: FilteredLayer, feature: { feature, freshness }) { function addTo(layer: FilteredLayer, feature: { feature, freshness }) {
const id = layer.layerDef.id const id = layer.layerDef.id
const list = featuresPerLayer.get(id) const list = featuresPerLayer.get(id)
@ -82,7 +83,7 @@ export default class PerLayerFeatureSourceSplitter {
} }
// AT last, the leftovers are handled // AT last, the leftovers are handled
if(options?.handleLeftovers !== undefined && noLayerFound.length > 0){ if (options?.handleLeftovers !== undefined && noLayerFound.length > 0) {
options.handleLeftovers(noLayerFound) options.handleLeftovers(noLayerFound)
} }
} }

View file

@ -11,9 +11,9 @@ import {ChangeDescription, ChangeDescriptionTools} from "../../Osm/Actions/Chang
export default class ChangeGeometryApplicator implements FeatureSourceForLayer { export default class ChangeGeometryApplicator implements FeatureSourceForLayer {
public readonly features: UIEventSource<{ feature: any; freshness: Date }[]> = new UIEventSource<{ feature: any; freshness: Date }[]>([]); public readonly features: UIEventSource<{ feature: any; freshness: Date }[]> = new UIEventSource<{ feature: any; freshness: Date }[]>([]);
public readonly name: string; public readonly name: string;
public readonly layer: FilteredLayer
private readonly source: IndexedFeatureSource; private readonly source: IndexedFeatureSource;
private readonly changes: Changes; private readonly changes: Changes;
public readonly layer: FilteredLayer
constructor(source: (IndexedFeatureSource & FeatureSourceForLayer), changes: Changes) { constructor(source: (IndexedFeatureSource & FeatureSourceForLayer), changes: Changes) {
this.source = source; this.source = source;
@ -52,9 +52,9 @@ export default class ChangeGeometryApplicator implements FeatureSourceForLayer {
const changesPerId = new Map<string, ChangeDescription[]>() const changesPerId = new Map<string, ChangeDescription[]>()
for (const ch of changesToApply) { for (const ch of changesToApply) {
const key = ch.type + "/" + ch.id const key = ch.type + "/" + ch.id
if(changesPerId.has(key)){ if (changesPerId.has(key)) {
changesPerId.get(key).push(ch) changesPerId.get(key).push(ch)
}else{ } else {
changesPerId.set(key, [ch]) changesPerId.set(key, [ch])
} }
} }

View file

@ -5,7 +5,6 @@
import {UIEventSource} from "../../UIEventSource"; import {UIEventSource} from "../../UIEventSource";
import FeatureSource, {FeatureSourceForLayer, IndexedFeatureSource, Tiled} from "../FeatureSource"; import FeatureSource, {FeatureSourceForLayer, IndexedFeatureSource, Tiled} from "../FeatureSource";
import FilteredLayer from "../../../Models/FilteredLayer"; import FilteredLayer from "../../../Models/FilteredLayer";
import {Utils} from "../../../Utils";
import {Tiles} from "../../../Models/TileRange"; import {Tiles} from "../../../Models/TileRange";
import {BBox} from "../../BBox"; import {BBox} from "../../BBox";
@ -14,17 +13,17 @@ export default class FeatureSourceMerger implements FeatureSourceForLayer, Tiled
public features: UIEventSource<{ feature: any; freshness: Date }[]> = new UIEventSource<{ feature: any; freshness: Date }[]>([]); public features: UIEventSource<{ feature: any; freshness: Date }[]> = new UIEventSource<{ feature: any; freshness: Date }[]>([]);
public readonly name; public readonly name;
public readonly layer: FilteredLayer public readonly layer: FilteredLayer
private readonly _sources: UIEventSource<FeatureSource[]>;
public readonly tileIndex: number; public readonly tileIndex: number;
public readonly bbox: BBox; public readonly bbox: BBox;
public readonly containedIds: UIEventSource<Set<string>> = new UIEventSource<Set<string>>(new Set()) public readonly containedIds: UIEventSource<Set<string>> = new UIEventSource<Set<string>>(new Set())
private readonly _sources: UIEventSource<FeatureSource[]>;
constructor(layer: FilteredLayer, tileIndex: number, bbox: BBox, sources: UIEventSource<FeatureSource[]>) { constructor(layer: FilteredLayer, tileIndex: number, bbox: BBox, sources: UIEventSource<FeatureSource[]>) {
this.tileIndex = tileIndex; this.tileIndex = tileIndex;
this.bbox = bbox; this.bbox = bbox;
this._sources = sources; this._sources = sources;
this.layer = layer; this.layer = layer;
this.name = "FeatureSourceMerger("+layer.layerDef.id+", "+Tiles.tile_from_index(tileIndex).join(",")+")" this.name = "FeatureSourceMerger(" + layer.layerDef.id + ", " + Tiles.tile_from_index(tileIndex).join(",") + ")"
const self = this; const self = this;
const handledSources = new Set<FeatureSource>(); const handledSources = new Set<FeatureSource>();

View file

@ -18,6 +18,8 @@ export default class FilteringFeatureSource implements FeatureSourceForLayer, Ti
locationControl: UIEventSource<{ zoom: number }>; selectedElement: UIEventSource<any>, locationControl: UIEventSource<{ zoom: number }>; selectedElement: UIEventSource<any>,
allElements: ElementStorage allElements: ElementStorage
}; };
private readonly _alreadyRegistered = new Set<UIEventSource<any>>();
private readonly _is_dirty = new UIEventSource(false)
constructor( constructor(
state: { state: {
@ -55,24 +57,6 @@ export default class FilteringFeatureSource implements FeatureSourceForLayer, Ti
this.update(); this.update();
} }
private readonly _alreadyRegistered = new Set<UIEventSource<any>>();
private readonly _is_dirty = new UIEventSource(false)
private registerCallback(feature: any, layer: LayerConfig) {
const src = this.state.allElements.addOrGetElement(feature)
if (this._alreadyRegistered.has(src)) {
return
}
this._alreadyRegistered.add(src)
if (layer.isShown !== undefined) {
const self = this;
src.map(tags => layer.isShown?.GetRenderValue(tags, "yes").txt).addCallbackAndRunD(isShown => {
self._is_dirty.setData(true)
})
}
}
public update() { public update() {
const self = this; const self = this;
const layer = this.upstream.layer; const layer = this.upstream.layer;
@ -116,4 +100,19 @@ export default class FilteringFeatureSource implements FeatureSourceForLayer, Ti
this._is_dirty.setData(false) this._is_dirty.setData(false)
} }
private registerCallback(feature: any, layer: LayerConfig) {
const src = this.state.allElements.addOrGetElement(feature)
if (this._alreadyRegistered.has(src)) {
return
}
this._alreadyRegistered.add(src)
if (layer.isShown !== undefined) {
const self = this;
src.map(tags => layer.isShown?.GetRenderValue(tags, "yes").txt).addCallbackAndRunD(isShown => {
self._is_dirty.setData(true)
})
}
}
} }

View file

@ -15,12 +15,10 @@ export default class GeoJsonSource implements FeatureSourceForLayer, Tiled {
public readonly features: UIEventSource<{ feature: any; freshness: Date }[]>; public readonly features: UIEventSource<{ feature: any; freshness: Date }[]>;
public readonly name; public readonly name;
public readonly isOsmCache: boolean public readonly isOsmCache: boolean
private readonly seenids: Set<string> = new Set<string>()
public readonly layer: FilteredLayer; public readonly layer: FilteredLayer;
public readonly tileIndex public readonly tileIndex
public readonly bbox; public readonly bbox;
private readonly seenids: Set<string> = new Set<string>()
/** /**
* Only used if the actual source is a tiled geojson. * Only used if the actual source is a tiled geojson.
* A big feature might be contained in multiple tiles. * A big feature might be contained in multiple tiles.
@ -32,7 +30,7 @@ export default class GeoJsonSource implements FeatureSourceForLayer, Tiled {
public constructor(flayer: FilteredLayer, public constructor(flayer: FilteredLayer,
zxy?: [number, number, number], zxy?: [number, number, number],
options?: { options?: {
featureIdBlacklist?: UIEventSource<Set<string>> featureIdBlacklist?: UIEventSource<Set<string>>
}) { }) {
if (flayer.layerDef.source.geojsonZoomLevel !== undefined && zxy === undefined) { if (flayer.layerDef.source.geojsonZoomLevel !== undefined && zxy === undefined) {
@ -45,18 +43,18 @@ export default class GeoJsonSource implements FeatureSourceForLayer, Tiled {
if (zxy !== undefined) { if (zxy !== undefined) {
const [z, x, y] = zxy; const [z, x, y] = zxy;
let tile_bbox = BBox.fromTile(z, x, y) let tile_bbox = BBox.fromTile(z, x, y)
let bounds : { minLat: number, maxLat: number, minLon: number, maxLon: number } = tile_bbox let bounds: { minLat: number, maxLat: number, minLon: number, maxLon: number } = tile_bbox
if(this.layer.layerDef.source.mercatorCrs){ if (this.layer.layerDef.source.mercatorCrs) {
bounds = tile_bbox.toMercator() bounds = tile_bbox.toMercator()
} }
url = url url = url
.replace('{z}', "" + z) .replace('{z}', "" + z)
.replace('{x}', "" + x) .replace('{x}', "" + x)
.replace('{y}', "" + y) .replace('{y}', "" + y)
.replace('{y_min}',""+bounds.minLat) .replace('{y_min}', "" + bounds.minLat)
.replace('{y_max}',""+bounds.maxLat) .replace('{y_max}', "" + bounds.maxLat)
.replace('{x_min}',""+bounds.minLon) .replace('{x_min}', "" + bounds.minLon)
.replace('{x_max}',""+bounds.maxLon) .replace('{x_max}', "" + bounds.maxLon)
this.tileIndex = Tiles.tile_index(z, x, y) this.tileIndex = Tiles.tile_index(z, x, y)
this.bbox = BBox.fromTile(z, x, y) this.bbox = BBox.fromTile(z, x, y)
@ -78,11 +76,11 @@ export default class GeoJsonSource implements FeatureSourceForLayer, Tiled {
const self = this; const self = this;
Utils.downloadJson(url) Utils.downloadJson(url)
.then(json => { .then(json => {
if(json.features === undefined || json.features === null){ if (json.features === undefined || json.features === null) {
return; return;
} }
if(self.layer.layerDef.source.mercatorCrs){ if (self.layer.layerDef.source.mercatorCrs) {
json = GeoOperations.GeoJsonToWGS84(json) json = GeoOperations.GeoJsonToWGS84(json)
} }
@ -110,7 +108,7 @@ export default class GeoJsonSource implements FeatureSourceForLayer, Tiled {
} }
self.seenids.add(props.id) self.seenids.add(props.id)
if(self.featureIdBlacklist?.data?.has(props.id)){ if (self.featureIdBlacklist?.data?.has(props.id)) {
continue; continue;
} }
@ -122,7 +120,7 @@ export default class GeoJsonSource implements FeatureSourceForLayer, Tiled {
newFeatures.push({feature: feature, freshness: freshness}) newFeatures.push({feature: feature, freshness: freshness})
} }
if ( newFeatures.length == 0) { if (newFeatures.length == 0) {
return; return;
} }

View file

@ -53,7 +53,7 @@ export class NewGeometryFromChangesFeatureSource implements FeatureSource {
for (const kv of change.tags) { for (const kv of change.tags) {
tags[kv.k] = kv.v tags[kv.k] = kv.v
} }
tags["id"] = change.type+"/"+change.id tags["id"] = change.type + "/" + change.id
tags["_backend"] = State.state.osmConnection._oauth_config.url tags["_backend"] = State.state.osmConnection._oauth_config.url

View file

@ -6,17 +6,17 @@ import FeatureSource, {Tiled} from "../FeatureSource";
import {UIEventSource} from "../../UIEventSource"; import {UIEventSource} from "../../UIEventSource";
import {BBox} from "../../BBox"; import {BBox} from "../../BBox";
export default class RememberingSource implements FeatureSource , Tiled{ export default class RememberingSource implements FeatureSource, Tiled {
public readonly features: UIEventSource<{ feature: any, freshness: Date }[]>; public readonly features: UIEventSource<{ feature: any, freshness: Date }[]>;
public readonly name; public readonly name;
public readonly tileIndex : number public readonly tileIndex: number
public readonly bbox : BBox public readonly bbox: BBox
constructor(source: FeatureSource & Tiled) { constructor(source: FeatureSource & Tiled) {
const self = this; const self = this;
this.name = "RememberingSource of " + source.name; this.name = "RememberingSource of " + source.name;
this.tileIndex= source.tileIndex this.tileIndex = source.tileIndex
this.bbox = source.bbox; this.bbox = source.bbox;
const empty = []; const empty = [];

View file

@ -32,7 +32,7 @@ export default class RenderingMultiPlexerFeatureSource {
const withIndex: (any & { pointRenderingIndex: number | undefined, lineRenderingIndex: number | undefined })[] = []; const withIndex: (any & { pointRenderingIndex: number | undefined, lineRenderingIndex: number | undefined })[] = [];
function addAsPoint(feat, rendering, coordinate) { function addAsPoint(feat, rendering, coordinate) {
const patched = { const patched = {
...feat, ...feat,
pointRenderingIndex: rendering.index pointRenderingIndex: rendering.index

View file

@ -13,35 +13,35 @@ export default class TileFreshnessCalculator {
* @param tileId * @param tileId
* @param freshness * @param freshness
*/ */
public addTileLoad(tileId: number, freshness: Date){ public addTileLoad(tileId: number, freshness: Date) {
const existingFreshness = this.freshnessFor(...Tiles.tile_from_index(tileId)) const existingFreshness = this.freshnessFor(...Tiles.tile_from_index(tileId))
if(existingFreshness >= freshness){ if (existingFreshness >= freshness) {
return; return;
} }
this.freshnesses.set(tileId, freshness) this.freshnesses.set(tileId, freshness)
// Do we have freshness for the neighbouring tiles? If so, we can mark the tile above as loaded too! // Do we have freshness for the neighbouring tiles? If so, we can mark the tile above as loaded too!
let [z, x, y] = Tiles.tile_from_index(tileId) let [z, x, y] = Tiles.tile_from_index(tileId)
if(z === 0){ if (z === 0) {
return; return;
} }
x = x - (x % 2) // Make the tiles always even x = x - (x % 2) // Make the tiles always even
y = y - (y % 2) y = y - (y % 2)
const ul = this.freshnessFor(z, x, y)?.getTime() const ul = this.freshnessFor(z, x, y)?.getTime()
if(ul === undefined){ if (ul === undefined) {
return return
} }
const ur = this.freshnessFor(z, x + 1, y)?.getTime() const ur = this.freshnessFor(z, x + 1, y)?.getTime()
if(ur === undefined){ if (ur === undefined) {
return return
} }
const ll = this.freshnessFor(z, x, y + 1)?.getTime() const ll = this.freshnessFor(z, x, y + 1)?.getTime()
if(ll === undefined){ if (ll === undefined) {
return return
} }
const lr = this.freshnessFor(z, x + 1, y + 1)?.getTime() const lr = this.freshnessFor(z, x + 1, y + 1)?.getTime()
if(lr === undefined){ if (lr === undefined) {
return return
} }
@ -50,21 +50,21 @@ export default class TileFreshnessCalculator {
date.setTime(leastFresh) date.setTime(leastFresh)
this.addTileLoad( this.addTileLoad(
Tiles.tile_index(z - 1, Math.floor(x / 2), Math.floor(y / 2)), Tiles.tile_index(z - 1, Math.floor(x / 2), Math.floor(y / 2)),
date date
) )
} }
public freshnessFor(z: number, x: number, y:number): Date { public freshnessFor(z: number, x: number, y: number): Date {
if(z < 0){ if (z < 0) {
return undefined return undefined
} }
const tileId = Tiles.tile_index(z, x, y) const tileId = Tiles.tile_index(z, x, y)
if(this.freshnesses.has(tileId)) { if (this.freshnesses.has(tileId)) {
return this.freshnesses.get(tileId) return this.freshnesses.get(tileId)
} }
// recurse up // recurse up
return this.freshnessFor(z - 1, Math.floor(x /2), Math.floor(y / 2)) return this.freshnessFor(z - 1, Math.floor(x / 2), Math.floor(y / 2))
} }

View file

@ -9,9 +9,8 @@ import {Tiles} from "../../../Models/TileRange";
* A tiled source which dynamically loads the required tiles at a fixed zoom level * A tiled source which dynamically loads the required tiles at a fixed zoom level
*/ */
export default class DynamicTileSource implements TileHierarchy<FeatureSourceForLayer & Tiled> { export default class DynamicTileSource implements TileHierarchy<FeatureSourceForLayer & Tiled> {
private readonly _loadedTiles = new Set<number>();
public readonly loadedTiles: Map<number, FeatureSourceForLayer & Tiled>; public readonly loadedTiles: Map<number, FeatureSourceForLayer & Tiled>;
private readonly _loadedTiles = new Set<number>();
constructor( constructor(
layer: FilteredLayer, layer: FilteredLayer,
@ -24,7 +23,7 @@ export default class DynamicTileSource implements TileHierarchy<FeatureSourceFor
) { ) {
const self = this; const self = this;
this.loadedTiles = new Map<number,FeatureSourceForLayer & Tiled>() this.loadedTiles = new Map<number, FeatureSourceForLayer & Tiled>()
const neededTiles = state.locationControl.map( const neededTiles = state.locationControl.map(
location => { location => {
if (!layer.isDisplayed.data) { if (!layer.isDisplayed.data) {
@ -54,14 +53,14 @@ export default class DynamicTileSource implements TileHierarchy<FeatureSourceFor
, [layer.isDisplayed, state.leafletMap]).stabilized(250); , [layer.isDisplayed, state.leafletMap]).stabilized(250);
neededTiles.addCallbackAndRunD(neededIndexes => { neededTiles.addCallbackAndRunD(neededIndexes => {
console.log("Tiled geojson source ",layer.layerDef.id," needs", neededIndexes) console.log("Tiled geojson source ", layer.layerDef.id, " needs", neededIndexes)
if (neededIndexes === undefined) { if (neededIndexes === undefined) {
return; return;
} }
for (const neededIndex of neededIndexes) { for (const neededIndex of neededIndexes) {
self._loadedTiles.add(neededIndex) self._loadedTiles.add(neededIndex)
const src = constructTile(Tiles.tile_from_index(neededIndex)) const src = constructTile(Tiles.tile_from_index(neededIndex))
if(src !== undefined){ if (src !== undefined) {
self.loadedTiles.set(neededIndex, src) self.loadedTiles.set(neededIndex, src)
} }
} }

View file

@ -13,9 +13,10 @@ import {Or} from "../../Tags/Or";
import {TagsFilter} from "../../Tags/TagsFilter"; import {TagsFilter} from "../../Tags/TagsFilter";
export default class OsmFeatureSource { export default class OsmFeatureSource {
private readonly _backend: string;
public readonly isRunning: UIEventSource<boolean> = new UIEventSource<boolean>(false) public readonly isRunning: UIEventSource<boolean> = new UIEventSource<boolean>(false)
public readonly downloadedTiles = new Set<number>()
public rawDataHandlers: ((osmJson: any, tileId: number) => void)[] = []
private readonly _backend: string;
private readonly filteredLayers: UIEventSource<FilteredLayer[]>; private readonly filteredLayers: UIEventSource<FilteredLayer[]>;
private readonly handleTile: (fs: (FeatureSourceForLayer & Tiled)) => void; private readonly handleTile: (fs: (FeatureSourceForLayer & Tiled)) => void;
private isActive: UIEventSource<boolean>; private isActive: UIEventSource<boolean>;
@ -28,11 +29,8 @@ export default class OsmFeatureSource {
}, },
markTileVisited?: (tileId: number) => void markTileVisited?: (tileId: number) => void
}; };
public readonly downloadedTiles = new Set<number>()
private readonly allowedTags: TagsFilter; private readonly allowedTags: TagsFilter;
public rawDataHandlers: ((osmJson: any, tileId: number) => void)[] = []
constructor(options: { constructor(options: {
handleTile: (tile: FeatureSourceForLayer & Tiled) => void; handleTile: (tile: FeatureSourceForLayer & Tiled) => void;
isActive: UIEventSource<boolean>, isActive: UIEventSource<boolean>,
@ -57,7 +55,7 @@ export default class OsmFeatureSource {
neededTiles = neededTiles.filter(tile => !self.downloadedTiles.has(tile)) neededTiles = neededTiles.filter(tile => !self.downloadedTiles.has(tile))
if(neededTiles.length == 0){ if (neededTiles.length == 0) {
return; return;
} }
@ -73,7 +71,7 @@ export default class OsmFeatureSource {
} }
} catch (e) { } catch (e) {
console.error(e) console.error(e)
}finally { } finally {
console.log("Done") console.log("Done")
self.isRunning.setData(false) self.isRunning.setData(false)
} }

View file

@ -11,17 +11,14 @@ Currently, they are:
When the data enters from Overpass or from the OSM-API, they are first distributed per layer: When the data enters from Overpass or from the OSM-API, they are first distributed per layer:
OVERPASS | ---PerLayerFeatureSource---> FeatureSourceForLayer[] OVERPASS | ---PerLayerFeatureSource---> FeatureSourceForLayer[]
OSM | OSM |
The GeoJSon files (not tiled) are then added to this list The GeoJSon files (not tiled) are then added to this list
A single FeatureSourcePerLayer is then further handled by splitting it into a tile hierarchy. A single FeatureSourcePerLayer is then further handled by splitting it into a tile hierarchy.
In order to keep thins snappy, they are distributed over a tiled database per layer. In order to keep thins snappy, they are distributed over a tiled database per layer.
## Notes ## Notes
`cached-featuresbookcases` is the old key used `cahced-features{themeid}` and should be cleaned up `cached-featuresbookcases` is the old key used `cahced-features{themeid}` and should be cleaned up

View file

@ -8,9 +8,8 @@ import {BBox} from "../../BBox";
export class TileHierarchyMerger implements TileHierarchy<FeatureSourceForLayer & Tiled> { export class TileHierarchyMerger implements TileHierarchy<FeatureSourceForLayer & Tiled> {
public readonly loadedTiles: Map<number, FeatureSourceForLayer & Tiled> = new Map<number, FeatureSourceForLayer & Tiled>(); public readonly loadedTiles: Map<number, FeatureSourceForLayer & Tiled> = new Map<number, FeatureSourceForLayer & Tiled>();
private readonly sources: Map<number, UIEventSource<FeatureSource[]>> = new Map<number, UIEventSource<FeatureSource[]>>();
public readonly layer: FilteredLayer; public readonly layer: FilteredLayer;
private readonly sources: Map<number, UIEventSource<FeatureSource[]>> = new Map<number, UIEventSource<FeatureSource[]>>();
private _handleTile: (src: FeatureSourceForLayer & IndexedFeatureSource, index: number) => void; private _handleTile: (src: FeatureSourceForLayer & IndexedFeatureSource, index: number) => void;
constructor(layer: FilteredLayer, handleTile: (src: FeatureSourceForLayer & IndexedFeatureSource & Tiled, index: number) => void) { constructor(layer: FilteredLayer, handleTile: (src: FeatureSourceForLayer & IndexedFeatureSource & Tiled, index: number) => void) {
@ -24,7 +23,7 @@ export class TileHierarchyMerger implements TileHierarchy<FeatureSourceForLayer
* @param src * @param src
* @param index * @param index
*/ */
public registerTile(src: FeatureSource & Tiled) { public registerTile(src: FeatureSource & Tiled) {
const index = src.tileIndex const index = src.tileIndex
if (this.sources.has(index)) { if (this.sources.has(index)) {

View file

@ -1,6 +1,5 @@
import FeatureSource, {FeatureSourceForLayer, IndexedFeatureSource, Tiled} from "../FeatureSource"; import FeatureSource, {FeatureSourceForLayer, IndexedFeatureSource, Tiled} from "../FeatureSource";
import {UIEventSource} from "../../UIEventSource"; import {UIEventSource} from "../../UIEventSource";
import {Utils} from "../../../Utils";
import FilteredLayer from "../../../Models/FilteredLayer"; import FilteredLayer from "../../../Models/FilteredLayer";
import TileHierarchy from "./TileHierarchy"; import TileHierarchy from "./TileHierarchy";
import {Tiles} from "../../../Models/TileRange"; import {Tiles} from "../../../Models/TileRange";
@ -28,13 +27,13 @@ export default class TiledFeatureSource implements Tiled, IndexedFeatureSource,
public readonly containedIds: UIEventSource<Set<string>> public readonly containedIds: UIEventSource<Set<string>>
public readonly bbox: BBox; public readonly bbox: BBox;
public readonly tileIndex: number;
private upper_left: TiledFeatureSource private upper_left: TiledFeatureSource
private upper_right: TiledFeatureSource private upper_right: TiledFeatureSource
private lower_left: TiledFeatureSource private lower_left: TiledFeatureSource
private lower_right: TiledFeatureSource private lower_right: TiledFeatureSource
private readonly maxzoom: number; private readonly maxzoom: number;
private readonly options: TiledFeatureSourceOptions private readonly options: TiledFeatureSourceOptions
public readonly tileIndex: number;
private constructor(z: number, x: number, y: number, parent: TiledFeatureSource, options?: TiledFeatureSourceOptions) { private constructor(z: number, x: number, y: number, parent: TiledFeatureSource, options?: TiledFeatureSourceOptions) {
this.z = z; this.z = z;
@ -92,16 +91,16 @@ export default class TiledFeatureSource implements Tiled, IndexedFeatureSource,
return root; return root;
} }
private isSplitNeeded(featureCount: number){ private isSplitNeeded(featureCount: number) {
if(this.upper_left !== undefined){ if (this.upper_left !== undefined) {
// This tile has been split previously, so we keep on splitting // This tile has been split previously, so we keep on splitting
return true; return true;
} }
if(this.z >= this.maxzoom){ if (this.z >= this.maxzoom) {
// We are not allowed to split any further // We are not allowed to split any further
return false return false
} }
if(this.options.minZoomLevel !== undefined && this.z < this.options.minZoomLevel){ if (this.options.minZoomLevel !== undefined && this.z < this.options.minZoomLevel) {
// We must have at least this zoom level before we are allowed to start splitting // We must have at least this zoom level before we are allowed to start splitting
return true return true
} }
@ -155,7 +154,7 @@ export default class TiledFeatureSource implements Tiled, IndexedFeatureSource,
} else { } else {
overlapsboundary.push(feature) overlapsboundary.push(feature)
} }
}else if (this.options.minZoomLevel === undefined) { } else if (this.options.minZoomLevel === undefined) {
if (bbox.isContainedIn(this.upper_left.bbox)) { if (bbox.isContainedIn(this.upper_left.bbox)) {
ulf.push(feature) ulf.push(feature)
} else if (bbox.isContainedIn(this.upper_right.bbox)) { } else if (bbox.isContainedIn(this.upper_right.bbox)) {

View file

@ -13,44 +13,6 @@ export default class TiledFromLocalStorageSource implements TileHierarchy<Featur
private readonly handleFeatureSource: (src: FeatureSourceForLayer & Tiled, index: number) => void; private readonly handleFeatureSource: (src: FeatureSourceForLayer & Tiled, index: number) => void;
private readonly undefinedTiles: Set<number>; private readonly undefinedTiles: Set<number>;
public static GetFreshnesses(layerId: string): Map<number, Date> {
const prefix = SaveTileToLocalStorageActor.storageKey + "-" + layerId + "-"
const freshnesses = new Map<number, Date>()
for (const key of Object.keys(localStorage)) {
if (!(key.startsWith(prefix) && key.endsWith("-time"))) {
continue
}
const index = Number(key.substring(prefix.length, key.length - "-time".length))
const time = Number(localStorage.getItem(key))
const freshness = new Date()
freshness.setTime(time)
freshnesses.set(index, freshness)
}
return freshnesses
}
static cleanCacheForLayer(layer: LayerConfig) {
const now = new Date()
const prefix = SaveTileToLocalStorageActor.storageKey + "-" + layer.id + "-"
console.log("Cleaning tiles of ", prefix, "with max age",layer.maxAgeOfCache)
for (const key of Object.keys(localStorage)) {
if (!(key.startsWith(prefix) && key.endsWith("-time"))) {
continue
}
const index = Number(key.substring(prefix.length, key.length - "-time".length))
const time = Number(localStorage.getItem(key))
const timeDiff = (now.getTime() - time) / 1000
if(timeDiff >= layer.maxAgeOfCache){
const k = prefix+index;
localStorage.removeItem(k)
localStorage.removeItem(k+"-format")
localStorage.removeItem(k+"-time")
}
}
}
constructor(layer: FilteredLayer, constructor(layer: FilteredLayer,
handleFeatureSource: (src: FeatureSourceForLayer & Tiled, index: number) => void, handleFeatureSource: (src: FeatureSourceForLayer & Tiled, index: number) => void,
state: { state: {
@ -110,6 +72,43 @@ export default class TiledFromLocalStorageSource implements TileHierarchy<Featur
} }
public static GetFreshnesses(layerId: string): Map<number, Date> {
const prefix = SaveTileToLocalStorageActor.storageKey + "-" + layerId + "-"
const freshnesses = new Map<number, Date>()
for (const key of Object.keys(localStorage)) {
if (!(key.startsWith(prefix) && key.endsWith("-time"))) {
continue
}
const index = Number(key.substring(prefix.length, key.length - "-time".length))
const time = Number(localStorage.getItem(key))
const freshness = new Date()
freshness.setTime(time)
freshnesses.set(index, freshness)
}
return freshnesses
}
static cleanCacheForLayer(layer: LayerConfig) {
const now = new Date()
const prefix = SaveTileToLocalStorageActor.storageKey + "-" + layer.id + "-"
console.log("Cleaning tiles of ", prefix, "with max age", layer.maxAgeOfCache)
for (const key of Object.keys(localStorage)) {
if (!(key.startsWith(prefix) && key.endsWith("-time"))) {
continue
}
const index = Number(key.substring(prefix.length, key.length - "-time".length))
const time = Number(localStorage.getItem(key))
const timeDiff = (now.getTime() - time) / 1000
if (timeDiff >= layer.maxAgeOfCache) {
const k = prefix + index;
localStorage.removeItem(k)
localStorage.removeItem(k + "-format")
localStorage.removeItem(k + "-time")
}
}
}
private loadTile(neededIndex: number) { private loadTile(neededIndex: number) {
try { try {
const key = SaveTileToLocalStorageActor.storageKey + "-" + this.layer.layerDef.id + "-" + neededIndex const key = SaveTileToLocalStorageActor.storageKey + "-" + this.layer.layerDef.id + "-" + neededIndex

View file

@ -3,6 +3,9 @@ import {BBox} from "./BBox";
export class GeoOperations { export class GeoOperations {
private static readonly _earthRadius = 6378137;
private static readonly _originShift = 2 * Math.PI * GeoOperations._earthRadius / 2;
static surfaceAreaInSqMeters(feature: any) { static surfaceAreaInSqMeters(feature: any) {
return turf.area(feature); return turf.area(feature);
} }
@ -237,7 +240,7 @@ export class GeoOperations {
* @param point Point defined as [lon, lat] * @param point Point defined as [lon, lat]
*/ */
public static nearestPoint(way, point: [number, number]) { public static nearestPoint(way, point: [number, number]) {
if(way.geometry.type === "Polygon"){ if (way.geometry.type === "Polygon") {
way = {...way} way = {...way}
way.geometry = {...way.geometry} way.geometry = {...way.geometry}
way.geometry.type = "LineString" way.geometry.type = "LineString"
@ -292,10 +295,6 @@ export class GeoOperations {
return headerValuesOrdered.map(v => JSON.stringify(v)).join(",") + "\n" + lines.join("\n") return headerValuesOrdered.map(v => JSON.stringify(v)).join(",") + "\n" + lines.join("\n")
} }
private static readonly _earthRadius = 6378137;
private static readonly _originShift = 2 * Math.PI * GeoOperations._earthRadius / 2;
//Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913 //Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913
public static ConvertWgs84To900913(lonLat: [number, number]): [number, number] { public static ConvertWgs84To900913(lonLat: [number, number]): [number, number] {
const lon = lonLat[0]; const lon = lonLat[0];
@ -316,10 +315,35 @@ export class GeoOperations {
return [x, y]; return [x, y];
} }
public static GeoJsonToWGS84(geojson){ public static GeoJsonToWGS84(geojson) {
return turf.toWgs84(geojson) return turf.toWgs84(geojson)
} }
/**
* Tries to remove points which do not contribute much to the general outline.
* Points for which the angle is ~ 180° are removed
* @param coordinates
* @constructor
*/
public static SimplifyCoordinates(coordinates: [number, number][]) {
const newCoordinates = []
for (let i = 1; i < coordinates.length - 1; i++) {
const coordinate = coordinates[i];
const prev = coordinates[i - 1]
const next = coordinates[i + 1]
const b0 = turf.bearing(prev, coordinate, {final: true})
const b1 = turf.bearing(coordinate, next)
const diff = Math.abs(b1 - b0)
if (diff < 2) {
continue
}
newCoordinates.push(coordinate)
}
return newCoordinates
}
/** /**
* Calculates the intersection between two features. * Calculates the intersection between two features.
* Returns the length if intersecting a linestring and a (multi)polygon (in meters), returns a surface area (in m²) if intersecting two (multi)polygons * Returns the length if intersecting a linestring and a (multi)polygon (in meters), returns a surface area (in m²) if intersecting two (multi)polygons
@ -412,31 +436,6 @@ export class GeoOperations {
return undefined; return undefined;
} }
/**
* Tries to remove points which do not contribute much to the general outline.
* Points for which the angle is ~ 180° are removed
* @param coordinates
* @constructor
*/
public static SimplifyCoordinates(coordinates: [number, number][]){
const newCoordinates = []
for (let i = 1; i < coordinates.length - 1; i++){
const coordinate = coordinates[i];
const prev = coordinates[i - 1]
const next = coordinates[i + 1]
const b0 = turf.bearing(prev, coordinate, {final: true})
const b1 = turf.bearing(coordinate, next)
const diff = Math.abs(b1 - b0)
if(diff < 2){
continue
}
newCoordinates.push(coordinate)
}
return newCoordinates
}
} }

View file

@ -32,7 +32,7 @@ export default class AllImageProviders {
return undefined; return undefined;
} }
const cacheKey = tags.data.id+tagKey const cacheKey = tags.data.id + tagKey
const cached = this._cache.get(cacheKey) const cached = this._cache.get(cacheKey)
if (cached !== undefined) { if (cached !== undefined) {
return cached return cached
@ -45,7 +45,7 @@ export default class AllImageProviders {
for (const imageProvider of AllImageProviders.ImageAttributionSource) { for (const imageProvider of AllImageProviders.ImageAttributionSource) {
let prefixes = imageProvider.defaultKeyPrefixes let prefixes = imageProvider.defaultKeyPrefixes
if(tagKey !== undefined){ if (tagKey !== undefined) {
prefixes = tagKey prefixes = tagKey
} }
@ -54,11 +54,11 @@ export default class AllImageProviders {
}) })
allSources.push(singleSource) allSources.push(singleSource)
singleSource.addCallbackAndRunD(_ => { singleSource.addCallbackAndRunD(_ => {
const all : ProvidedImage[] = [].concat(...allSources.map(source => source.data)) const all: ProvidedImage[] = [].concat(...allSources.map(source => source.data))
const uniq = [] const uniq = []
const seen = new Set<string>() const seen = new Set<string>()
for (const img of all) { for (const img of all) {
if(seen.has(img.url)){ if (seen.has(img.url)) {
continue continue
} }
seen.add(img.url) seen.add(img.url)

View file

@ -10,20 +10,15 @@ export default class GenericImageProvider extends ImageProvider {
this._valuePrefixBlacklist = valuePrefixBlacklist; this._valuePrefixBlacklist = valuePrefixBlacklist;
} }
protected DownloadAttribution(url: string) {
return undefined
}
async ExtractUrls(key: string, value: string): Promise<Promise<ProvidedImage>[]> { async ExtractUrls(key: string, value: string): Promise<Promise<ProvidedImage>[]> {
if (this._valuePrefixBlacklist.some(prefix => value.startsWith(prefix))) { if (this._valuePrefixBlacklist.some(prefix => value.startsWith(prefix))) {
return [] return []
} }
try{ try {
new URL(value) new URL(value)
}catch (_){ } catch (_) {
// Not a valid URL // Not a valid URL
return [] return []
} }
@ -39,5 +34,9 @@ export default class GenericImageProvider extends ImageProvider {
return undefined; return undefined;
} }
protected DownloadAttribution(url: string) {
return undefined
}
} }

View file

@ -27,8 +27,6 @@ export default abstract class ImageProvider {
public abstract SourceIcon(backlinkSource?: string): BaseUIElement; public abstract SourceIcon(backlinkSource?: string): BaseUIElement;
protected abstract DownloadAttribution(url: string): Promise<LicenseInfo>;
/** /**
* Given a properies object, maps it onto _all_ the available pictures for this imageProvider * Given a properies object, maps it onto _all_ the available pictures for this imageProvider
*/ */
@ -77,4 +75,6 @@ export default abstract class ImageProvider {
public abstract ExtractUrls(key: string, value: string): Promise<Promise<ProvidedImage>[]>; public abstract ExtractUrls(key: string, value: string): Promise<Promise<ProvidedImage>[]>;
protected abstract DownloadAttribution(url: string): Promise<LicenseInfo>;
} }

View file

@ -8,9 +8,8 @@ import {LicenseInfo} from "./LicenseInfo";
export class Imgur extends ImageProvider { export class Imgur extends ImageProvider {
public static readonly defaultValuePrefix = ["https://i.imgur.com"] public static readonly defaultValuePrefix = ["https://i.imgur.com"]
public readonly defaultKeyPrefixes: string[] = ["image"];
public static readonly singleton = new Imgur(); public static readonly singleton = new Imgur();
public readonly defaultKeyPrefixes: string[] = ["image"];
private constructor() { private constructor() {
super(); super();
@ -89,6 +88,17 @@ export class Imgur extends ImageProvider {
return undefined; return undefined;
} }
public async ExtractUrls(key: string, value: string): Promise<Promise<ProvidedImage>[]> {
if (Imgur.defaultValuePrefix.some(prefix => value.startsWith(prefix))) {
return [Promise.resolve({
url: value,
key: key,
provider: this
})]
}
return []
}
protected DownloadAttribution: (url: string) => Promise<LicenseInfo> = async (url: string) => { protected DownloadAttribution: (url: string) => Promise<LicenseInfo> = async (url: string) => {
const hash = url.substr("https://i.imgur.com/".length).split(".jpg")[0]; const hash = url.substr("https://i.imgur.com/".length).split(".jpg")[0];
@ -112,16 +122,5 @@ export class Imgur extends ImageProvider {
return licenseInfo return licenseInfo
} }
public async ExtractUrls(key: string, value: string): Promise<Promise<ProvidedImage>[]> {
if (Imgur.defaultValuePrefix.some(prefix => value.startsWith(prefix))) {
return [Promise.resolve({
url: value,
key: key,
provider: this
})]
}
return []
}
} }

View file

@ -6,9 +6,8 @@ export default class ImgurUploader {
public readonly queue: UIEventSource<string[]> = new UIEventSource<string[]>([]); public readonly queue: UIEventSource<string[]> = new UIEventSource<string[]>([]);
public readonly failed: UIEventSource<string[]> = new UIEventSource<string[]>([]); public readonly failed: UIEventSource<string[]> = new UIEventSource<string[]>([]);
public readonly success: UIEventSource<string[]> = new UIEventSource<string[]>([]); public readonly success: UIEventSource<string[]> = new UIEventSource<string[]>([]);
private readonly _handleSuccessUrl: (string) => void;
public maxFileSizeInMegabytes = 10; public maxFileSizeInMegabytes = 10;
private readonly _handleSuccessUrl: (string) => void;
constructor(handleSuccessUrl: (string) => void) { constructor(handleSuccessUrl: (string) => void) {
this._handleSuccessUrl = handleSuccessUrl; this._handleSuccessUrl = handleSuccessUrl;

View file

@ -7,11 +7,10 @@ import Constants from "../../Models/Constants";
export class Mapillary extends ImageProvider { export class Mapillary extends ImageProvider {
defaultKeyPrefixes = ["mapillary","image"]
public static readonly singleton = new Mapillary(); public static readonly singleton = new Mapillary();
private static readonly valuePrefix = "https://a.mapillary.com" private static readonly valuePrefix = "https://a.mapillary.com"
public static readonly valuePrefixes = [Mapillary.valuePrefix, "http://mapillary.com","https://mapillary.com","http://www.mapillary.com","https://www.mapillary.com"] public static readonly valuePrefixes = [Mapillary.valuePrefix, "http://mapillary.com", "https://mapillary.com", "http://www.mapillary.com", "https://www.mapillary.com"]
defaultKeyPrefixes = ["mapillary", "image"]
private static ExtractKeyFromURL(value: string, failIfNoMath = false): { private static ExtractKeyFromURL(value: string, failIfNoMath = false): {
key: string, key: string,
@ -44,7 +43,7 @@ export class Mapillary extends ImageProvider {
return {key: matchApi[1]}; return {key: matchApi[1]};
} }
if(failIfNoMath){ if (failIfNoMath) {
return undefined; return undefined;
} }
@ -59,33 +58,6 @@ export class Mapillary extends ImageProvider {
return [this.PrepareUrlAsync(key, value)] return [this.PrepareUrlAsync(key, value)]
} }
private async PrepareUrlAsync(key: string, value: string): Promise<ProvidedImage> {
const failIfNoMatch = key.indexOf("mapillary") < 0
const keyV = Mapillary.ExtractKeyFromURL(value, failIfNoMatch)
if(keyV === undefined){
return undefined;
}
if (!keyV.isApiv4) {
const url = `https://images.mapillary.com/${keyV.key}/thumb-640.jpg?client_id=${Constants.mapillary_client_token_v3}`
return {
url: url,
provider: this,
key: key
}
} else {
const mapillaryId = keyV.key;
const metadataUrl = 'https://graph.mapillary.com/' + mapillaryId + '?fields=thumb_1024_url&&access_token=' + Constants.mapillary_client_token_v4;
const response = await Utils.downloadJson(metadataUrl)
const url = <string> response["thumb_1024_url"];
return {
url: url,
provider: this,
key: key
}
}
}
protected async DownloadAttribution(url: string): Promise<LicenseInfo> { protected async DownloadAttribution(url: string): Promise<LicenseInfo> {
const keyV = Mapillary.ExtractKeyFromURL(url) const keyV = Mapillary.ExtractKeyFromURL(url)
@ -110,4 +82,31 @@ export class Mapillary extends ImageProvider {
return license return license
} }
private async PrepareUrlAsync(key: string, value: string): Promise<ProvidedImage> {
const failIfNoMatch = key.indexOf("mapillary") < 0
const keyV = Mapillary.ExtractKeyFromURL(value, failIfNoMatch)
if (keyV === undefined) {
return undefined;
}
if (!keyV.isApiv4) {
const url = `https://images.mapillary.com/${keyV.key}/thumb-640.jpg?client_id=${Constants.mapillary_client_token_v3}`
return {
url: url,
provider: this,
key: key
}
} else {
const mapillaryId = keyV.key;
const metadataUrl = 'https://graph.mapillary.com/' + mapillaryId + '?fields=thumb_1024_url&&access_token=' + Constants.mapillary_client_token_v4;
const response = await Utils.downloadJson(metadataUrl)
const url = <string>response["thumb_1024_url"];
return {
url: url,
provider: this,
key: key
}
}
}
} }

View file

@ -1,4 +1,3 @@
import {Utils} from "../../Utils";
import ImageProvider, {ProvidedImage} from "./ImageProvider"; import ImageProvider, {ProvidedImage} from "./ImageProvider";
import BaseUIElement from "../../UI/BaseUIElement"; import BaseUIElement from "../../UI/BaseUIElement";
import Svg from "../../Svg"; import Svg from "../../Svg";
@ -7,10 +6,6 @@ import Wikidata from "../Web/Wikidata";
export class WikidataImageProvider extends ImageProvider { export class WikidataImageProvider extends ImageProvider {
public SourceIcon(backlinkSource?: string): BaseUIElement {
throw Svg.wikidata_svg();
}
public static readonly singleton = new WikidataImageProvider() public static readonly singleton = new WikidataImageProvider()
public readonly defaultKeyPrefixes = ["wikidata"] public readonly defaultKeyPrefixes = ["wikidata"]
@ -18,17 +13,17 @@ export class WikidataImageProvider extends ImageProvider {
super() super()
} }
protected DownloadAttribution(url: string): Promise<any> { public SourceIcon(backlinkSource?: string): BaseUIElement {
throw new Error("Method not implemented; shouldn't be needed!"); throw Svg.wikidata_svg();
} }
public async ExtractUrls(key: string, value: string): Promise<Promise<ProvidedImage>[]> { public async ExtractUrls(key: string, value: string): Promise<Promise<ProvidedImage>[]> {
const entity = await Wikidata.LoadWikidataEntryAsync(value) const entity = await Wikidata.LoadWikidataEntryAsync(value)
if(entity === undefined){ if (entity === undefined) {
return [] return []
} }
const allImages : Promise<ProvidedImage>[] = [] const allImages: Promise<ProvidedImage>[] = []
// P18 is the claim 'depicted in this image' // P18 is the claim 'depicted in this image'
for (const img of Array.from(entity.claims.get("P18") ?? [])) { for (const img of Array.from(entity.claims.get("P18") ?? [])) {
const promises = await WikimediaImageProvider.singleton.ExtractUrls(undefined, img) const promises = await WikimediaImageProvider.singleton.ExtractUrls(undefined, img)
@ -36,8 +31,8 @@ export class WikidataImageProvider extends ImageProvider {
} }
// P373 is 'commons category' // P373 is 'commons category'
for (let cat of Array.from(entity.claims.get("P373") ?? [])) { for (let cat of Array.from(entity.claims.get("P373") ?? [])) {
if(!cat.startsWith("Category:")){ if (!cat.startsWith("Category:")) {
cat = "Category:"+cat cat = "Category:" + cat
} }
const promises = await WikimediaImageProvider.singleton.ExtractUrls(undefined, cat) const promises = await WikimediaImageProvider.singleton.ExtractUrls(undefined, cat)
allImages.push(...promises) allImages.push(...promises)
@ -45,10 +40,14 @@ export class WikidataImageProvider extends ImageProvider {
const commons = entity.commons const commons = entity.commons
if (commons !== undefined && (commons.startsWith("Category:") || commons.startsWith("File:"))) { if (commons !== undefined && (commons.startsWith("Category:") || commons.startsWith("File:"))) {
const promises = await WikimediaImageProvider.singleton.ExtractUrls(undefined , commons) const promises = await WikimediaImageProvider.singleton.ExtractUrls(undefined, commons)
allImages.push(...promises) allImages.push(...promises)
} }
return allImages return allImages
} }
protected DownloadAttribution(url: string): Promise<any> {
throw new Error("Method not implemented; shouldn't be needed!");
}
} }

View file

@ -12,10 +12,10 @@ import Wikimedia from "../Web/Wikimedia";
export class WikimediaImageProvider extends ImageProvider { export class WikimediaImageProvider extends ImageProvider {
private readonly commons_key = "wikimedia_commons"
public readonly defaultKeyPrefixes = [this.commons_key,"image"]
public static readonly singleton = new WikimediaImageProvider(); public static readonly singleton = new WikimediaImageProvider();
public static readonly commonsPrefixes = ["https://commons.wikimedia.org/wiki/", "https://upload.wikimedia.org", "File:"] public static readonly commonsPrefixes = ["https://commons.wikimedia.org/wiki/", "https://upload.wikimedia.org", "File:"]
private readonly commons_key = "wikimedia_commons"
public readonly defaultKeyPrefixes = [this.commons_key, "image"]
private constructor() { private constructor() {
super(); super();
@ -30,6 +30,40 @@ export class WikimediaImageProvider extends ImageProvider {
} }
private static PrepareUrl(value: string): string {
if (value.toLowerCase().startsWith("https://commons.wikimedia.org/wiki/")) {
return value;
}
return (`https://commons.wikimedia.org/wiki/Special:FilePath/${encodeURIComponent(value)}?width=500&height=400`)
}
private static startsWithCommonsPrefix(value: string): boolean {
return WikimediaImageProvider.commonsPrefixes.some(prefix => value.startsWith(prefix))
}
private static removeCommonsPrefix(value: string): string {
if (value.startsWith("https://upload.wikimedia.org/")) {
value = value.substring(value.lastIndexOf("/") + 1)
value = decodeURIComponent(value)
if (!value.startsWith("File:")) {
value = "File:" + value
}
return value;
}
for (const prefix of WikimediaImageProvider.commonsPrefixes) {
if (value.startsWith(prefix)) {
let part = value.substr(prefix.length)
if (prefix.startsWith("http")) {
part = decodeURIComponent(part)
}
return part
}
}
return value;
}
SourceIcon(backlink: string): BaseUIElement { SourceIcon(backlink: string): BaseUIElement {
const img = Svg.wikimedia_commons_white_svg() const img = Svg.wikimedia_commons_white_svg()
.SetStyle("width:2em;height: 2em"); .SetStyle("width:2em;height: 2em");
@ -44,12 +78,38 @@ export class WikimediaImageProvider extends ImageProvider {
} }
private static PrepareUrl(value: string): string { public PrepUrl(value: string): ProvidedImage {
const hasCommonsPrefix = WikimediaImageProvider.startsWithCommonsPrefix(value)
value = WikimediaImageProvider.removeCommonsPrefix(value)
if (value.toLowerCase().startsWith("https://commons.wikimedia.org/wiki/")) { if (value.startsWith("File:")) {
return value; return this.UrlForImage(value)
} }
return (`https://commons.wikimedia.org/wiki/Special:FilePath/${encodeURIComponent(value)}?width=500&height=400`)
// We do a last effort and assume this is a file
return this.UrlForImage("File:" + value)
}
public async ExtractUrls(key: string, value: string): Promise<Promise<ProvidedImage>[]> {
const hasCommonsPrefix = WikimediaImageProvider.startsWithCommonsPrefix(value)
if (key !== undefined && key !== this.commons_key && !hasCommonsPrefix) {
return []
}
value = WikimediaImageProvider.removeCommonsPrefix(value)
if (value.startsWith("Category:")) {
const urls = await Wikimedia.GetCategoryContents(value)
return urls.filter(url => url.startsWith("File:")).map(image => Promise.resolve(this.UrlForImage(image)))
}
if (value.startsWith("File:")) {
return [Promise.resolve(this.UrlForImage(value))]
}
if (value.startsWith("http")) {
// PRobably an error
return []
}
// We do a last effort and assume this is a file
return [Promise.resolve(this.UrlForImage("File:" + value))]
} }
protected async DownloadAttribution(filename: string): Promise<LicenseInfo> { protected async DownloadAttribution(filename: string): Promise<LicenseInfo> {
@ -66,21 +126,21 @@ export class WikimediaImageProvider extends ImageProvider {
const data = await Utils.downloadJson(url) const data = await Utils.downloadJson(url)
const licenseInfo = new LicenseInfo(); const licenseInfo = new LicenseInfo();
const pageInfo = data.query.pages[-1] const pageInfo = data.query.pages[-1]
if(pageInfo === undefined){ if (pageInfo === undefined) {
return undefined; return undefined;
} }
const license = (pageInfo.imageinfo ?? [])[0]?.extmetadata; const license = (pageInfo.imageinfo ?? [])[0]?.extmetadata;
if (license === undefined) { if (license === undefined) {
console.warn("The file", filename ,"has no usable metedata or license attached... Please fix the license info file yourself!") console.warn("The file", filename, "has no usable metedata or license attached... Please fix the license info file yourself!")
return undefined; return undefined;
} }
let title = pageInfo.title let title = pageInfo.title
if(title.startsWith("File:")){ if (title.startsWith("File:")) {
title= title.substr("File:".length) title = title.substr("File:".length)
} }
if(title.endsWith(".jpg") || title.endsWith(".png")){ if (title.endsWith(".jpg") || title.endsWith(".png")) {
title = title.substring(0, title.length - 4) title = title.substring(0, title.length - 4)
} }
@ -104,66 +164,6 @@ export class WikimediaImageProvider extends ImageProvider {
return {url: WikimediaImageProvider.PrepareUrl(image), key: undefined, provider: this} return {url: WikimediaImageProvider.PrepareUrl(image), key: undefined, provider: this}
} }
private static startsWithCommonsPrefix(value: string): boolean{
return WikimediaImageProvider.commonsPrefixes.some(prefix => value.startsWith(prefix))
}
private static removeCommonsPrefix(value: string): string{
if(value.startsWith("https://upload.wikimedia.org/")){
value = value.substring(value.lastIndexOf("/") + 1)
value = decodeURIComponent(value)
if(!value.startsWith("File:")){
value = "File:"+value
}
return value;
}
for (const prefix of WikimediaImageProvider.commonsPrefixes) {
if(value.startsWith(prefix)){
let part = value.substr(prefix.length)
if(prefix.startsWith("http")){
part = decodeURIComponent(part)
}
return part
}
}
return value;
}
public PrepUrl(value: string): ProvidedImage {
const hasCommonsPrefix = WikimediaImageProvider.startsWithCommonsPrefix(value)
value = WikimediaImageProvider.removeCommonsPrefix(value)
if (value.startsWith("File:")) {
return this.UrlForImage(value)
}
// We do a last effort and assume this is a file
return this.UrlForImage("File:" + value)
}
public async ExtractUrls(key: string, value: string): Promise<Promise<ProvidedImage>[]> {
const hasCommonsPrefix = WikimediaImageProvider.startsWithCommonsPrefix(value)
if(key !== undefined && key !== this.commons_key && !hasCommonsPrefix){
return []
}
value = WikimediaImageProvider.removeCommonsPrefix(value)
if (value.startsWith("Category:")) {
const urls = await Wikimedia.GetCategoryContents(value)
return urls.filter(url => url.startsWith("File:")).map(image => Promise.resolve(this.UrlForImage(image)))
}
if (value.startsWith("File:")) {
return [Promise.resolve(this.UrlForImage(value))]
}
if (value.startsWith("http")) {
// PRobably an error
return []
}
// We do a last effort and assume this is a file
return [Promise.resolve(this.UrlForImage("File:" + value))]
}
} }

View file

@ -64,12 +64,12 @@ export default class MetaTagging {
continue continue
} }
if(metatag.isLazy){ if (metatag.isLazy) {
somethingChanged = true; somethingChanged = true;
metatag.applyMetaTagsOnFeature(feature, freshness, layer) metatag.applyMetaTagsOnFeature(feature, freshness, layer)
}else{ } else {
const newValueAdded = metatag.applyMetaTagsOnFeature(feature, freshness, layer) const newValueAdded = metatag.applyMetaTagsOnFeature(feature, freshness, layer)
@ -147,7 +147,8 @@ export default class MetaTagging {
} }
} }
}} ) }
})
} }

View file

@ -16,7 +16,7 @@ export interface ChangeDescription {
/** /**
* The type of the change * The type of the change
*/ */
changeType: "answer" | "create" | "split" | "delete" | "move" | "import" | string | null changeType: "answer" | "create" | "split" | "delete" | "move" | "import" | string | null
/** /**
* THe motivation for the change, e.g. 'deleted because does not exist anymore' * THe motivation for the change, e.g. 'deleted because does not exist anymore'
*/ */
@ -65,9 +65,9 @@ export interface ChangeDescription {
doDelete?: boolean doDelete?: boolean
} }
export class ChangeDescriptionTools{ export class ChangeDescriptionTools {
public static getGeojsonGeometry(change: ChangeDescription): any{ public static getGeojsonGeometry(change: ChangeDescription): any {
switch (change.type) { switch (change.type) {
case "node": case "node":
const n = new OsmNode(change.id) const n = new OsmNode(change.id)

View file

@ -7,7 +7,7 @@ export default class ChangeTagAction extends OsmChangeAction {
private readonly _elementId: string; private readonly _elementId: string;
private readonly _tagsFilter: TagsFilter; private readonly _tagsFilter: TagsFilter;
private readonly _currentTags: any; private readonly _currentTags: any;
private readonly _meta: {theme: string, changeType: string}; private readonly _meta: { theme: string, changeType: string };
constructor(elementId: string, tagsFilter: TagsFilter, currentTags: any, meta: { constructor(elementId: string, tagsFilter: TagsFilter, currentTags: any, meta: {
theme: string, theme: string,
@ -31,11 +31,11 @@ export default class ChangeTagAction extends OsmChangeAction {
return undefined; return undefined;
} }
if (value === undefined || value === null) { if (value === undefined || value === null) {
console.error("Invalid value for ", key,":", value); console.error("Invalid value for ", key, ":", value);
return undefined; return undefined;
} }
if(typeof value !== "string"){ if (typeof value !== "string") {
console.error("Invalid value for ", key, "as it is not a string:", value) console.error("Invalid value for ", key, "as it is not a string:", value)
return undefined; return undefined;
} }
@ -53,7 +53,7 @@ export default class ChangeTagAction extends OsmChangeAction {
const type = typeId[0] const type = typeId[0]
const id = Number(typeId [1]) const id = Number(typeId [1])
return [{ return [{
type: <"node"|"way"|"relation"> type, type: <"node" | "way" | "relation">type,
id: id, id: id,
tags: changedTags, tags: changedTags,
meta: this._meta meta: this._meta

View file

@ -156,7 +156,7 @@ export default class CreateNewNodeAction extends OsmChangeAction {
private setElementId(id: number) { private setElementId(id: number) {
this.newElementIdNumber = id; this.newElementIdNumber = id;
this.newElementId = "node/"+id this.newElementId = "node/" + id
if (!this._reusePreviouslyCreatedPoint) { if (!this._reusePreviouslyCreatedPoint) {
return return
} }

View file

@ -166,14 +166,15 @@ export default class CreateWayWithPointReuseAction extends OsmChangeAction {
nodeIdsToUse.push({ nodeIdsToUse.push({
lat, lon, lat, lon,
nodeId : newNodeAction.newElementIdNumber}) nodeId: newNodeAction.newElementIdNumber
})
continue continue
} }
const closestPoint = info.closebyNodes[0] const closestPoint = info.closebyNodes[0]
const id = Number(closestPoint.node.properties.id.split("/")[1]) const id = Number(closestPoint.node.properties.id.split("/")[1])
if(closestPoint.config.mode === "move_osm_point"){ if (closestPoint.config.mode === "move_osm_point") {
allChanges.push({ allChanges.push({
type: "node", type: "node",
id, id,

View file

@ -10,6 +10,7 @@ export interface RelationSplitInput {
originalNodes: number[], originalNodes: number[],
allWaysNodesInOrder: number[][] allWaysNodesInOrder: number[][]
} }
abstract class AbstractRelationSplitHandler extends OsmChangeAction { abstract class AbstractRelationSplitHandler extends OsmChangeAction {
protected readonly _input: RelationSplitInput; protected readonly _input: RelationSplitInput;
protected readonly _theme: string; protected readonly _theme: string;
@ -57,11 +58,11 @@ export default class RelationSplitHandler extends AbstractRelationSplitHandler {
} }
async CreateChangeDescriptions(changes: Changes): Promise<ChangeDescription[]> { async CreateChangeDescriptions(changes: Changes): Promise<ChangeDescription[]> {
if(this._input.relation.tags["type"] === "restriction"){ if (this._input.relation.tags["type"] === "restriction") {
// This is a turn restriction // This is a turn restriction
return new TurnRestrictionRSH(this._input, this._theme).CreateChangeDescriptions(changes) return new TurnRestrictionRSH(this._input, this._theme).CreateChangeDescriptions(changes)
} }
return new InPlaceReplacedmentRTSH(this._input, this._theme).CreateChangeDescriptions(changes) return new InPlaceReplacedmentRTSH(this._input, this._theme).CreateChangeDescriptions(changes)
} }
@ -80,12 +81,12 @@ export class TurnRestrictionRSH extends AbstractRelationSplitHandler {
const selfMembers = members.filter(m => m.type === "way" && m.ref === this._input.originalWayId) const selfMembers = members.filter(m => m.type === "way" && m.ref === this._input.originalWayId)
if(selfMembers.length > 1){ if (selfMembers.length > 1) {
console.warn("Detected a turn restriction where this way has multiple occurances. This is an error") console.warn("Detected a turn restriction where this way has multiple occurances. This is an error")
} }
const selfMember = selfMembers[0] const selfMember = selfMembers[0]
if(selfMember.role === "via"){ if (selfMember.role === "via") {
// A via way can be replaced in place // A via way can be replaced in place
return new InPlaceReplacedmentRTSH(this._input, this._theme).CreateChangeDescriptions(changes); return new InPlaceReplacedmentRTSH(this._input, this._theme).CreateChangeDescriptions(changes);
} }
@ -94,39 +95,42 @@ export class TurnRestrictionRSH extends AbstractRelationSplitHandler {
// We have to keep only the way with a common point with the rest of the relation // We have to keep only the way with a common point with the rest of the relation
// Let's figure out which member is neighbouring our way // Let's figure out which member is neighbouring our way
let commonStartPoint : number = await this.targetNodeAt(members.indexOf(selfMember), true) let commonStartPoint: number = await this.targetNodeAt(members.indexOf(selfMember), true)
let commonEndPoint : number = await this.targetNodeAt(members.indexOf(selfMember), false) let commonEndPoint: number = await this.targetNodeAt(members.indexOf(selfMember), false)
// In normal circumstances, only one of those should be defined // In normal circumstances, only one of those should be defined
let commonPoint = commonStartPoint ?? commonEndPoint let commonPoint = commonStartPoint ?? commonEndPoint
// Let's select the way to keep // Let's select the way to keep
const idToKeep : {id: number} = this._input.allWaysNodesInOrder.map((nodes, i) => ({nodes: nodes, id: this._input.allWayIdsInOrder[i]})) const idToKeep: { id: number } = this._input.allWaysNodesInOrder.map((nodes, i) => ({
nodes: nodes,
id: this._input.allWayIdsInOrder[i]
}))
.filter(nodesId => { .filter(nodesId => {
const nds = nodesId.nodes const nds = nodesId.nodes
return nds[0] == commonPoint || nds[nds.length - 1] == commonPoint return nds[0] == commonPoint || nds[nds.length - 1] == commonPoint
})[0] })[0]
if(idToKeep === undefined){ if (idToKeep === undefined) {
console.error("No common point found, this was a broken turn restriction!", relation.id) console.error("No common point found, this was a broken turn restriction!", relation.id)
return [] return []
} }
const originalWayId = this._input.originalWayId const originalWayId = this._input.originalWayId
if(idToKeep.id === originalWayId){ if (idToKeep.id === originalWayId) {
console.log("Turn_restriction fixer: the original ID can be kept, nothing to do") console.log("Turn_restriction fixer: the original ID can be kept, nothing to do")
return [] return []
} }
const newMembers : { const newMembers: {
ref:number, ref: number,
type:"way" | "node" | "relation", type: "way" | "node" | "relation",
role:string role: string
} [] = relation.members.map(m => { } [] = relation.members.map(m => {
if(m.type === "way" && m.ref === originalWayId){ if (m.type === "way" && m.ref === originalWayId) {
return { return {
ref: idToKeep.id, ref: idToKeep.id,
type:"way", type: "way",
role: m.role role: m.role
} }
} }
@ -184,8 +188,8 @@ export class InPlaceReplacedmentRTSH extends AbstractRelationSplitHandler {
const nodeIdBefore = await this.targetNodeAt(i - 1, false) const nodeIdBefore = await this.targetNodeAt(i - 1, false)
const nodeIdAfter = await this.targetNodeAt(i + 1, true) const nodeIdAfter = await this.targetNodeAt(i + 1, true)
const firstNodeMatches = nodeIdBefore === undefined || nodeIdBefore === firstNode const firstNodeMatches = nodeIdBefore === undefined || nodeIdBefore === firstNode
const lastNodeMatches =nodeIdAfter === undefined || nodeIdAfter === lastNode const lastNodeMatches = nodeIdAfter === undefined || nodeIdAfter === lastNode
if (firstNodeMatches && lastNodeMatches) { if (firstNodeMatches && lastNodeMatches) {
// We have a classic situation, forward situation // We have a classic situation, forward situation
@ -200,10 +204,10 @@ export class InPlaceReplacedmentRTSH extends AbstractRelationSplitHandler {
} }
const firstNodeMatchesRev = nodeIdBefore === undefined || nodeIdBefore === lastNode const firstNodeMatchesRev = nodeIdBefore === undefined || nodeIdBefore === lastNode
const lastNodeMatchesRev =nodeIdAfter === undefined || nodeIdAfter === firstNode const lastNodeMatchesRev = nodeIdAfter === undefined || nodeIdAfter === firstNode
if (firstNodeMatchesRev || lastNodeMatchesRev) { if (firstNodeMatchesRev || lastNodeMatchesRev) {
// We (probably) have a reversed situation, backward situation // We (probably) have a reversed situation, backward situation
for (let i1 = this._input.allWayIdsInOrder.length - 1; i1 >= 0; i1--){ for (let i1 = this._input.allWayIdsInOrder.length - 1; i1 >= 0; i1--) {
// Iterate BACKWARDS // Iterate BACKWARDS
const wId = this._input.allWayIdsInOrder[i1]; const wId = this._input.allWayIdsInOrder[i1];
newMembers.push({ newMembers.push({
@ -231,7 +235,7 @@ export class InPlaceReplacedmentRTSH extends AbstractRelationSplitHandler {
id: relation.id, id: relation.id,
type: "relation", type: "relation",
changes: {members: newMembers}, changes: {members: newMembers},
meta:{ meta: {
changeType: "relation-fix", changeType: "relation-fix",
theme: this._theme theme: this._theme
} }

View file

@ -77,9 +77,9 @@ export default class ReplaceGeometryAction extends OsmChangeAction {
public async getPreview(): Promise<FeatureSource> { public async getPreview(): Promise<FeatureSource> {
const {closestIds, allNodesById} = await this.GetClosestIds(); const {closestIds, allNodesById} = await this.GetClosestIds();
console.log("Generating preview, identicals are ", ) console.log("Generating preview, identicals are ",)
const preview = closestIds.map((newId, i) => { const preview = closestIds.map((newId, i) => {
if(this.identicalTo[i] !== undefined){ if (this.identicalTo[i] !== undefined) {
return undefined return undefined
} }
@ -123,7 +123,7 @@ export default class ReplaceGeometryAction extends OsmChangeAction {
const {closestIds, osmWay} = await this.GetClosestIds() const {closestIds, osmWay} = await this.GetClosestIds()
for (let i = 0; i < closestIds.length; i++) { for (let i = 0; i < closestIds.length; i++) {
if(this.identicalTo[i] !== undefined){ if (this.identicalTo[i] !== undefined) {
const j = this.identicalTo[i] const j = this.identicalTo[i]
actualIdsToUse.push(actualIdsToUse[j]) actualIdsToUse.push(actualIdsToUse[j])
continue continue
@ -221,7 +221,7 @@ export default class ReplaceGeometryAction extends OsmChangeAction {
const closestIds = [] const closestIds = []
const distances = [] const distances = []
for (let i = 0; i < this.targetCoordinates.length; i++){ for (let i = 0; i < this.targetCoordinates.length; i++) {
const target = this.targetCoordinates[i]; const target = this.targetCoordinates[i];
let closestDistance = undefined let closestDistance = undefined
let closestId = undefined; let closestId = undefined;
@ -240,15 +240,15 @@ export default class ReplaceGeometryAction extends OsmChangeAction {
// Next step: every closestId can only occur once in the list // Next step: every closestId can only occur once in the list
// We skip the ones which are identical // We skip the ones which are identical
console.log("Erasing double ids") console.log("Erasing double ids")
for (let i = 0; i < closestIds.length; i++) { for (let i = 0; i < closestIds.length; i++) {
if(this.identicalTo[i] !== undefined){ if (this.identicalTo[i] !== undefined) {
closestIds[i] = closestIds[this.identicalTo[i]] closestIds[i] = closestIds[this.identicalTo[i]]
continue continue
} }
const closestId = closestIds[i] const closestId = closestIds[i]
for (let j = i + 1; j < closestIds.length; j++) { for (let j = i + 1; j < closestIds.length; j++) {
if(this.identicalTo[j] !== undefined){ if (this.identicalTo[j] !== undefined) {
continue continue
} }
const otherClosestId = closestIds[j] const otherClosestId = closestIds[j]

View file

@ -25,7 +25,7 @@ export default class SplitAction extends OsmChangeAction {
* @param meta * @param meta
* @param toleranceInMeters: if a splitpoint closer then this amount of meters to an existing point, the existing point will be used to split the line instead of a new point * @param toleranceInMeters: if a splitpoint closer then this amount of meters to an existing point, the existing point will be used to split the line instead of a new point
*/ */
constructor(wayId: string, splitPointCoordinates: [number, number][], meta: {theme: string}, toleranceInMeters = 5) { constructor(wayId: string, splitPointCoordinates: [number, number][], meta: { theme: string }, toleranceInMeters = 5) {
super() super()
this.wayId = wayId; this.wayId = wayId;
this._splitPointsCoordinates = splitPointCoordinates this._splitPointsCoordinates = splitPointCoordinates
@ -51,7 +51,7 @@ export default class SplitAction extends OsmChangeAction {
} }
async CreateChangeDescriptions(changes: Changes): Promise<ChangeDescription[]> { async CreateChangeDescriptions(changes: Changes): Promise<ChangeDescription[]> {
const originalElement = <OsmWay> await OsmObject.DownloadObjectAsync(this.wayId) const originalElement = <OsmWay>await OsmObject.DownloadObjectAsync(this.wayId)
const originalNodes = originalElement.nodes; const originalNodes = originalElement.nodes;
// First, calculate splitpoints and remove points close to one another // First, calculate splitpoints and remove points close to one another
@ -180,7 +180,7 @@ export default class SplitAction extends OsmChangeAction {
private CalculateSplitCoordinates(osmWay: OsmWay, toleranceInM = 5): SplitInfo[] { private CalculateSplitCoordinates(osmWay: OsmWay, toleranceInM = 5): SplitInfo[] {
const wayGeoJson = osmWay.asGeoJson() const wayGeoJson = osmWay.asGeoJson()
// Should be [lon, lat][] // Should be [lon, lat][]
const originalPoints : [number, number][] = osmWay.coordinates.map(c => [c[1], c[0]]) const originalPoints: [number, number][] = osmWay.coordinates.map(c => [c[1], c[0]])
const allPoints: { const allPoints: {
// lon, lat // lon, lat
coordinates: [number, number], coordinates: [number, number],
@ -242,7 +242,7 @@ export default class SplitAction extends OsmChangeAction {
const distToNext = nextPoint.location - point.location const distToNext = nextPoint.location - point.location
const distToPrev = point.location - prevPoint.location const distToPrev = point.location - prevPoint.location
if(distToNext * 1000 > toleranceInM && distToPrev * 1000 > toleranceInM){ if (distToNext * 1000 > toleranceInM && distToPrev * 1000 > toleranceInM) {
// Both are too far away to mark them as the split point // Both are too far away to mark them as the split point
continue; continue;
} }
@ -252,7 +252,7 @@ export default class SplitAction extends OsmChangeAction {
closest = prevPoint closest = prevPoint
} }
// Ok, we have a closest point! // Ok, we have a closest point!
if(closest.originalIndex === 0 || closest.originalIndex === originalPoints.length){ if (closest.originalIndex === 0 || closest.originalIndex === originalPoints.length) {
// We can not split on the first or last points... // We can not split on the first or last points...
continue continue
} }

View file

@ -53,61 +53,6 @@ export class ChangesetHandler {
} }
} }
private handleIdRewrite(node: any, type: string): [string, string] {
const oldId = parseInt(node.attributes.old_id.value);
if (node.attributes.new_id === undefined) {
// We just removed this point!
const element = this.allElements.getEventSourceById("node/" + oldId);
element.data._deleted = "yes"
element.ping();
return;
}
const newId = parseInt(node.attributes.new_id.value);
const result: [string, string] = [type + "/" + oldId, type + "/" + newId]
if (!(oldId !== undefined && newId !== undefined &&
!isNaN(oldId) && !isNaN(newId))) {
return undefined;
}
if (oldId == newId) {
return undefined;
}
console.log("Rewriting id: ", type + "/" + oldId, "-->", type + "/" + newId);
const element = this.allElements.getEventSourceById("node/" + oldId);
if(element === undefined){
// Element to rewrite not found, probably a node or relation that is not rendered
return undefined
}
element.data.id = type + "/" + newId;
this.allElements.addElementById(type + "/" + newId, element);
this.allElements.ContainingFeatures.set(type + "/" + newId, this.allElements.ContainingFeatures.get(type + "/" + oldId))
element.ping();
return result;
}
private parseUploadChangesetResponse(response: XMLDocument): void {
const nodes = response.getElementsByTagName("node");
const mappings = new Map<string, string>()
// @ts-ignore
for (const node of nodes) {
const mapping = this.handleIdRewrite(node, "node")
if (mapping !== undefined) {
mappings.set(mapping[0], mapping[1])
}
}
const ways = response.getElementsByTagName("way");
// @ts-ignore
for (const way of ways) {
const mapping = this.handleIdRewrite(way, "way")
if (mapping !== undefined) {
mappings.set(mapping[0], mapping[1])
}
}
this.changes.registerIdRewrites(mappings)
}
/** /**
* The full logic to upload a change to one or more elements. * The full logic to upload a change to one or more elements.
* *
@ -207,6 +152,60 @@ export class ChangesetHandler {
} }
} }
private handleIdRewrite(node: any, type: string): [string, string] {
const oldId = parseInt(node.attributes.old_id.value);
if (node.attributes.new_id === undefined) {
// We just removed this point!
const element = this.allElements.getEventSourceById("node/" + oldId);
element.data._deleted = "yes"
element.ping();
return;
}
const newId = parseInt(node.attributes.new_id.value);
const result: [string, string] = [type + "/" + oldId, type + "/" + newId]
if (!(oldId !== undefined && newId !== undefined &&
!isNaN(oldId) && !isNaN(newId))) {
return undefined;
}
if (oldId == newId) {
return undefined;
}
console.log("Rewriting id: ", type + "/" + oldId, "-->", type + "/" + newId);
const element = this.allElements.getEventSourceById("node/" + oldId);
if (element === undefined) {
// Element to rewrite not found, probably a node or relation that is not rendered
return undefined
}
element.data.id = type + "/" + newId;
this.allElements.addElementById(type + "/" + newId, element);
this.allElements.ContainingFeatures.set(type + "/" + newId, this.allElements.ContainingFeatures.get(type + "/" + oldId))
element.ping();
return result;
}
private parseUploadChangesetResponse(response: XMLDocument): void {
const nodes = response.getElementsByTagName("node");
const mappings = new Map<string, string>()
// @ts-ignore
for (const node of nodes) {
const mapping = this.handleIdRewrite(node, "node")
if (mapping !== undefined) {
mappings.set(mapping[0], mapping[1])
}
}
const ways = response.getElementsByTagName("way");
// @ts-ignore
for (const way of ways) {
const mapping = this.handleIdRewrite(way, "way")
if (mapping !== undefined) {
mappings.set(mapping[0], mapping[1])
}
}
this.changes.registerIdRewrites(mappings)
}
private async CloseChangeset(changesetId: number = undefined): Promise<void> { private async CloseChangeset(changesetId: number = undefined): Promise<void> {
const self = this const self = this

View file

@ -50,26 +50,28 @@ export class OsmConnection {
_dryRun: boolean; _dryRun: boolean;
public preferencesHandler: OsmPreferences; public preferencesHandler: OsmPreferences;
public changesetHandler: ChangesetHandler; public changesetHandler: ChangesetHandler;
private fakeUser: boolean;
private _onLoggedIn: ((userDetails: UserDetails) => void)[] = [];
private readonly _iframeMode: Boolean | boolean;
private readonly _singlePage: boolean;
public readonly _oauth_config: { public readonly _oauth_config: {
oauth_consumer_key: string, oauth_consumer_key: string,
oauth_secret: string, oauth_secret: string,
url: string url: string
}; };
private fakeUser: boolean;
private _onLoggedIn: ((userDetails: UserDetails) => void)[] = [];
private readonly _iframeMode: Boolean | boolean;
private readonly _singlePage: boolean;
private isChecking = false; private isChecking = false;
constructor(options:{dryRun?: false | boolean, constructor(options: {
fakeUser?: false | boolean, dryRun?: false | boolean,
allElements: ElementStorage, fakeUser?: false | boolean,
changes: Changes, allElements: ElementStorage,
oauth_token?: UIEventSource<string>, changes: Changes,
// Used to keep multiple changesets open and to write to the correct changeset oauth_token?: UIEventSource<string>,
layoutName: string, // Used to keep multiple changesets open and to write to the correct changeset
singlePage?: boolean, layoutName: string,
osmConfiguration?: "osm" | "osm-test" } singlePage?: boolean,
osmConfiguration?: "osm" | "osm-test"
}
) { ) {
this.fakeUser = options.fakeUser ?? false; this.fakeUser = options.fakeUser ?? false;
this._singlePage = options.singlePage ?? true; this._singlePage = options.singlePage ?? true;
@ -79,7 +81,7 @@ export class OsmConnection {
this._iframeMode = Utils.runningFromConsole ? false : window !== window.top; this._iframeMode = Utils.runningFromConsole ? false : window !== window.top;
this.userDetails = new UIEventSource<UserDetails>(new UserDetails(this._oauth_config.url), "userDetails"); this.userDetails = new UIEventSource<UserDetails>(new UserDetails(this._oauth_config.url), "userDetails");
this.userDetails.data.dryRun = (options.dryRun ?? false) || (options.fakeUser ?? false) ; this.userDetails.data.dryRun = (options.dryRun ?? false) || (options.fakeUser ?? false);
if (options.fakeUser) { if (options.fakeUser) {
const ud = this.userDetails.data; const ud = this.userDetails.data;
ud.csCount = 5678 ud.csCount = 5678
@ -112,7 +114,7 @@ export class OsmConnection {
self.AttemptLogin(); self.AttemptLogin();
}, this.auth); }, this.auth);
options. oauth_token.setData(undefined); options.oauth_token.setData(undefined);
} }
if (this.auth.authenticated()) { if (this.auth.authenticated()) {

View file

@ -84,10 +84,10 @@ export abstract class OsmObject {
const parsed = OsmObject.ParseObjects(rawData.elements); const parsed = OsmObject.ParseObjects(rawData.elements);
// Lets fetch the object we need // Lets fetch the object we need
for (const osmObject of parsed) { for (const osmObject of parsed) {
if(osmObject.type !== type){ if (osmObject.type !== type) {
continue; continue;
} }
if(osmObject.id !== idN){ if (osmObject.id !== idN) {
continue continue
} }
// Found the one! // Found the one!
@ -170,41 +170,6 @@ export abstract class OsmObject {
const elements: any[] = data.elements; const elements: any[] = data.elements;
return OsmObject.ParseObjects(elements); return OsmObject.ParseObjects(elements);
} }
protected static isPolygon(tags: any): boolean {
for (const tagsKey in tags) {
if (!tags.hasOwnProperty(tagsKey)) {
continue
}
const polyGuide = OsmObject.polygonFeatures.get(tagsKey)
if (polyGuide === undefined) {
continue
}
if ((polyGuide.values === null)) {
// We match all
return !polyGuide.blacklist
}
// is the key contained?
return polyGuide.values.has(tags[tagsKey])
}
}
private static constructPolygonFeatures(): Map<string, { values: Set<string>, blacklist: boolean }> {
const result = new Map<string, { values: Set<string>, blacklist: boolean }>();
for (const polygonFeature of polygon_features) {
const key = polygonFeature.key;
if (polygonFeature.polygon === "all") {
result.set(key, {values: null, blacklist: false})
continue
}
const blacklist = polygonFeature.polygon === "blacklist"
result.set(key, {values: new Set<string>(polygonFeature.values), blacklist: blacklist})
}
return result;
}
public static ParseObjects(elements: any[]): OsmObject[] { public static ParseObjects(elements: any[]): OsmObject[] {
const objects: OsmObject[] = []; const objects: OsmObject[] = [];
@ -242,6 +207,42 @@ export abstract class OsmObject {
return objects; return objects;
} }
protected static isPolygon(tags: any): boolean {
for (const tagsKey in tags) {
if (!tags.hasOwnProperty(tagsKey)) {
continue
}
const polyGuide = OsmObject.polygonFeatures.get(tagsKey)
if (polyGuide === undefined) {
continue
}
if ((polyGuide.values === null)) {
// We match all
return !polyGuide.blacklist
}
// is the key contained?
return polyGuide.values.has(tags[tagsKey])
}
}
private static constructPolygonFeatures(): Map<string, { values: Set<string>, blacklist: boolean }> {
const result = new Map<string, { values: Set<string>, blacklist: boolean }>();
for (const polygonFeature of polygon_features) {
const key = polygonFeature.key;
if (polygonFeature.polygon === "all") {
result.set(key, {values: null, blacklist: false})
continue
}
const blacklist = polygonFeature.polygon === "blacklist"
result.set(key, {values: new Set<string>(polygonFeature.values), blacklist: blacklist})
}
return result;
}
// The centerpoint of the feature, as [lat, lon] // The centerpoint of the feature, as [lat, lon]
public abstract centerpoint(): [number, number]; public abstract centerpoint(): [number, number];

View file

@ -47,8 +47,8 @@ export class Overpass {
console.warn("Timeout or other runtime error while querying overpass", json.remark); console.warn("Timeout or other runtime error while querying overpass", json.remark);
throw `Runtime error (timeout or similar)${json.remark}` throw `Runtime error (timeout or similar)${json.remark}`
} }
if(json.elements.length === 0){ if (json.elements.length === 0) {
console.warn("No features for" ,json) console.warn("No features for", json)
} }
self._relationTracker.RegisterRelations(json) self._relationTracker.RegisterRelations(json)

View file

@ -1,4 +1,3 @@
import State from "../../State";
import {UIEventSource} from "../UIEventSource"; import {UIEventSource} from "../UIEventSource";
export interface Relation { export interface Relation {
@ -21,10 +20,6 @@ export default class RelationsTracker {
constructor() { constructor() {
} }
public RegisterRelations(overpassJson: any): void {
this.UpdateMembershipTable(RelationsTracker.GetRelationElements(overpassJson))
}
/** /**
* Gets an overview of the relations - except for multipolygons. We don't care about those * Gets an overview of the relations - except for multipolygons. We don't care about those
* @param overpassJson * @param overpassJson
@ -39,6 +34,10 @@ export default class RelationsTracker {
return relations return relations
} }
public RegisterRelations(overpassJson: any): void {
this.UpdateMembershipTable(RelationsTracker.GetRelationElements(overpassJson))
}
/** /**
* Build a mapping of {memberId --> {role in relation, id of relation} } * Build a mapping of {memberId --> {role in relation, id of relation} }
* @param relations * @param relations

View file

@ -49,6 +49,8 @@ export default class SimpleMetaTagger {
return true; return true;
} }
) )
public static readonly lazyTags: string[] = [].concat(...SimpleMetaTagger.metatags.filter(tagger => tagger.isLazy)
.map(tagger => tagger.keys));
private static latlon = new SimpleMetaTagger({ private static latlon = new SimpleMetaTagger({
keys: ["_lat", "_lon"], keys: ["_lat", "_lon"],
doc: "The latitude and longitude of the point (or centerpoint in the case of a way/area)" doc: "The latitude and longitude of the point (or centerpoint in the case of a way/area)"
@ -78,83 +80,6 @@ export default class SimpleMetaTagger {
return true; return true;
} }
) )
/**
* Edits the given object to rewrite 'both'-tagging into a 'left-right' tagging scheme.
* These changes are performed in-place.
*
* Returns 'true' is at least one change has been made
* @param tags
*/
public static removeBothTagging(tags: any): boolean{
let somethingChanged = false
/**
* Sets the key onto the properties (but doesn't overwrite if already existing)
*/
function set(k, value) {
if (tags[k] === undefined || tags[k] === "") {
tags[k] = value
somethingChanged = true
}
}
if (tags["sidewalk"]) {
const v = tags["sidewalk"]
switch (v) {
case "none":
case "no":
set("sidewalk:left", "no");
set("sidewalk:right", "no");
break
case "both":
set("sidewalk:left", "yes");
set("sidewalk:right", "yes");
break;
case "left":
set("sidewalk:left", "yes");
set("sidewalk:right", "no");
break;
case "right":
set("sidewalk:left", "no");
set("sidewalk:right", "yes");
break;
default:
set("sidewalk:left", v);
set("sidewalk:right", v);
break;
}
delete tags["sidewalk"]
somethingChanged = true
}
const regex = /\([^:]*\):both:\(.*\)/
for (const key in tags) {
const v = tags[key]
if (key.endsWith(":both")) {
const strippedKey = key.substring(0, key.length - ":both".length)
set(strippedKey + ":left", v)
set(strippedKey + ":right", v)
delete tags[key]
continue
}
const match = key.match(regex)
if (match !== null) {
const strippedKey = match[1]
const property = match[1]
set(strippedKey + ":left:" + property, v)
set(strippedKey + ":right:" + property, v)
console.log("Left-right rewritten " + key)
delete tags[key]
}
}
return somethingChanged
}
private static noBothButLeftRight = new SimpleMetaTagger( private static noBothButLeftRight = new SimpleMetaTagger(
{ {
keys: ["sidewalk:left", "sidewalk:right", "generic_key:left:property", "generic_key:right:property"], keys: ["sidewalk:left", "sidewalk:right", "generic_key:left:property", "generic_key:right:property"],
@ -164,7 +89,7 @@ export default class SimpleMetaTagger {
}, },
((feature, state, layer) => { ((feature, state, layer) => {
if(!layer.lineRendering.some(lr => lr.leftRightSensitive)){ if (!layer.lineRendering.some(lr => lr.leftRightSensitive)) {
return; return;
} }
@ -451,9 +376,6 @@ export default class SimpleMetaTagger {
SimpleMetaTagger.noBothButLeftRight SimpleMetaTagger.noBothButLeftRight
]; ];
public static readonly lazyTags: string[] = [].concat(...SimpleMetaTagger.metatags.filter(tagger => tagger.isLazy)
.map(tagger => tagger.keys));
public readonly keys: string[]; public readonly keys: string[];
public readonly doc: string; public readonly doc: string;
public readonly isLazy: boolean; public readonly isLazy: boolean;
@ -481,6 +403,83 @@ export default class SimpleMetaTagger {
} }
} }
/**
* Edits the given object to rewrite 'both'-tagging into a 'left-right' tagging scheme.
* These changes are performed in-place.
*
* Returns 'true' is at least one change has been made
* @param tags
*/
public static removeBothTagging(tags: any): boolean {
let somethingChanged = false
/**
* Sets the key onto the properties (but doesn't overwrite if already existing)
*/
function set(k, value) {
if (tags[k] === undefined || tags[k] === "") {
tags[k] = value
somethingChanged = true
}
}
if (tags["sidewalk"]) {
const v = tags["sidewalk"]
switch (v) {
case "none":
case "no":
set("sidewalk:left", "no");
set("sidewalk:right", "no");
break
case "both":
set("sidewalk:left", "yes");
set("sidewalk:right", "yes");
break;
case "left":
set("sidewalk:left", "yes");
set("sidewalk:right", "no");
break;
case "right":
set("sidewalk:left", "no");
set("sidewalk:right", "yes");
break;
default:
set("sidewalk:left", v);
set("sidewalk:right", v);
break;
}
delete tags["sidewalk"]
somethingChanged = true
}
const regex = /\([^:]*\):both:\(.*\)/
for (const key in tags) {
const v = tags[key]
if (key.endsWith(":both")) {
const strippedKey = key.substring(0, key.length - ":both".length)
set(strippedKey + ":left", v)
set(strippedKey + ":right", v)
delete tags[key]
continue
}
const match = key.match(regex)
if (match !== null) {
const strippedKey = match[1]
const property = match[1]
set(strippedKey + ":left:" + property, v)
set(strippedKey + ":right:" + property, v)
console.log("Left-right rewritten " + key)
delete tags[key]
}
}
return somethingChanged
}
public static HelpText(): BaseUIElement { public static HelpText(): BaseUIElement {
const subElements: (string | BaseUIElement)[] = [ const subElements: (string | BaseUIElement)[] = [
new Combine([ new Combine([

View file

@ -146,7 +146,7 @@ export default class FeatureSwitchState {
this.featureSwitchIsTesting = QueryParameters.GetBooleanQueryParameter( this.featureSwitchIsTesting = QueryParameters.GetBooleanQueryParameter(
"test", "test",
""+testingDefaultValue, "" + testingDefaultValue,
"If true, 'dryrun' mode is activated. The app will behave as normal, except that changes to OSM will be printed onto the console instead of actually uploaded to osm.org" "If true, 'dryrun' mode is activated. The app will behave as normal, except that changes to OSM will be printed onto the console instead of actually uploaded to osm.org"
) )

View file

@ -14,7 +14,6 @@ import {QueryParameters} from "../Web/QueryParameters";
import * as personal from "../../assets/themes/personal/personal.json"; import * as personal from "../../assets/themes/personal/personal.json";
import FilterConfig from "../../Models/ThemeConfig/FilterConfig"; import FilterConfig from "../../Models/ThemeConfig/FilterConfig";
import ShowOverlayLayer from "../../UI/ShowDataLayer/ShowOverlayLayer"; import ShowOverlayLayer from "../../UI/ShowDataLayer/ShowOverlayLayer";
import {Coord} from "@turf/turf";
/** /**
* Contains all the leaflet-map related state * Contains all the leaflet-map related state
@ -123,7 +122,21 @@ export default class MapState extends UserRelatedState {
this.AddAllOverlaysToMap(this.leafletMap) this.AddAllOverlaysToMap(this.leafletMap)
} }
public AddAllOverlaysToMap(leafletMap: UIEventSource<any>) {
const initialized = new Set()
for (const overlayToggle of this.overlayToggles) {
new ShowOverlayLayer(overlayToggle.config, leafletMap, overlayToggle.isDisplayed)
initialized.add(overlayToggle.config)
}
for (const tileLayerSource of this.layoutToUse.tileLayerSources) {
if (initialized.has(tileLayerSource)) {
continue
}
new ShowOverlayLayer(tileLayerSource, leafletMap)
}
}
private lockBounds() { private lockBounds() {
const layout = this.layoutToUse; const layout = this.layoutToUse;
@ -201,21 +214,5 @@ export default class MapState extends UserRelatedState {
return new UIEventSource<FilteredLayer[]>(flayers); return new UIEventSource<FilteredLayer[]>(flayers);
} }
public AddAllOverlaysToMap(leafletMap: UIEventSource<any>) {
const initialized = new Set()
for (const overlayToggle of this.overlayToggles) {
new ShowOverlayLayer(overlayToggle.config, leafletMap, overlayToggle.isDisplayed)
initialized.add(overlayToggle.config)
}
for (const tileLayerSource of this.layoutToUse.tileLayerSources) {
if (initialized.has(tileLayerSource)) {
continue
}
new ShowOverlayLayer(tileLayerSource, leafletMap)
}
}
} }

View file

@ -64,7 +64,7 @@ export default class UserRelatedState extends ElementsState {
if (layoutToUse?.hideFromOverview) { if (layoutToUse?.hideFromOverview) {
this.osmConnection.isLoggedIn.addCallbackAndRunD(loggedIn => { this.osmConnection.isLoggedIn.addCallbackAndRunD(loggedIn => {
if(loggedIn){ if (loggedIn) {
this.osmConnection this.osmConnection
.GetPreference("hidden-theme-" + layoutToUse?.id + "-enabled") .GetPreference("hidden-theme-" + layoutToUse?.id + "-enabled")
.setData("true"); .setData("true");
@ -129,7 +129,7 @@ export default class UserRelatedState extends ElementsState {
} }
return [home.lon, home.lat] return [home.lon, home.lat]
})).map(homeLonLat => { })).map(homeLonLat => {
if(homeLonLat === undefined){ if (homeLonLat === undefined) {
return empty return empty
} }
return [{ return [{

View file

@ -19,7 +19,7 @@ export class RegexTag extends TagsFilter {
if (fromTag === undefined) { if (fromTag === undefined) {
return; return;
} }
if(typeof fromTag === "number"){ if (typeof fromTag === "number") {
fromTag = "" + fromTag; fromTag = "" + fromTag;
} }
if (typeof possibleRegex === "string") { if (typeof possibleRegex === "string") {
@ -47,7 +47,7 @@ export class RegexTag extends TagsFilter {
} }
matchesProperties(tags: any): boolean { matchesProperties(tags: any): boolean {
if(typeof this.key === "string"){ if (typeof this.key === "string") {
const value = tags[this.key] ?? "" const value = tags[this.key] ?? ""
return RegexTag.doesMatch(value, this.value) != this.invert; return RegexTag.doesMatch(value, this.value) != this.invert;
} }

View file

@ -27,7 +27,7 @@ export class TagUtils {
return properties; return properties;
} }
static changeAsProperties(kvs : {k: string, v: string}[]): any { static changeAsProperties(kvs: { k: string, v: string }[]): any {
const tags = {} const tags = {}
for (const kv of kvs) { for (const kv of kvs) {
tags[kv.k] = kv.v tags[kv.k] = kv.v

View file

@ -1,5 +1,4 @@
import {Utils} from "../Utils"; import {Utils} from "../Utils";
import * as Events from "events";
export class UIEventSource<T> { export class UIEventSource<T> {
@ -76,27 +75,6 @@ export class UIEventSource<T> {
return src return src
} }
public AsPromise(): Promise<T>{
const self = this;
return new Promise((resolve, reject) => {
if(self.data !== undefined){
resolve(self.data)
}else{
self.addCallbackD(data => {
resolve(data)
return true; // return true to unregister as we only need to be called once
})
}
})
}
public WaitForPromise(promise: Promise<T>, onFail: ((any) => void)): UIEventSource<T> {
const self = this;
promise?.then(d => self.setData(d))
promise?.catch(err =>onFail(err))
return this
}
/** /**
* Converts a promise into a UIVentsource, sets the UIEVentSource when the result is calculated. * Converts a promise into a UIVentsource, sets the UIEVentSource when the result is calculated.
* If the promise fails, the value will stay undefined * If the promise fails, the value will stay undefined
@ -110,20 +88,6 @@ export class UIEventSource<T> {
return src return src
} }
public withEqualityStabilized(comparator: (t:T | undefined, t1:T | undefined) => boolean): UIEventSource<T>{
let oldValue = undefined;
return this.map(v => {
if(v == oldValue){
return oldValue
}
if(comparator(oldValue, v)){
return oldValue
}
oldValue = v;
return v;
})
}
/** /**
* Given a UIEVentSource with a list, returns a new UIEventSource which is only updated if the _contents_ of the list are different. * Given a UIEVentSource with a list, returns a new UIEventSource which is only updated if the _contents_ of the list are different.
* E.g. * E.g.
@ -168,6 +132,57 @@ export class UIEventSource<T> {
return stable return stable
} }
public static asFloat(source: UIEventSource<string>): UIEventSource<number> {
return source.map(
(str) => {
let parsed = parseFloat(str);
return isNaN(parsed) ? undefined : parsed;
},
[],
(fl) => {
if (fl === undefined || isNaN(fl)) {
return undefined;
}
return ("" + fl).substr(0, 8);
}
)
}
public AsPromise(): Promise<T> {
const self = this;
return new Promise((resolve, reject) => {
if (self.data !== undefined) {
resolve(self.data)
} else {
self.addCallbackD(data => {
resolve(data)
return true; // return true to unregister as we only need to be called once
})
}
})
}
public WaitForPromise(promise: Promise<T>, onFail: ((any) => void)): UIEventSource<T> {
const self = this;
promise?.then(d => self.setData(d))
promise?.catch(err => onFail(err))
return this
}
public withEqualityStabilized(comparator: (t: T | undefined, t1: T | undefined) => boolean): UIEventSource<T> {
let oldValue = undefined;
return this.map(v => {
if (v == oldValue) {
return oldValue
}
if (comparator(oldValue, v)) {
return oldValue
}
oldValue = v;
return v;
})
}
/** /**
* Adds a callback * Adds a callback
* *
@ -234,14 +249,14 @@ export class UIEventSource<T> {
sink.setData(null) sink.setData(null)
} else if (newEventSource === undefined) { } else if (newEventSource === undefined) {
sink.setData(undefined) sink.setData(undefined)
}else if (!seenEventSources.has(newEventSource)) { } else if (!seenEventSources.has(newEventSource)) {
seenEventSources.add(newEventSource) seenEventSources.add(newEventSource)
newEventSource.addCallbackAndRun(resultData => { newEventSource.addCallbackAndRun(resultData => {
if (mapped.data === newEventSource) { if (mapped.data === newEventSource) {
sink.setData(resultData); sink.setData(resultData);
} }
}) })
}else{ } else {
// Already seen, so we don't have to add a callback, just update the value // Already seen, so we don't have to add a callback, just update the value
sink.setData(newEventSource.data) sink.setData(newEventSource.data)
} }
@ -300,7 +315,7 @@ export class UIEventSource<T> {
} }
public stabilized(millisToStabilize): UIEventSource<T> { public stabilized(millisToStabilize): UIEventSource<T> {
if(Utils.runningFromConsole){ if (Utils.runningFromConsole) {
return this; return this;
} }
@ -335,20 +350,4 @@ export class UIEventSource<T> {
} }
}) })
} }
public static asFloat(source: UIEventSource<string>): UIEventSource<number> {
return source.map(
(str) => {
let parsed = parseFloat(str);
return isNaN(parsed) ? undefined : parsed;
},
[],
(fl) => {
if (fl === undefined || isNaN(fl)) {
return undefined;
}
return ("" + fl).substr(0, 8);
}
)
}
} }

View file

@ -55,8 +55,8 @@ export class QueryParameters {
return source; return source;
} }
public static GetBooleanQueryParameter(key: string, deflt: string, documentation?: string): UIEventSource<boolean>{ public static GetBooleanQueryParameter(key: string, deflt: string, documentation?: string): UIEventSource<boolean> {
return QueryParameters.GetQueryParameter(key, deflt, documentation).map(str => str === "true", [], b => ""+b) return QueryParameters.GetQueryParameter(key, deflt, documentation).map(str => str === "true", [], b => "" + b)
} }
public static GenerateQueryParameterDocs(): string { public static GenerateQueryParameterDocs(): string {

View file

@ -65,7 +65,7 @@ export class WikidataResponse {
static extractClaims(claimsJson: any): Map<string, Set<string>> { static extractClaims(claimsJson: any): Map<string, Set<string>> {
const simplified = wds.simplify.claims(claimsJson, { const simplified = wds.simplify.claims(claimsJson, {
timeConverter: 'simple-day' timeConverter: 'simple-day'
}) })
@ -98,11 +98,11 @@ export class WikidataLexeme {
for (const sense of json.senses) { for (const sense of json.senses) {
const glosses = sense.glosses const glosses = sense.glosses
for (const language in glosses) { for (const language in glosses) {
let previousSenses = this.senses.get(language) let previousSenses = this.senses.get(language)
if(previousSenses === undefined){ if (previousSenses === undefined) {
previousSenses = "" previousSenses = ""
}else{ } else {
previousSenses = previousSenses+"; " previousSenses = previousSenses + "; "
} }
this.senses.set(language, previousSenses + glosses[language].value ?? "") this.senses.set(language, previousSenses + glosses[language].value ?? "")
} }
@ -248,7 +248,7 @@ export default class Wikidata {
for (const identifierPrefix of Wikidata._identifierPrefixes) { for (const identifierPrefix of Wikidata._identifierPrefixes) {
if (value.startsWith(identifierPrefix)) { if (value.startsWith(identifierPrefix)) {
const trimmed = value.substring(identifierPrefix.length); const trimmed = value.substring(identifierPrefix.length);
if(trimmed === ""){ if (trimmed === "") {
return undefined return undefined
} }
const n = Number(trimmed) const n = Number(trimmed)
@ -266,14 +266,14 @@ export default class Wikidata {
return undefined; return undefined;
} }
public static IdToArticle(id: string){ public static IdToArticle(id: string) {
if(id.startsWith("Q")){ if (id.startsWith("Q")) {
return "https://wikidata.org/wiki/"+id return "https://wikidata.org/wiki/" + id
} }
if(id.startsWith("L")){ if (id.startsWith("L")) {
return "https://wikidata.org/wiki/Lexeme:"+id return "https://wikidata.org/wiki/Lexeme:" + id
} }
throw "Unknown id type: "+id throw "Unknown id type: " + id
} }
/** /**
@ -289,7 +289,7 @@ export default class Wikidata {
const url = "https://www.wikidata.org/wiki/Special:EntityData/" + id + ".json"; const url = "https://www.wikidata.org/wiki/Special:EntityData/" + id + ".json";
const entities = (await Utils.downloadJsonCached(url, 10000)).entities const entities = (await Utils.downloadJsonCached(url, 10000)).entities
const firstKey = <string> Array.from(Object.keys(entities))[0] // Roundabout way to fetch the entity; it might have been a redirect const firstKey = <string>Array.from(Object.keys(entities))[0] // Roundabout way to fetch the entity; it might have been a redirect
const response = entities[firstKey] const response = entities[firstKey]
if (id.startsWith("L")) { if (id.startsWith("L")) {

View file

@ -9,8 +9,8 @@ export default class Wikimedia {
* @param continueParameter: if the page indicates that more pages should be loaded, this uses a token to continue. Provided by wikimedia * @param continueParameter: if the page indicates that more pages should be loaded, this uses a token to continue. Provided by wikimedia
*/ */
public static async GetCategoryContents(categoryName: string, public static async GetCategoryContents(categoryName: string,
maxLoad = 10, maxLoad = 10,
continueParameter: string = undefined): Promise<string[]> { continueParameter: string = undefined): Promise<string[]> {
if (categoryName === undefined || categoryName === null || categoryName === "") { if (categoryName === undefined || categoryName === null || categoryName === "") {
return []; return [];
} }

View file

@ -14,7 +14,7 @@ export default class Wikipedia {
private static readonly classesToRemove = [ private static readonly classesToRemove = [
"shortdescription", "shortdescription",
"sidebar", "sidebar",
"infobox","infobox_v2", "infobox", "infobox_v2",
"noprint", "noprint",
"ambox", "ambox",
"mw-editsection", "mw-editsection",
@ -31,10 +31,11 @@ export default class Wikipedia {
public static GetArticle(options: { public static GetArticle(options: {
pageName: string, pageName: string,
language?: "en" | string}): UIEventSource<{ success: string } | { error: any }>{ language?: "en" | string
const key = (options.language ?? "en")+":"+options.pageName }): UIEventSource<{ success: string } | { error: any }> {
const key = (options.language ?? "en") + ":" + options.pageName
const cached = Wikipedia._cache.get(key) const cached = Wikipedia._cache.get(key)
if(cached !== undefined){ if (cached !== undefined) {
return cached return cached
} }
const v = UIEventSource.FromPromiseWithErr(Wikipedia.GetArticleAsync(options)) const v = UIEventSource.FromPromiseWithErr(Wikipedia.GetArticleAsync(options))
@ -57,24 +58,22 @@ export default class Wikipedia {
const content = Array.from(div.children)[0] const content = Array.from(div.children)[0]
for (const forbiddenClass of Wikipedia.classesToRemove) { for (const forbiddenClass of Wikipedia.classesToRemove) {
const toRemove = content.getElementsByClassName(forbiddenClass) const toRemove = content.getElementsByClassName(forbiddenClass)
for (const toRemoveElement of Array.from(toRemove)) { for (const toRemoveElement of Array.from(toRemove)) {
toRemoveElement.parentElement?.removeChild(toRemoveElement) toRemoveElement.parentElement?.removeChild(toRemoveElement)
} }
} }
for (const forbiddenId of Wikipedia.idsToRemove) { for (const forbiddenId of Wikipedia.idsToRemove) {
const toRemove = content.querySelector("#"+forbiddenId) const toRemove = content.querySelector("#" + forbiddenId)
toRemove?.parentElement?.removeChild(toRemove) toRemove?.parentElement?.removeChild(toRemove)
} }
const links = Array.from(content.getElementsByTagName("a")) const links = Array.from(content.getElementsByTagName("a"))
// Rewrite relative links to absolute links + open them in a new tab // Rewrite relative links to absolute links + open them in a new tab
links.filter(link => link.getAttribute("href")?.startsWith("/") ?? false). links.filter(link => link.getAttribute("href")?.startsWith("/") ?? false).forEach(link => {
forEach(link => {
link.target = '_blank' link.target = '_blank'
// note: link.getAttribute("href") gets the textual value, link.href is the rewritten version which'll contain the host for relative paths // note: link.getAttribute("href") gets the textual value, link.href is the rewritten version which'll contain the host for relative paths
link.href = `https://${language}.wikipedia.org${link.getAttribute("href")}`; link.href = `https://${language}.wikipedia.org${link.getAttribute("href")}`;

View file

@ -18,7 +18,6 @@ export default class Constants {
] ]
// The user journey states thresholds when a new feature gets unlocked // The user journey states thresholds when a new feature gets unlocked
public static userJourney = { public static userJourney = {
moreScreenUnlock: 1, moreScreenUnlock: 1,

View file

@ -49,8 +49,8 @@ export class Denomination {
return (this._humanSingular ?? this._human).Clone() return (this._humanSingular ?? this._human).Clone()
} }
getToggledHuman(isSingular: UIEventSource<boolean>): BaseUIElement{ getToggledHuman(isSingular: UIEventSource<boolean>): BaseUIElement {
if(this._humanSingular === undefined){ if (this._humanSingular === undefined) {
return this.human return this.human
} }
return new Toggle( return new Toggle(
@ -68,8 +68,8 @@ export class Denomination {
if (stripped === null) { if (stripped === null) {
return null; return null;
} }
if(stripped === "1" && this._canonicalSingular !== undefined){ if (stripped === "1" && this._canonicalSingular !== undefined) {
return "1 "+this._canonicalSingular return "1 " + this._canonicalSingular
} }
return stripped + " " + this.canonical; return stripped + " " + this.canonical;
} }
@ -89,27 +89,28 @@ export class Denomination {
value = value.toLowerCase() value = value.toLowerCase()
const self = this; const self = this;
function startsWith(key){
if(self.prefix){ function startsWith(key) {
if (self.prefix) {
return value.startsWith(key) return value.startsWith(key)
}else{ } else {
return value.endsWith(key) return value.endsWith(key)
} }
} }
function substr(key){ function substr(key) {
if(self.prefix){ if (self.prefix) {
return value.substr(key.length).trim() return value.substr(key.length).trim()
}else{ } else {
return value.substring(0, value.length - key.length).trim() return value.substring(0, value.length - key.length).trim()
} }
} }
if(this.canonical !== "" && startsWith(this.canonical.toLowerCase())){ if (this.canonical !== "" && startsWith(this.canonical.toLowerCase())) {
return substr(this.canonical) return substr(this.canonical)
} }
if(this._canonicalSingular !== undefined && this._canonicalSingular !== "" && startsWith(this._canonicalSingular)){ if (this._canonicalSingular !== undefined && this._canonicalSingular !== "" && startsWith(this._canonicalSingular)) {
return substr(this._canonicalSingular) return substr(this._canonicalSingular)
} }

View file

@ -1,10 +1,9 @@
import {UIEventSource} from "../Logic/UIEventSource"; import {UIEventSource} from "../Logic/UIEventSource";
import LayerConfig from "./ThemeConfig/LayerConfig"; import LayerConfig from "./ThemeConfig/LayerConfig";
import {And} from "../Logic/Tags/And";
import FilterConfig from "./ThemeConfig/FilterConfig"; import FilterConfig from "./ThemeConfig/FilterConfig";
export default interface FilteredLayer { export default interface FilteredLayer {
readonly isDisplayed: UIEventSource<boolean>; readonly isDisplayed: UIEventSource<boolean>;
readonly appliedFilters: UIEventSource<{filter: FilterConfig, selected: number}[]>; readonly appliedFilters: UIEventSource<{ filter: FilterConfig, selected: number }[]>;
readonly layerDef: LayerConfig; readonly layerDef: LayerConfig;
} }

View file

@ -18,7 +18,7 @@ export default class FilterConfig {
if (json.id === undefined) { if (json.id === undefined) {
throw `A filter without id was found at ${context}` throw `A filter without id was found at ${context}`
} }
if(json.id.match(/^[a-zA-Z0-9_-]*$/) === null){ if (json.id.match(/^[a-zA-Z0-9_-]*$/) === null) {
throw `A filter with invalid id was found at ${context}. Ids should only contain letters, numbers or - _` throw `A filter with invalid id was found at ${context}. Ids should only contain letters, numbers or - _`
} }
@ -43,8 +43,8 @@ export default class FilterConfig {
return {question: question, osmTags: osmTags}; return {question: question, osmTags: osmTags};
}); });
if(this.options.length > 1 && this.options[0].osmTags["and"]?.length !== 0){ if (this.options.length > 1 && this.options[0].osmTags["and"]?.length !== 0) {
throw "Error in "+context+"."+this.id+": the first option of a multi-filter should always be the 'reset' option and not have any filters" throw "Error in " + context + "." + this.id + ": the first option of a multi-filter should always be the 'reset' option and not have any filters"
} }
} }
} }

View file

@ -64,7 +64,7 @@ export interface LayerConfigJson {
* NOTE: the previous format was 'overpassTags: AndOrTagConfigJson | string', which is interpreted as a shorthand for source: {osmTags: "key=value"} * NOTE: the previous format was 'overpassTags: AndOrTagConfigJson | string', which is interpreted as a shorthand for source: {osmTags: "key=value"}
* While still supported, this is considered deprecated * While still supported, this is considered deprecated
*/ */
source: ({ osmTags: AndOrTagConfigJson | string, overpassScript?: string } | source: ({ osmTags: AndOrTagConfigJson | string, overpassScript?: string } |
{ osmTags: AndOrTagConfigJson | string, geoJson: string, geoJsonZoomLevel?: number, isOsmCache?: boolean, mercatorCrs?: boolean }) & ({ { osmTags: AndOrTagConfigJson | string, geoJson: string, geoJsonZoomLevel?: number, isOsmCache?: boolean, mercatorCrs?: boolean }) & ({
/** /**
* The maximum amount of seconds that a tile is allowed to linger in the cache * The maximum amount of seconds that a tile is allowed to linger in the cache
@ -207,17 +207,15 @@ export interface LayerConfigJson {
* This is mainly create questions for a 'left' and a 'right' side of the road. * This is mainly create questions for a 'left' and a 'right' side of the road.
* These will be grouped and questions will be asked together * These will be grouped and questions will be asked together
*/ */
tagRenderings?: (string | {builtin: string, override: any} | TagRenderingConfigJson | { tagRenderings?: (string | { builtin: string, override: any } | TagRenderingConfigJson | {
rewrite: { rewrite: {
sourceString: string, sourceString: string,
into: string[] into: string[]
}[], }[],
renderings: (string | {builtin: string, override: any} | TagRenderingConfigJson)[] renderings: (string | { builtin: string, override: any } | TagRenderingConfigJson)[]
}) [], }) [],
/** /**
* All the extra questions for filtering * All the extra questions for filtering
*/ */

View file

@ -1,4 +1,3 @@
import {TagRenderingConfigJson} from "./TagRenderingConfigJson";
import {LayerConfigJson} from "./LayerConfigJson"; import {LayerConfigJson} from "./LayerConfigJson";
import TilesourceConfigJson from "./TilesourceConfigJson"; import TilesourceConfigJson from "./TilesourceConfigJson";

View file

@ -12,12 +12,11 @@ export default interface UnitConfigJson {
/** /**
* The possible denominations * The possible denominations
*/ */
applicableUnits:ApplicableUnitJson[] applicableUnits: ApplicableUnitJson[]
} }
export interface ApplicableUnitJson export interface ApplicableUnitJson {
{
/** /**
* The canonical value which will be added to the text. * The canonical value which will be added to the text.
* e.g. "m" for meters * e.g. "m" for meters

View file

@ -264,7 +264,7 @@ export default class LayerConfig extends WithContextLoader {
} }
} }
public defaultIcon() : BaseUIElement | undefined{ public defaultIcon(): BaseUIElement | undefined {
const mapRendering = this.mapRendering.filter(r => r.location.has("point"))[0] const mapRendering = this.mapRendering.filter(r => r.location.has("point"))[0]
if (mapRendering === undefined) { if (mapRendering === undefined) {
return undefined return undefined

View file

@ -52,7 +52,7 @@ export default class LayoutConfig {
public readonly overpassMaxZoom: number public readonly overpassMaxZoom: number
public readonly osmApiTileSize: number public readonly osmApiTileSize: number
public readonly official: boolean; public readonly official: boolean;
public readonly trackAllNodes : boolean; public readonly trackAllNodes: boolean;
constructor(json: LayoutConfigJson, official = true, context?: string) { constructor(json: LayoutConfigJson, official = true, context?: string) {
this.official = official; this.official = official;
@ -87,18 +87,18 @@ export default class LayoutConfig {
this.startZoom = json.startZoom; this.startZoom = json.startZoom;
this.startLat = json.startLat; this.startLat = json.startLat;
this.startLon = json.startLon; this.startLon = json.startLon;
if(json.widenFactor <= 0){ if (json.widenFactor <= 0) {
throw "Widenfactor too small, shoud be > 0" throw "Widenfactor too small, shoud be > 0"
} }
if(json.widenFactor > 20){ if (json.widenFactor > 20) {
throw "Widenfactor is very big, use a value between 1 and 5 (current value is "+json.widenFactor+") at "+context throw "Widenfactor is very big, use a value between 1 and 5 (current value is " + json.widenFactor + ") at " + context
} }
this.widenFactor = json.widenFactor ?? 1.5; this.widenFactor = json.widenFactor ?? 1.5;
this.defaultBackgroundId = json.defaultBackgroundId; this.defaultBackgroundId = json.defaultBackgroundId;
this.tileLayerSources = (json.tileLayerSources??[]).map((config, i) => new TilesourceConfig(config, `${this.id}.tileLayerSources[${i}]`)) this.tileLayerSources = (json.tileLayerSources ?? []).map((config, i) => new TilesourceConfig(config, `${this.id}.tileLayerSources[${i}]`))
const layerInfo = LayoutConfig.ExtractLayers(json, official, context); const layerInfo = LayoutConfig.ExtractLayers(json, official, context);
this.layers = layerInfo.layers this.layers = layerInfo.layers
this.trackAllNodes = layerInfo.extractAllNodes this.trackAllNodes = layerInfo.extractAllNodes
@ -107,12 +107,12 @@ export default class LayoutConfig {
maxZoom: 16, maxZoom: 16,
minNeededElements: 25, minNeededElements: 25,
}; };
if(json.clustering === false){ if (json.clustering === false) {
this.clustering = { this.clustering = {
maxZoom: 0, maxZoom: 0,
minNeededElements: 100000, minNeededElements: 100000,
}; };
}else if (json.clustering) { } else if (json.clustering) {
this.clustering = { this.clustering = {
maxZoom: json.clustering.maxZoom ?? 18, maxZoom: json.clustering.maxZoom ?? 18,
minNeededElements: json.clustering.minNeededElements ?? 25, minNeededElements: json.clustering.minNeededElements ?? 25,
@ -124,7 +124,7 @@ export default class LayoutConfig {
if (json.hideInOverview) { if (json.hideInOverview) {
throw "The json for " + this.id + " contains a 'hideInOverview'. Did you mean hideFromOverview instead?" throw "The json for " + this.id + " contains a 'hideInOverview'. Did you mean hideFromOverview instead?"
} }
this.lockLocation = <[[number, number], [number, number]]> json.lockLocation ?? undefined; this.lockLocation = <[[number, number], [number, number]]>json.lockLocation ?? undefined;
this.enableUserBadge = json.enableUserBadge ?? true; this.enableUserBadge = json.enableUserBadge ?? true;
this.enableShareScreen = json.enableShareScreen ?? true; this.enableShareScreen = json.enableShareScreen ?? true;
this.enableMoreQuests = json.enableMoreQuests ?? true; this.enableMoreQuests = json.enableMoreQuests ?? true;
@ -139,10 +139,10 @@ export default class LayoutConfig {
this.enableIframePopout = json.enableIframePopout ?? true this.enableIframePopout = json.enableIframePopout ?? true
this.customCss = json.customCss; this.customCss = json.customCss;
this.overpassUrl = Constants.defaultOverpassUrls this.overpassUrl = Constants.defaultOverpassUrls
if(json.overpassUrl !== undefined){ if (json.overpassUrl !== undefined) {
if(typeof json.overpassUrl === "string"){ if (typeof json.overpassUrl === "string") {
this.overpassUrl = [json.overpassUrl] this.overpassUrl = [json.overpassUrl]
}else{ } else {
this.overpassUrl = json.overpassUrl this.overpassUrl = json.overpassUrl
} }
} }
@ -152,7 +152,7 @@ export default class LayoutConfig {
} }
private static ExtractLayers(json: LayoutConfigJson, official: boolean, context: string): {layers: LayerConfig[], extractAllNodes: boolean} { private static ExtractLayers(json: LayoutConfigJson, official: boolean, context: string): { layers: LayerConfig[], extractAllNodes: boolean } {
const result: LayerConfig[] = [] const result: LayerConfig[] = []
let exportAllNodes = false let exportAllNodes = false
json.layers.forEach((layer, i) => { json.layers.forEach((layer, i) => {
@ -191,7 +191,7 @@ export default class LayoutConfig {
} }
names.forEach(name => { names.forEach(name => {
if(name === "type_node"){ if (name === "type_node") {
// This is a very special layer which triggers special behaviour // This is a very special layer which triggers special behaviour
exportAllNodes = true; exportAllNodes = true;
} }
@ -288,7 +288,7 @@ export default class LayoutConfig {
return new LayoutConfig(JSON.parse(originalJson), false, "Layout rewriting") return new LayoutConfig(JSON.parse(originalJson), false, "Layout rewriting")
} }
public isLeftRightSensitive(){ public isLeftRightSensitive() {
return this.layers.some(l => l.isLeftRightSensitive()) return this.layers.some(l => l.isLeftRightSensitive())
} }

View file

@ -1,6 +1,4 @@
import PointRenderingConfigJson from "./Json/PointRenderingConfigJson";
import WithContextLoader from "./WithContextLoader"; import WithContextLoader from "./WithContextLoader";
import {UIEventSource} from "../../Logic/UIEventSource";
import TagRenderingConfig from "./TagRenderingConfig"; import TagRenderingConfig from "./TagRenderingConfig";
import {Utils} from "../../Utils"; import {Utils} from "../../Utils";
import LineRenderingConfigJson from "./Json/LineRenderingConfigJson"; import LineRenderingConfigJson from "./Json/LineRenderingConfigJson";

View file

@ -15,7 +15,7 @@ import {VariableUiElement} from "../../UI/Base/VariableUIElement";
export default class PointRenderingConfig extends WithContextLoader { export default class PointRenderingConfig extends WithContextLoader {
private static readonly allowed_location_codes = new Set<string>(["point", "centroid","start","end"]) private static readonly allowed_location_codes = new Set<string>(["point", "centroid", "start", "end"])
public readonly location: Set<"point" | "centroid" | "start" | "end"> public readonly location: Set<"point" | "centroid" | "start" | "end">
public readonly icon: TagRenderingConfig; public readonly icon: TagRenderingConfig;
@ -27,7 +27,7 @@ export default class PointRenderingConfig extends WithContextLoader {
constructor(json: PointRenderingConfigJson, context: string) { constructor(json: PointRenderingConfigJson, context: string) {
super(json, context) super(json, context)
if(typeof json.location === "string"){ if (typeof json.location === "string") {
json.location = [json.location] json.location = [json.location]
} }
@ -35,25 +35,25 @@ export default class PointRenderingConfig extends WithContextLoader {
this.location.forEach(l => { this.location.forEach(l => {
const allowed = PointRenderingConfig.allowed_location_codes const allowed = PointRenderingConfig.allowed_location_codes
if(!allowed.has(l)){ if (!allowed.has(l)) {
throw `A point rendering has an invalid location: '${l}' is not one of ${Array.from(allowed).join(", ")} (at ${context}.location)` throw `A point rendering has an invalid location: '${l}' is not one of ${Array.from(allowed).join(", ")} (at ${context}.location)`
} }
}) })
if(json.icon === undefined && json.label === undefined){ if (json.icon === undefined && json.label === undefined) {
throw `A point rendering should define at least an icon or a label` throw `A point rendering should define at least an icon or a label`
} }
if(this.location.size == 0){ if (this.location.size == 0) {
throw "A pointRendering should have at least one 'location' to defined where it should be rendered. (At "+context+".location)" throw "A pointRendering should have at least one 'location' to defined where it should be rendered. (At " + context + ".location)"
} }
this.icon = this.tr("icon", ""); this.icon = this.tr("icon", "");
this.iconBadges = (json.iconBadges ?? []).map((overlay, i) => { this.iconBadges = (json.iconBadges ?? []).map((overlay, i) => {
let tr : TagRenderingConfig; let tr: TagRenderingConfig;
if (typeof overlay.then === "string" && if (typeof overlay.then === "string" &&
SharedTagRenderings.SharedIcons.get(overlay.then) !== undefined) { SharedTagRenderings.SharedIcons.get(overlay.then) !== undefined) {
tr = SharedTagRenderings.SharedIcons.get(overlay.then); tr = SharedTagRenderings.SharedIcons.get(overlay.then);
}else{ } else {
tr = new TagRenderingConfig( tr = new TagRenderingConfig(
overlay.then, overlay.then,
`iconBadges.${i}` `iconBadges.${i}`
@ -77,6 +77,43 @@ export default class PointRenderingConfig extends WithContextLoader {
this.rotation = this.tr("rotation", "0"); this.rotation = this.tr("rotation", "0");
} }
/**
* Given a single HTML spec (either a single image path OR "image_path_to_known_svg:fill-colour", returns a fixedUIElement containing that
* The element will fill 100% and be positioned absolutely with top:0 and left: 0
*/
private static FromHtmlSpec(htmlSpec: string, style: string, isBadge = false): BaseUIElement {
if (htmlSpec === undefined) {
return undefined;
}
const match = htmlSpec.match(/([a-zA-Z0-9_]*):([^;]*)/);
if (match !== null && Svg.All[match[1] + ".svg"] !== undefined) {
const svg = (Svg.All[match[1] + ".svg"] as string)
const targetColor = match[2]
const img = new Img(svg.replace(/#000000/g, targetColor), true)
.SetStyle(style)
if (isBadge) {
img.SetClass("badge")
}
return img
} else {
return new FixedUiElement(`<img src="${htmlSpec}" style="${style}" />`);
}
}
private static FromHtmlMulti(multiSpec: string, rotation: string, isBadge: boolean, defaultElement: BaseUIElement = undefined) {
if (multiSpec === undefined) {
return defaultElement
}
const style = `width:100%;height:100%;transform: rotate( ${rotation} );display:block;position: absolute; top: 0; left: 0`;
const htmlDefs = multiSpec.trim()?.split(";") ?? []
const elements = Utils.NoEmpty(htmlDefs).map(def => PointRenderingConfig.FromHtmlSpec(def, style, isBadge))
if (elements.length === 0) {
return defaultElement
} else {
return new Combine(elements).SetClass("relative block w-full h-full")
}
}
public ExtractImages(): Set<string> { public ExtractImages(): Set<string> {
const parts: Set<string>[] = []; const parts: Set<string>[] = [];
@ -92,44 +129,6 @@ export default class PointRenderingConfig extends WithContextLoader {
return allIcons; return allIcons;
} }
/**
* Given a single HTML spec (either a single image path OR "image_path_to_known_svg:fill-colour", returns a fixedUIElement containing that
* The element will fill 100% and be positioned absolutely with top:0 and left: 0
*/
private static FromHtmlSpec(htmlSpec: string, style: string, isBadge = false): BaseUIElement {
if (htmlSpec === undefined) {
return undefined;
}
const match = htmlSpec.match(/([a-zA-Z0-9_]*):([^;]*)/);
if (match !== null && Svg.All[match[1] + ".svg"] !== undefined) {
const svg = (Svg.All[match[1] + ".svg"] as string)
const targetColor = match[2]
const img = new Img(svg.replace(/#000000/g, targetColor), true)
.SetStyle(style)
if(isBadge){
img.SetClass("badge")
}
return img
} else {
return new FixedUiElement(`<img src="${htmlSpec}" style="${style}" />`);
}
}
private static FromHtmlMulti(multiSpec: string, rotation: string , isBadge: boolean, defaultElement: BaseUIElement = undefined){
if(multiSpec === undefined){
return defaultElement
}
const style = `width:100%;height:100%;transform: rotate( ${rotation} );display:block;position: absolute; top: 0; left: 0`;
const htmlDefs = multiSpec.trim()?.split(";") ?? []
const elements = Utils.NoEmpty(htmlDefs).map(def => PointRenderingConfig.FromHtmlSpec(def, style, isBadge))
if (elements.length === 0) {
return defaultElement
} else {
return new Combine(elements).SetClass("relative block w-full h-full")
}
}
public GetSimpleIcon(tags: UIEventSource<any>): BaseUIElement { public GetSimpleIcon(tags: UIEventSource<any>): BaseUIElement {
const self = this; const self = this;
if (this.icon === undefined) { if (this.icon === undefined) {
@ -139,56 +138,14 @@ export default class PointRenderingConfig extends WithContextLoader {
const rotation = Utils.SubstituteKeys(self.rotation?.GetRenderValue(tags)?.txt ?? "0deg", tags) const rotation = Utils.SubstituteKeys(self.rotation?.GetRenderValue(tags)?.txt ?? "0deg", tags)
const htmlDefs = Utils.SubstituteKeys(self.icon.GetRenderValue(tags)?.txt, tags) const htmlDefs = Utils.SubstituteKeys(self.icon.GetRenderValue(tags)?.txt, tags)
let defaultPin : BaseUIElement = undefined let defaultPin: BaseUIElement = undefined
if(self.label === undefined){ if (self.label === undefined) {
defaultPin = Svg.teardrop_with_hole_green_svg() defaultPin = Svg.teardrop_with_hole_green_svg()
} }
return PointRenderingConfig.FromHtmlMulti(htmlDefs, rotation,false, defaultPin) return PointRenderingConfig.FromHtmlMulti(htmlDefs, rotation, false, defaultPin)
})).SetClass("w-full h-full block") })).SetClass("w-full h-full block")
} }
private GetBadges(tags: UIEventSource<any>): BaseUIElement {
if (this.iconBadges.length === 0) {
return undefined
}
return new VariableUiElement(
tags.map(tags => {
const badgeElements = this.iconBadges.map(badge => {
if (!badge.if.matchesProperties(tags)) {
// Doesn't match...
return undefined
}
const htmlDefs = Utils.SubstituteKeys(badge.then.GetRenderValue(tags)?.txt, tags)
const badgeElement= PointRenderingConfig.FromHtmlMulti(htmlDefs, "0", true)?.SetClass("block relative")
if(badgeElement === undefined){
return undefined;
}
return new Combine([badgeElement]).SetStyle("width: 1.5rem").SetClass("block")
})
return new Combine(badgeElements).SetClass("inline-flex h-full")
})).SetClass("absolute bottom-0 right-1/3 h-1/2 w-0")
}
private GetLabel(tags: UIEventSource<any>): BaseUIElement {
if (this.label === undefined) {
return undefined;
}
const self = this;
return new VariableUiElement(tags.map(tags => {
const label = self.label
?.GetRenderValue(tags)
?.Subs(tags)
?.SetClass("block text-center")
return new Combine([label]).SetClass("flex flex-col items-center mt-1")
}))
}
public GenerateLeafletStyle( public GenerateLeafletStyle(
tags: UIEventSource<any>, tags: UIEventSource<any>,
clickable: boolean, clickable: boolean,
@ -246,9 +203,9 @@ export default class PointRenderingConfig extends WithContextLoader {
const iconAndBadges = new Combine([this.GetSimpleIcon(tags), this.GetBadges(tags)]) const iconAndBadges = new Combine([this.GetSimpleIcon(tags), this.GetBadges(tags)])
.SetClass("block relative") .SetClass("block relative")
if(!options?.noSize){ if (!options?.noSize) {
iconAndBadges.SetStyle(`width: ${iconW}px; height: ${iconH}px`) iconAndBadges.SetStyle(`width: ${iconW}px; height: ${iconH}px`)
}else{ } else {
iconAndBadges.SetClass("w-full h-full") iconAndBadges.SetClass("w-full h-full")
} }
@ -264,4 +221,46 @@ export default class PointRenderingConfig extends WithContextLoader {
}; };
} }
private GetBadges(tags: UIEventSource<any>): BaseUIElement {
if (this.iconBadges.length === 0) {
return undefined
}
return new VariableUiElement(
tags.map(tags => {
const badgeElements = this.iconBadges.map(badge => {
if (!badge.if.matchesProperties(tags)) {
// Doesn't match...
return undefined
}
const htmlDefs = Utils.SubstituteKeys(badge.then.GetRenderValue(tags)?.txt, tags)
const badgeElement = PointRenderingConfig.FromHtmlMulti(htmlDefs, "0", true)?.SetClass("block relative")
if (badgeElement === undefined) {
return undefined;
}
return new Combine([badgeElement]).SetStyle("width: 1.5rem").SetClass("block")
})
return new Combine(badgeElements).SetClass("inline-flex h-full")
})).SetClass("absolute bottom-0 right-1/3 h-1/2 w-0")
}
private GetLabel(tags: UIEventSource<any>): BaseUIElement {
if (this.label === undefined) {
return undefined;
}
const self = this;
return new VariableUiElement(tags.map(tags => {
const label = self.label
?.GetRenderValue(tags)
?.Subs(tags)
?.SetClass("block text-center")
return new Combine([label]).SetClass("flex flex-col items-center mt-1")
}))
}
} }

View file

@ -8,7 +8,7 @@ export default class SourceConfig {
public readonly geojsonSource?: string; public readonly geojsonSource?: string;
public readonly geojsonZoomLevel?: number; public readonly geojsonZoomLevel?: number;
public readonly isOsmCacheLayer: boolean; public readonly isOsmCacheLayer: boolean;
public readonly mercatorCrs: boolean; public readonly mercatorCrs: boolean;
constructor(params: { constructor(params: {
mercatorCrs?: boolean; mercatorCrs?: boolean;
@ -36,11 +36,12 @@ export default class SourceConfig {
console.error(params) console.error(params)
throw `Source said it is a OSM-cached layer, but didn't define the actual source of the cache (in context ${context})` throw `Source said it is a OSM-cached layer, but didn't define the actual source of the cache (in context ${context})`
} }
if(params.geojsonSource !== undefined && params.geojsonSourceLevel !== undefined){ if (params.geojsonSource !== undefined && params.geojsonSourceLevel !== undefined) {
if(! ["x","y","x_min","x_max","y_min","Y_max"].some(toSearch => params.geojsonSource.indexOf(toSearch) > 0)){ if (!["x", "y", "x_min", "x_max", "y_min", "Y_max"].some(toSearch => params.geojsonSource.indexOf(toSearch) > 0)) {
throw `Source defines a geojson-zoomLevel, but does not specify {x} nor {y} (or equivalent), this is probably a bug (in context ${context})` throw `Source defines a geojson-zoomLevel, but does not specify {x} nor {y} (or equivalent), this is probably a bug (in context ${context})`
}} }
this.osmTags = params.osmTags ?? new RegexTag("id",/.*/); }
this.osmTags = params.osmTags ?? new RegexTag("id", /.*/);
this.overpassScript = params.overpassScript; this.overpassScript = params.overpassScript;
this.geojsonSource = params.geojsonSource; this.geojsonSource = params.geojsonSource;
this.geojsonZoomLevel = params.geojsonSourceLevel; this.geojsonZoomLevel = params.geojsonSourceLevel;

View file

@ -51,8 +51,8 @@ export default class TagRenderingConfig {
} }
if(typeof json === "number"){ if (typeof json === "number") {
this.render = Translations.WT( ""+json) this.render = Translations.WT("" + json)
return; return;
} }
@ -74,7 +74,7 @@ export default class TagRenderingConfig {
this.condition = TagUtils.Tag(json.condition ?? {"and": []}, `${context}.condition`); this.condition = TagUtils.Tag(json.condition ?? {"and": []}, `${context}.condition`);
if (json.freeform) { if (json.freeform) {
if(json.freeform.addExtraTags !== undefined && json.freeform.addExtraTags.map === undefined){ if (json.freeform.addExtraTags !== undefined && json.freeform.addExtraTags.map === undefined) {
throw `Freeform.addExtraTags should be a list of strings - not a single string (at ${context})` throw `Freeform.addExtraTags should be a list of strings - not a single string (at ${context})`
} }
this.freeform = { this.freeform = {
@ -135,7 +135,7 @@ export default class TagRenderingConfig {
throw `${ctx}: Invalid mapping: "if" is defined as an array. Use {"and": <your conditions>} or {"or": <your conditions>} instead` throw `${ctx}: Invalid mapping: "if" is defined as an array. Use {"and": <your conditions>} or {"or": <your conditions>} instead`
} }
if(mapping.addExtraTags !== undefined && this.multiAnswer){ if (mapping.addExtraTags !== undefined && this.multiAnswer) {
throw `${ctx}: Invalid mapping: got a multi-Answer with addExtraTags; this is not allowed` throw `${ctx}: Invalid mapping: got a multi-Answer with addExtraTags; this is not allowed`
} }
@ -150,7 +150,7 @@ export default class TagRenderingConfig {
ifnot: (mapping.ifnot !== undefined ? TagUtils.Tag(mapping.ifnot, `${ctx}.ifnot`) : undefined), ifnot: (mapping.ifnot !== undefined ? TagUtils.Tag(mapping.ifnot, `${ctx}.ifnot`) : undefined),
then: Translations.T(mapping.then, `${ctx}.then`), then: Translations.T(mapping.then, `${ctx}.then`),
hideInAnswer: hideInAnswer, hideInAnswer: hideInAnswer,
addExtraTags: (mapping.addExtraTags??[]).map((str, j) => TagUtils.SimpleTag(str, `${ctx}.addExtraTags[${j}]`)) addExtraTags: (mapping.addExtraTags ?? []).map((str, j) => TagUtils.SimpleTag(str, `${ctx}.addExtraTags[${j}]`))
}; };
if (this.question) { if (this.question) {
if (hideInAnswer !== true && mp.if !== undefined && !mp.if.isUsableAsAnswer()) { if (hideInAnswer !== true && mp.if !== undefined && !mp.if.isUsableAsAnswer()) {
@ -260,6 +260,7 @@ export default class TagRenderingConfig {
return false; return false;
} }
/** /**
* Gets all the render values. Will return multiple render values if 'multianswer' is enabled. * Gets all the render values. Will return multiple render values if 'multianswer' is enabled.
* The result will equal [GetRenderValue] if not 'multiAnswer' * The result will equal [GetRenderValue] if not 'multiAnswer'

View file

@ -19,7 +19,7 @@ export default class TilesourceConfig {
this.minzoom = config.minZoom ?? 0 this.minzoom = config.minZoom ?? 0
this.maxzoom = config.maxZoom ?? 999 this.maxzoom = config.maxZoom ?? 999
this.defaultState = config.defaultState ?? true; this.defaultState = config.defaultState ?? true;
if(this.id === undefined){ if (this.id === undefined) {
throw "An id is obligated" throw "An id is obligated"
} }
if (this.minzoom > this.maxzoom) { if (this.minzoom > this.maxzoom) {
@ -34,7 +34,7 @@ export default class TilesourceConfig {
if (this.source.indexOf("{zoom}") >= 0) { if (this.source.indexOf("{zoom}") >= 0) {
throw "Invalid source url: use {z} instead of {zoom} (at " + ctx + ".source)" throw "Invalid source url: use {z} instead of {zoom} (at " + ctx + ".source)"
} }
if(!this.defaultState && config.name === undefined){ if (!this.defaultState && config.name === undefined) {
throw "Disabling an overlay without a name is not possible" throw "Disabling an overlay without a name is not possible"
} }
} }

View file

@ -4,8 +4,8 @@ import {TagRenderingConfigJson} from "./Json/TagRenderingConfigJson";
import {Utils} from "../../Utils"; import {Utils} from "../../Utils";
export default class WithContextLoader { export default class WithContextLoader {
private readonly _json: any;
protected readonly _context: string; protected readonly _context: string;
private readonly _json: any;
constructor(json: any, context: string) { constructor(json: any, context: string) {
this._json = json; this._json = json;
@ -47,7 +47,7 @@ export default class WithContextLoader {
tagRenderings?: (string | { builtin: string, override: any } | TagRenderingConfigJson)[], tagRenderings?: (string | { builtin: string, override: any } | TagRenderingConfigJson)[],
readOnly = false, readOnly = false,
prepConfig: ((config: TagRenderingConfigJson) => TagRenderingConfigJson) = undefined prepConfig: ((config: TagRenderingConfigJson) => TagRenderingConfigJson) = undefined
) : TagRenderingConfig[]{ ): TagRenderingConfig[] {
if (tagRenderings === undefined) { if (tagRenderings === undefined) {
return []; return [];
} }

View file

@ -1,5 +1,5 @@
import {control} from "leaflet"; import {control} from "leaflet";
import zoom = control.zoom;
export interface TileRange { export interface TileRange {
xstart: number, xstart: number,
@ -15,7 +15,7 @@ export class Tiles {
public static MapRange<T>(tileRange: TileRange, f: (x: number, y: number) => T): T[] { public static MapRange<T>(tileRange: TileRange, f: (x: number, y: number) => T): T[] {
const result: T[] = [] const result: T[] = []
const total = tileRange.total const total = tileRange.total
if(total > 100000){ if (total > 100000) {
throw "Tilerange too big" throw "Tilerange too big"
} }
for (let x = tileRange.xstart; x <= tileRange.xend; x++) { for (let x = tileRange.xstart; x <= tileRange.xend; x++) {
@ -27,24 +27,6 @@ export class Tiles {
return result; return result;
} }
private static tile2long(x, z) {
return (x / Math.pow(2, z) * 360 - 180);
}
private static tile2lat(y, z) {
const n = Math.PI - 2 * Math.PI * y / Math.pow(2, z);
return (180 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))));
}
private static lon2tile(lon, zoom) {
return (Math.floor((lon + 180) / 360 * Math.pow(2, zoom)));
}
private static lat2tile(lat, zoom) {
return (Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, zoom)));
}
/** /**
* Calculates the tile bounds of the * Calculates the tile bounds of the
* @param z * @param z
@ -56,7 +38,6 @@ export class Tiles {
return [[Tiles.tile2lat(y, z), Tiles.tile2long(x, z)], [Tiles.tile2lat(y + 1, z), Tiles.tile2long(x + 1, z)]] return [[Tiles.tile2lat(y, z), Tiles.tile2long(x, z)], [Tiles.tile2lat(y + 1, z), Tiles.tile2long(x + 1, z)]]
} }
static tile_bounds_lon_lat(z: number, x: number, y: number): [[number, number], [number, number]] { static tile_bounds_lon_lat(z: number, x: number, y: number): [[number, number], [number, number]] {
return [[Tiles.tile2long(x, z), Tiles.tile2lat(y, z)], [Tiles.tile2long(x + 1, z), Tiles.tile2lat(y + 1, z)]] return [[Tiles.tile2long(x, z), Tiles.tile2lat(y, z)], [Tiles.tile2long(x + 1, z), Tiles.tile2lat(y + 1, z)]]
} }
@ -67,13 +48,14 @@ export class Tiles {
* @param x * @param x
* @param y * @param y
*/ */
static centerPointOf(z: number, x: number, y: number): [number, number]{ static centerPointOf(z: number, x: number, y: number): [number, number] {
return [(Tiles.tile2long(x, z) + Tiles.tile2long(x+1, z)) / 2, (Tiles.tile2lat(y, z) + Tiles.tile2lat(y+1, z)) / 2] return [(Tiles.tile2long(x, z) + Tiles.tile2long(x + 1, z)) / 2, (Tiles.tile2lat(y, z) + Tiles.tile2lat(y + 1, z)) / 2]
} }
static tile_index(z: number, x: number, y: number): number { static tile_index(z: number, x: number, y: number): number {
return ((x * (2 << z)) + y) * 100 + z return ((x * (2 << z)) + y) * 100 + z
} }
/** /**
* Given a tile index number, returns [z, x, y] * Given a tile index number, returns [z, x, y]
* @param index * @param index
@ -114,5 +96,22 @@ export class Tiles {
} }
} }
private static tile2long(x, z) {
return (x / Math.pow(2, z) * 360 - 180);
}
private static tile2lat(y, z) {
const n = Math.PI - 2 * Math.PI * y / Math.pow(2, z);
return (180 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))));
}
private static lon2tile(lon, zoom) {
return (Math.floor((lon + 180) / 360 * Math.pow(2, zoom)));
}
private static lat2tile(lat, zoom) {
return (Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, zoom)));
}
} }

View file

@ -37,7 +37,9 @@ export class Unit {
const possiblePostFixes = new Set<string>() const possiblePostFixes = new Set<string>()
function addPostfixesOf(str) { function addPostfixesOf(str) {
if(str === undefined){return} if (str === undefined) {
return
}
str = str.toLowerCase() str = str.toLowerCase()
for (let i = 0; i < str.length + 1; i++) { for (let i = 0; i < str.length + 1; i++) {
const substr = str.substring(0, i) const substr = str.substring(0, i)
@ -55,7 +57,7 @@ export class Unit {
} }
static fromJson(json: UnitConfigJson, ctx: string){ static fromJson(json: UnitConfigJson, ctx: string) {
const appliesTo = json.appliesToKey const appliesTo = json.appliesToKey
for (let i = 0; i < appliesTo.length; i++) { for (let i = 0; i < appliesTo.length; i++) {
let key = appliesTo[i]; let key = appliesTo[i];
@ -112,7 +114,7 @@ export class Unit {
return undefined; return undefined;
} }
const [stripped, denom] = this.findDenomination(value) const [stripped, denom] = this.findDenomination(value)
const human = stripped === "1" ? denom?.humanSingular : denom?.human const human = stripped === "1" ? denom?.humanSingular : denom?.human
if (human === undefined) { if (human === undefined) {
return new FixedUiElement(stripped ?? value); return new FixedUiElement(stripped ?? value);
} }

View file

@ -2,8 +2,8 @@
> Let a thousand flowers bloom > Let a thousand flowers bloom
**MapComplete is an OpenStreetMap viewer and editor.** It shows map features on a certain topic, and allows to see, edit and **MapComplete is an OpenStreetMap viewer and editor.** It shows map features on a certain topic, and allows to see, edit
add new features to the map. It can be seen as a and add new features to the map. It can be seen as a
webversion [crossover of StreetComplete and MapContrib](Docs/MapComplete_vs_other_editors.md). It tries to be just as webversion [crossover of StreetComplete and MapContrib](Docs/MapComplete_vs_other_editors.md). It tries to be just as
easy to use as StreetComplete, but it allows to focus on one single theme per instance (e.g. nature, bicycle easy to use as StreetComplete, but it allows to focus on one single theme per instance (e.g. nature, bicycle
infrastructure, ...) infrastructure, ...)
@ -15,20 +15,23 @@ infrastructure, ...)
- Easy to set up a custom theme - Easy to set up a custom theme
- Easy to fall down the rabbit hole of OSM - Easy to fall down the rabbit hole of OSM
**The basic functionality is** to download some map features from Overpass and then ask certain questions. An answer is sent **The basic functionality is** to download some map features from Overpass and then ask certain questions. An answer is
back to directly to OpenStreetMap. sent back to directly to OpenStreetMap.
Furthermore, it shows images present in the `image` tag or, if a `wikidata` or `wikimedia_commons`-tag is present, it Furthermore, it shows images present in the `image` tag or, if a `wikidata` or `wikimedia_commons`-tag is present, it
follows those to get these images too. follows those to get these images too.
**An explicit non-goal** of MapComplete is to modify geometries of ways. Although adding a point to a way or splitting a way **An explicit non-goal** of MapComplete is to modify geometries of ways. Although adding a point to a way or splitting a
in two parts might be added one day. way in two parts might be added one day.
**More about MapComplete:** [Watch Pieter's talk on the 2021 State Of The Map Conference](https://media.ccc.de/v/sotm2021-9448-introduction-and-review-of-mapcomplete) ([YouTube](https://www.youtube.com/watch?v=zTtMn6fNbYY)) about the history, vision and future of MapComplete. **More about
MapComplete:** [Watch Pieter's talk on the 2021 State Of The Map Conference](https://media.ccc.de/v/sotm2021-9448-introduction-and-review-of-mapcomplete) ([YouTube](https://www.youtube.com/watch?v=zTtMn6fNbYY))
about the history, vision and future of MapComplete.
# Creating your own theme # Creating your own theme
It is possible to quickly make and distribute your own theme It is possible to quickly make and distribute your own theme
- [please read the documentation on how to do this](Docs/Making_Your_Own_Theme.md). - [please read the documentation on how to do this](Docs/Making_Your_Own_Theme.md).
## Examples ## Examples

View file

@ -15,5 +15,4 @@ export default class State extends FeaturePipelineState {
} }
} }

View file

@ -8,32 +8,31 @@ import {Utils} from "../Utils";
import LanguagePicker from "./LanguagePicker"; import LanguagePicker from "./LanguagePicker";
import IndexText from "./BigComponents/IndexText"; import IndexText from "./BigComponents/IndexText";
import FeaturedMessage from "./BigComponents/FeaturedMessage"; import FeaturedMessage from "./BigComponents/FeaturedMessage";
import {AllKnownLayouts} from "../Customizations/AllKnownLayouts";
export default class AllThemesGui { export default class AllThemesGui {
constructor() { constructor() {
try{ try {
new FixedUiElement("").AttachTo("centermessage") new FixedUiElement("").AttachTo("centermessage")
const state = new UserRelatedState(undefined); const state = new UserRelatedState(undefined);
const intro = new Combine([ const intro = new Combine([
LanguagePicker.CreateLanguagePicker(Translations.t.index.title.SupportedLanguages()) LanguagePicker.CreateLanguagePicker(Translations.t.index.title.SupportedLanguages())
.SetClass("absolute top-2 right-3"), .SetClass("absolute top-2 right-3"),
new IndexText() new IndexText()
]); ]);
new Combine([ new Combine([
intro, intro,
new FeaturedMessage(), new FeaturedMessage(),
new MoreScreen(state, true), new MoreScreen(state, true),
Translations.t.general.aboutMapcomplete Translations.t.general.aboutMapcomplete
.Subs({"osmcha_link": Utils.OsmChaLinkFor(7)}) .Subs({"osmcha_link": Utils.OsmChaLinkFor(7)})
.SetClass("link-underline"), .SetClass("link-underline"),
new FixedUiElement("v" + Constants.vNumber) new FixedUiElement("v" + Constants.vNumber)
]).SetClass("block m-5 lg:w-3/4 lg:ml-40") ]).SetClass("block m-5 lg:w-3/4 lg:ml-40")
.SetStyle("pointer-events: all;") .SetStyle("pointer-events: all;")
.AttachTo("topleft-tools"); .AttachTo("topleft-tools");
}catch (e) { } catch (e) {
new FixedUiElement("Seems like no layers are compiled - check the output of `npm run generate:layeroverview`. Is this visible online? Contact pietervdvn immediately!").SetClass("alert") new FixedUiElement("Seems like no layers are compiled - check the output of `npm run generate:layeroverview`. Is this visible online? Contact pietervdvn immediately!").SetClass("alert")
.AttachTo("centermessage") .AttachTo("centermessage")
} }

View file

@ -3,7 +3,7 @@ import {VariableUiElement} from "./VariableUIElement";
import {UIEventSource} from "../../Logic/UIEventSource"; import {UIEventSource} from "../../Logic/UIEventSource";
import Loading from "./Loading"; import Loading from "./Loading";
export default class AsyncLazy extends BaseUIElement{ export default class AsyncLazy extends BaseUIElement {
private readonly _f: () => Promise<BaseUIElement>; private readonly _f: () => Promise<BaseUIElement>;
constructor(f: () => Promise<BaseUIElement>) { constructor(f: () => Promise<BaseUIElement>) {
@ -16,12 +16,11 @@ export default class AsyncLazy extends BaseUIElement{
return new VariableUiElement( return new VariableUiElement(
UIEventSource.FromPromise(this._f()).map(el => { UIEventSource.FromPromise(this._f()).map(el => {
if(el === undefined){ if (el === undefined) {
return new Loading() return new Loading()
} }
return el return el
}) })
).ConstructElement() ).ConstructElement()
} }

View file

@ -30,13 +30,13 @@ export default class Combine extends BaseUIElement {
if (subEl === undefined || subEl === null) { if (subEl === undefined || subEl === null) {
continue; continue;
} }
try{ try {
const subHtml = subEl.ConstructElement() const subHtml = subEl.ConstructElement()
if (subHtml !== undefined) { if (subHtml !== undefined) {
el.appendChild(subHtml) el.appendChild(subHtml)
} }
}catch(e){ } catch (e) {
console.error("Could not generate subelement in combine due to ", e) console.error("Could not generate subelement in combine due to ", e)
} }
} }

View file

@ -10,7 +10,7 @@ export default class Img extends BaseUIElement {
fallbackImage?: string fallbackImage?: string
}) { }) {
super(); super();
if(src === undefined || src === "undefined"){ if (src === undefined || src === "undefined") {
throw "Undefined src for image" throw "Undefined src for image"
} }
this._src = src; this._src = src;
@ -44,7 +44,7 @@ export default class Img extends BaseUIElement {
} }
el.onerror = () => { el.onerror = () => {
if (self._options?.fallbackImage) { if (self._options?.fallbackImage) {
if(el.src === self._options.fallbackImage){ if (el.src === self._options.fallbackImage) {
// Sigh... nothing to be done anymore // Sigh... nothing to be done anymore
return; return;
} }

Some files were not shown because too many files have changed in this diff Show more