@maptrip/map-tiles 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ import { VectorTileFactory } from "../../core/VectorTileFactory";
2
+ import { MIN_ZOOM, MAX_ZOOM } from "../../core/constants";
3
+
4
+ class MapTripGoogleMapType {
5
+ tileSize = new google.maps.Size(256, 256);
6
+ alt = null;
7
+ maxZoom = MAX_ZOOM;
8
+ minZoom = MIN_ZOOM;
9
+ projection = null;
10
+ radius = 6378137;
11
+
12
+ constructor(properties) {
13
+ this.name = properties.name ? properties.name : 'infoware';
14
+ this.token = properties.token;
15
+ this.factory = VectorTileFactory.createFactory(properties);
16
+ }
17
+
18
+ getTile(coord, zoom) {
19
+ return this.factory.getJsonTile(zoom, coord.x, coord.y, this.token);
20
+ }
21
+
22
+ releaseTile() {}
23
+ }
24
+
25
+ export { MapTripGoogleMapType };
@@ -0,0 +1,24 @@
1
+ import L from "leaflet";
2
+
3
+ import { VectorTileFactory } from "../../core/VectorTileFactory";
4
+ import { MIN_ZOOM, MAX_ZOOM, ATTRIBUTION } from "../../core/constants";
5
+
6
+ const MapTripLeafletGridLayer = L.GridLayer.extend({
7
+
8
+ MIN_ZOOM: MIN_ZOOM,
9
+ MAX_ZOOM: MAX_ZOOM,
10
+
11
+ initialize: function(options) {
12
+ this.token = options.token;
13
+ this.options.attribution = options.attribution ? options.attribution : ATTRIBUTION;
14
+ this.options.minZoom = options.minZoom ? Math.max(this.MIN_ZOOM, options.minZoom) : this.MIN_ZOOM;
15
+ this.options.maxZoom = options.maxZoom ? Math.min(this.MAX_ZOOM, options.maxZoom) : this.MAX_ZOOM;
16
+ this.factory = VectorTileFactory.createFactory(options);
17
+ },
18
+
19
+ createTile: function (coords) {
20
+ return this.factory.getJsonTile(coords.z, coords.x, coords.y, this.token);
21
+ }
22
+ });
23
+
24
+ export { MapTripLeafletGridLayer };
@@ -0,0 +1,43 @@
1
+ import XYZ from 'ol/source/XYZ.js';
2
+ import { createXYZ, extentFromProjection } from 'ol/tilegrid.js';
3
+
4
+ import { VectorTileFactory } from "../../core/VectorTileFactory";
5
+ import { MIN_ZOOM, MAX_ZOOM, ATTRIBUTION } from "../../core/constants";
6
+
7
+ class MapTripOpenLayersSource extends XYZ {
8
+ constructor(properties) {
9
+
10
+ const options = {};
11
+ const projection = 'EPSG:3857';
12
+
13
+ const tileGrid = createXYZ({
14
+ extent: extentFromProjection(projection),
15
+ maxResolution: options.maxResolution,
16
+ minZoom: MIN_ZOOM,
17
+ maxZoom: MAX_ZOOM,
18
+ tileSize: [256, 256]
19
+ });
20
+
21
+ super({
22
+ opaque: true,
23
+ minZoom: MIN_ZOOM,
24
+ maxZoom: MAX_ZOOM,
25
+ projection: projection,
26
+ tileGrid: tileGrid,
27
+ wrapX: true,
28
+ url: 'z:{z} x:{x} y:{y}',
29
+ tileLoadFunction: (tile) => {
30
+ let coord = tile.getTileCoord();
31
+ let canvas = this.factory.getJsonTile(coord[0], coord[1], coord[2], this.token, () => {
32
+ tile.setImage(canvas);
33
+ })
34
+ },
35
+ attributions: ATTRIBUTION
36
+ });
37
+
38
+ this.token = properties.token;
39
+ this.factory = VectorTileFactory.createFactory(properties);
40
+ }
41
+ }
42
+
43
+ export { MapTripOpenLayersSource };
@@ -0,0 +1,65 @@
1
+ import RTree from 'rtree';
2
+
3
+ class CollisionDetector {
4
+ constructor() {
5
+ this._tree = RTree(10);
6
+ }
7
+
8
+ insert(x, y, w, h) {
9
+ this._tree.insert({ x: x, y: y, w: w, h: h}, 0);
10
+ }
11
+
12
+ insertPolylineText(context, text, position) {
13
+ let widthUsed = 0;
14
+
15
+ for (let i = 0; i <= text.length; i++)
16
+ {
17
+ let box = this.getCollisionParams(context, text.charAt(i), position, widthUsed);
18
+ this.insert(box.x, box.y, box.w, box.h);
19
+
20
+ widthUsed += context.measureText(text.charAt(i)).width;
21
+ }
22
+ }
23
+
24
+ isCollision(x, y, w, h) {
25
+ return this._tree.search({ x: x, y: y, w: w, h: h }).length > 0;
26
+ }
27
+
28
+ isPolylineTextCollision(context, text, position) {
29
+ let border = 5;
30
+ let widthUsed = 0;
31
+
32
+ for (let i = 0; i <= text.length; i++)
33
+ {
34
+ var box = this.getCollisionParams(context, text.charAt(i), position, widthUsed);
35
+
36
+ if (box.x < border || box.y < border || box.x + box.w > 256 - border || box.y + box.h > 256 - border)
37
+ {
38
+ return true;
39
+ }
40
+
41
+ if (this.isCollision(box.x, box.y, box.w, box.h))
42
+ {
43
+ return true;
44
+ }
45
+
46
+ widthUsed += context.measureText(text.charAt(i)).width;
47
+ }
48
+
49
+ return false;
50
+ }
51
+
52
+ getCollisionParams(context, text, position) {
53
+ let textWidth = context.measureText(text).width;
54
+ let textHeight = context.measureText(text.charAt(0)).width * 1.5;
55
+
56
+ return {
57
+ x: position.x + 0.5 * Math.cos(position.angle) * textWidth,
58
+ y: position.y + 0.5 * Math.sin(position.angle) * textWidth,
59
+ w: Math.abs(Math.cos(position.angle) * textWidth) + Math.abs(Math.sin(position.angle) * textHeight),
60
+ h: Math.abs(Math.sin(position.angle) * textWidth) + Math.abs(Math.cos(position.angle) * textHeight)
61
+ }
62
+ }
63
+ }
64
+
65
+ export { CollisionDetector };
@@ -0,0 +1,245 @@
1
+ import { VectorTileLoader } from './VectorTileLoader.js';
2
+ import { VectorTileRenderer } from './VectorTileRenderer.js';
3
+
4
+ import { URL_TEMPLATE, PROVIDER_PROJECTS, PROVIDER_TRAFFIC } from './constants.js';
5
+
6
+ import { RENDERING_CONFIG_DEFAULT } from './rendering_config_default.js';
7
+ import { RENDERING_CONFIG_TRAFFIC } from './rendering_config_traffic.js';
8
+
9
+ import WebFont from 'webfontloader';
10
+
11
+ /**
12
+ * Creates a factory to create tiles from the provided URL templates.
13
+ *
14
+ * The templates must have variables ${x}, ${y} and ${z} for the tile index.
15
+ * When multiple URLs are specified, they are used round robin.
16
+ */
17
+ class VectorTileFactory {
18
+
19
+ static _fonts = undefined;
20
+
21
+ constructor(urls, additionalUrls, renderingConfig, properties)
22
+ {
23
+ this._urls = urls;
24
+ this._additionalUrls = additionalUrls;
25
+ this._layers = ['all']; // could be used to load just a selection of layers from the data server
26
+
27
+ this._tileLoader = new VectorTileLoader(properties);
28
+ this._renderer = new VectorTileRenderer(renderingConfig);
29
+
30
+ if (!VectorTileFactory._fonts) {
31
+ //console.log(this._renderer.findConfiguredFonts()); // TODO create families string like Open Sans:n4,n7,i4,i7
32
+
33
+ WebFont.load({
34
+ custom: {
35
+ families: ['Open Sans:n4,n7,i4,i7'],
36
+ urls: ['https://maps.infoware.de/MapAPI-1.4/css/opensans.css']
37
+ },
38
+ loading: function() {
39
+ VectorTileFactory._fonts = 'loading';
40
+ },
41
+ active: function() {
42
+ VectorTileFactory._fonts = 'active';
43
+ this._tileLoader.loadNext();
44
+ }.bind(this),
45
+ inactive: function() {
46
+ // font loading failed
47
+ VectorTileFactory._fonts = 'active';
48
+ this._tileLoader.loadNext();
49
+ }.bind(this)
50
+ });
51
+ }
52
+ }
53
+
54
+ static createFactory(properties) {
55
+ // apply default properties
56
+ this._properties = properties ? { ...VectorTileFactory.DEFAULT_PROPERTIES, ...properties } : VectorTileFactory.DEFAULT_PROPERTIES;
57
+ this._properties.provider = this._properties.provider.toLowerCase();
58
+
59
+ // assert the provider is valid
60
+ if (!PROVIDER_PROJECTS[this._properties.provider]) {
61
+ throw new Error('Unknown provider');
62
+ }
63
+
64
+ // assert there is no traffic requested for a provider which does not provide traffic information
65
+ if (this._properties.traffic && !PROVIDER_TRAFFIC[this._properties.provider]) {
66
+ throw new Error('There is now traffic information for this provider');
67
+ }
68
+
69
+ // assert there is either a base map or traffic (or both)
70
+ if (!this._properties.baseMap && !this._properties.traffic) {
71
+ throw new Error('You cannot create a factory with neither a base map nor traffic');
72
+ }
73
+
74
+ return new VectorTileFactory(
75
+ VectorTileFactory.getUrlTemplatesForBaseLayer(this._properties),
76
+ VectorTileFactory.getUrlTemplatesForTrafficLayer(this._properties),
77
+ VectorTileFactory.getRenderingConfig(this._properties),
78
+ this._properties);
79
+ }
80
+
81
+ static getUrlTemplatesForBaseLayer(properties) {
82
+ if (properties.baseMap) {
83
+ let template = URL_TEMPLATE.replace('${project}', PROVIDER_PROJECTS[properties.provider]);
84
+ return [0, 1, 2, 3].map(index => template.replace('${index}', index));
85
+ }
86
+ else {
87
+ return [];
88
+ }
89
+ }
90
+
91
+ static getUrlTemplatesForTrafficLayer(properties) {
92
+ return properties.traffic ? [PROVIDER_TRAFFIC[properties.provider]] : [];
93
+ }
94
+
95
+ static getRenderingConfig(properties) {
96
+ if (properties.renderingConfig) {
97
+ return properties.renderingConfig;
98
+ }
99
+ else if (properties.baseMap) {
100
+ return RENDERING_CONFIG_DEFAULT;
101
+ }
102
+ else {
103
+ return RENDERING_CONFIG_TRAFFIC;
104
+ }
105
+ }
106
+
107
+ getJsonTile(z, x, y, token, callback) {
108
+ let maximumIndex = Math.pow(2, z);
109
+ x = (x + 16 * maximumIndex) % maximumIndex;
110
+ y = (y + 16 * maximumIndex) % maximumIndex;
111
+
112
+ let canvas = document.createElement('canvas');
113
+ canvas.width = 256;
114
+ canvas.height = 256;
115
+
116
+ let baseMapUrl = this.resolveTileUrl(z, x, y);
117
+ let urls = baseMapUrl ? [ baseMapUrl ] : [];
118
+
119
+ // add URLs for additional data like traffic flows
120
+ this._additionalUrls.forEach(it => {
121
+ urls.push(it.replace('${x}', x).replace('${y}', y).replace(/\$\{z\}/g, z));
122
+ });
123
+
124
+ let tileLoadedSuccessfullyCallback = function(json) {
125
+ this.drawTile(json, z, x, y, canvas);
126
+
127
+ if (callback) {
128
+ callback(canvas);
129
+ }
130
+ }.bind(this);
131
+
132
+ let tile_FailedCallback = function() {
133
+ this.drawErroredTile(canvas);
134
+
135
+ if (callback) {
136
+ callback(null);
137
+ }
138
+ }.bind(this);
139
+
140
+ this._tileLoader.queue(
141
+ { x: x, y: y, z: z, urls: urls, token: token },
142
+ tileLoadedSuccessfullyCallback,
143
+ tile_FailedCallback
144
+ );
145
+
146
+ if (VectorTileFactory._fonts === 'active') {
147
+ this._tileLoader.loadNext();
148
+ }
149
+
150
+ return canvas;
151
+ }
152
+
153
+ /**
154
+ * @private
155
+ */
156
+ resolveTileUrl(z, x, y) {
157
+ if (this._urls.length > 0) {
158
+ var index = (x + y + z) % this._urls.length;
159
+
160
+ return this._urls[index]
161
+ .replace('${x}', x)
162
+ .replace('${y}', y)
163
+ .replace(/\$\{z\}/g, z)
164
+ .replace('${layers}', this._layers.join(','));
165
+ }
166
+ else {
167
+ // there is no base map layer
168
+ return null;
169
+ }
170
+ }
171
+
172
+ /**
173
+ * @private
174
+ */
175
+ tileIndexToLatLong(z, x, y) {
176
+ var n = Math.PI - 2 * Math.PI * y / Math.pow(2, z);
177
+
178
+ return {
179
+ lat: (180 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)))),
180
+ lon: (x / Math.pow(2, z) * 360 - 180)
181
+ };
182
+ }
183
+
184
+ /**
185
+ * @private
186
+ */
187
+ getTileBoundaries(z, x, y) {
188
+ return {
189
+ min: this.tileIndexToLatLong(z, x, y),
190
+ max: this.tileIndexToLatLong(z, x + 1, y + 1)
191
+ }
192
+ }
193
+
194
+ /**
195
+ * @private
196
+ */
197
+ drawTile(json, z, x, y, canvas) {
198
+ var features = this.getFeatures(json).sort(function(a, b) {
199
+ if (a.properties && a.properties.sort_rank) {
200
+ if (b.properties && b.properties.sort_rank) {
201
+ return a.properties.sort_rank - b.properties.sort_rank;
202
+ }
203
+ else {
204
+ return -1;
205
+ }
206
+ }
207
+ else {
208
+ if (b.properties && b.properties.sort_rank) {
209
+ return 1;
210
+ }
211
+ else {
212
+ return 0;
213
+ }
214
+ }
215
+ });
216
+
217
+ this._renderer.drawTile(features, z, this.getTileBoundaries(z, x, y), canvas.getContext('2d'));
218
+ }
219
+
220
+ /**
221
+ * Draws an error message on the tile.
222
+ *
223
+ * @param canvas
224
+ */
225
+ drawErroredTile(canvas) {
226
+ this._renderer.drawErroredTile(canvas);
227
+ }
228
+
229
+ /**
230
+ * @private
231
+ */
232
+ getFeatures(json) {
233
+ if (json.type && json.type == 'FeatureCollection') {
234
+ return json.features;
235
+ }
236
+ }
237
+
238
+ static DEFAULT_PROPERTIES = {
239
+ provider: 'OpenStreetmap',
240
+ baseMap: true,
241
+ traffic: false
242
+ };
243
+ }
244
+
245
+ export { VectorTileFactory };
@@ -0,0 +1,127 @@
1
+ class VectorTileLoader {
2
+
3
+ constructor(properties) {
4
+ this._properties = properties ? { ...VectorTileLoader.DEFAULT_PROPERTIES, ...properties } : VectorTileLoader.DEFAULT_PROPERTIES;
5
+
6
+ this._tiles = [];
7
+ this._numLoading = 0;
8
+ }
9
+
10
+ queue(tile, successCallback, errorCallback) {
11
+ this._tiles.push({ tile: tile, successCallback: successCallback, errorCallback: errorCallback });
12
+ }
13
+
14
+ loadNext() {
15
+ if (this._numLoading >= this._properties.parallelDownloads) {
16
+ return;
17
+ }
18
+
19
+ if (this._tiles.length > 0) {
20
+ // filter all files with wrong zoom levels
21
+ let latestZoom = this._tiles[this._tiles.length - 1].tile.z;
22
+ this._tiles = this._tiles.filter(function(tile) {
23
+ return latestZoom === tile.tile.z;
24
+ }.bind(this));
25
+
26
+ // load the first tile
27
+ var next = this._tiles.shift();
28
+ if (!next) {
29
+ return;
30
+ }
31
+
32
+ // load all URLs for that tile
33
+ this.loadAllUrls(next, next.tile.urls);
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Checks if a HTTP Request is successful
39
+ *
40
+ * @param {XMLHttpRequest} httpRequest
41
+ *
42
+ * @return {boolean}
43
+ */
44
+ isHttpRequestSuccessful(httpRequest) {
45
+ return httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200 && httpRequest.responseText.length > 0;
46
+ }
47
+
48
+ /**
49
+ * Checks if a HTTP Request has failed (there was a timeout or the status code is an error)
50
+ *
51
+ * @param {XMLHttpRequest} httpRequest
52
+ *
53
+ * @return {boolean}
54
+ */
55
+ isHttpRequestFailed(httpRequest) {
56
+ return this.isHttpRequestTimeout(httpRequest) || httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status >= 400;
57
+ }
58
+
59
+ /**
60
+ * Checks if a HTTP Request has timed out
61
+ *
62
+ * @param {XMLHttpRequest} httpRequest
63
+ *
64
+ * @return {boolean}
65
+ */
66
+ isHttpRequestTimeout(httpRequest) {
67
+ return httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 0;
68
+ }
69
+
70
+ loadAllUrls(tile, urls) {
71
+ var url = urls.pop();
72
+
73
+ var xhr = new XMLHttpRequest();
74
+ xhr.onreadystatechange = function() {
75
+ if (xhr.readyState !== XMLHttpRequest.DONE) {
76
+ return;
77
+ }
78
+
79
+ if (this.isHttpRequestSuccessful(xhr)) {
80
+ var json = JSON.parse(xhr.responseText); // XXX bei Fehlern des Data Servers kommt hier kein JSON sondern XML!
81
+
82
+ if (!tile.json) {
83
+ tile.json = json;
84
+ }
85
+ else {
86
+ tile.json.features = tile.json.features.concat(json.features);
87
+ }
88
+
89
+ if (urls.length === 0) {
90
+ // no more URLs left, so call the callback
91
+ tile.successCallback(tile.json);
92
+ }
93
+ else {
94
+ // load the remaining URLs
95
+ this.loadAllUrls(tile, urls);
96
+ }
97
+ }
98
+
99
+ if (this.isHttpRequestFailed(xhr) || this.isHttpRequestTimeout(xhr)) {
100
+ tile.errorCallback(xhr.responseText);
101
+ }
102
+
103
+ this._numLoading--;
104
+ this.loadNext();
105
+ }.bind(this);
106
+
107
+ xhr.ontimeout = function() {
108
+ tile.errorCallback(xhr.responseText);
109
+ this._numLoading--;
110
+ this.loadNext();
111
+ }.bind(this);
112
+
113
+ xhr.open('GET', url, true);
114
+ xhr.setRequestHeader('Authorization', `Bearer ${tile.tile.token}`);
115
+ xhr.timeout = this._properties.timeout;
116
+ xhr.send(null);
117
+
118
+ this._numLoading++;
119
+ }
120
+
121
+ static DEFAULT_PROPERTIES = {
122
+ timeout: 5000,
123
+ parallelDownloads: 12
124
+ };
125
+ }
126
+
127
+ export { VectorTileLoader };