-
Notifications
You must be signed in to change notification settings - Fork 383
/
MapUtils.js
445 lines (395 loc) · 14.9 KB
/
MapUtils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
* Copyright 2015-2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const {isString, trim, isNumber} = require('lodash');
const DEFAULT_SCREEN_DPI = 96;
const METERS_PER_UNIT = {
'm': 1,
'degrees': 111194.87428468118,
'ft': 0.3048,
'us-ft': 1200 / 3937
};
const GOOGLE_MERCATOR = {
RADIUS: 6378137,
TILE_WIDTH: 256,
ZOOM_FACTOR: 2
};
const EXTENT_TO_ZOOM_HOOK = 'EXTENT_TO_ZOOM_HOOK';
/**
* `ZOOM_TO_EXTENT_HOOK` hook takes 2 arguments:
* - `extent`: array of the extent [minx, miny, maxx, maxy]
* - `options` object, with the following attributes:
* - `crs`: crs of the extent
* - `maxZoom`: max zoom for the zoom to functionality.
* - `padding`: object with attributes, `top`, `right`, `bottom` and `top` with the size, in pixels of the padding for the visible part of the map. When supported by the mapping lib, it will zoom to visible area
*/
const ZOOM_TO_EXTENT_HOOK = 'ZOOM_TO_EXTENT_HOOK';
const RESOLUTIONS_HOOK = 'RESOLUTIONS_HOOK';
const RESOLUTION_HOOK = 'RESOLUTION_HOOK';
const COMPUTE_BBOX_HOOK = 'COMPUTE_BBOX_HOOK';
const GET_PIXEL_FROM_COORDINATES_HOOK = 'GET_PIXEL_FROM_COORDINATES_HOOK';
const GET_COORDINATES_FROM_PIXEL_HOOK = 'GET_COORDINATES_FROM_PIXEL_HOOK';
let hooks = {};
let CoordinatesUtils = require('./CoordinatesUtils');
let {set} = require('./ImmutableUtils');
const LayersUtils = require('./LayersUtils');
const assign = require('object-assign');
const {isObject, head, isEmpty, findIndex} = require('lodash');
function registerHook(name, hook) {
hooks[name] = hook;
}
function getHook(name) {
return hooks[name];
}
function executeHook(hookName, existCallback, dontExistCallback) {
const hook = getHook(hookName);
if (hook) {
return existCallback(hook);
}
if (dontExistCallback) {
return dontExistCallback();
}
return null;
}
/**
* @param dpi {number} dot per inch resolution
* @return {number} dot per meter resolution
*/
function dpi2dpm(dpi) {
return dpi * (100 / 2.54);
}
/**
* @param dpi {number} screen resolution in dots per inch.
* @param projection {string} map projection.
* @return {number} dots per map unit.
*/
function dpi2dpu(dpi, projection) {
const units = CoordinatesUtils.getUnits(projection || "EPSG:3857");
return METERS_PER_UNIT[units] * dpi2dpm(dpi || DEFAULT_SCREEN_DPI);
}
/**
* @param radius {number} Earth's radius of the model in meters.
* @param tileWidth {number} width of the tiles used to draw the map.
* @param zoomFactor {number} zoom factor.
* @param zoomLvl {number} target zoom level.
* @param dpi {number} screen resolution in dot per inch.
* @return {number} the scale of the showed map.
*/
function getSphericalMercatorScale(radius, tileWidth, zoomFactor, zoomLvl, dpi) {
return 2 * Math.PI * radius / (tileWidth * Math.pow(zoomFactor, zoomLvl) / dpi2dpm(dpi || DEFAULT_SCREEN_DPI));
}
/**
* @param zoomLvl {number} target zoom level.
* @param dpi {number} screen resolution in dot per inch.
* @return {number} the scale of the showed map.
*/
function getGoogleMercatorScale(zoomLvl, dpi) {
return getSphericalMercatorScale(GOOGLE_MERCATOR.RADIUS, GOOGLE_MERCATOR.TILE_WIDTH, GOOGLE_MERCATOR.ZOOM_FACTOR, zoomLvl, dpi);
}
/**
* @param radius {number} Earth's radius of the model in meters.
* @param tileWidth {number} width of the tiles used to draw the map.
* @param zoomFactor {number} zoom factor.
* @param minZoom {number} min zoom level.
* @param maxZoom {number} max zoom level.
* @param dpi {number} screen resolution in dot per inch.
* @return {array} a list of scale for each zoom level in the given interval.
*/
function getSphericalMercatorScales(radius, tileWidth, zoomFactor, minZoom, maxZoom, dpi) {
var retval = [];
for (let l = minZoom; l <= maxZoom; l++) {
retval.push(
getSphericalMercatorScale(
radius,
tileWidth,
zoomFactor,
l,
dpi
)
);
}
return retval;
}
/**
* Get a list of scales for each zoom level of the Google Mercator.
* @param minZoom {number} min zoom level.
* @param maxZoom {number} max zoom level.
* @return {array} a list of scale for each zoom level in the given interval.
*/
function getGoogleMercatorScales(minZoom, maxZoom, dpi) {
return getSphericalMercatorScales(
GOOGLE_MERCATOR.RADIUS,
GOOGLE_MERCATOR.TILE_WIDTH,
GOOGLE_MERCATOR.ZOOM_FACTOR,
minZoom,
maxZoom,
dpi
);
}
/**
* @param scales {array} list of scales.
* @param projection {string} map projection.
* @param dpi {number} screen resolution in dots per inch.
* @return {array} a list of resolutions corresponding to the given scales, projection and dpi.
*/
function getResolutionsForScales(scales, projection, dpi) {
const dpu = dpi2dpu(dpi, projection);
const resolutions = scales.map((scale) => {
return scale / dpu;
});
return resolutions;
}
function getGoogleMercatorResolutions(minZoom, maxZoom, dpi) {
return getResolutionsForScales(getGoogleMercatorScales(minZoom, maxZoom, dpi), "EPSG:3857", dpi);
}
function getResolutions() {
if (getHook('RESOLUTIONS_HOOK')) {
return getHook('RESOLUTIONS_HOOK')();
}
return getGoogleMercatorResolutions(0, 21, DEFAULT_SCREEN_DPI);
}
function getScales(projection, dpi) {
const dpu = dpi2dpu(dpi, projection);
return getResolutions().map((resolution) => resolution * dpu);
}
function defaultGetZoomForExtent(extent, mapSize, minZoom, maxZoom, dpi, mapResolutions) {
const wExtent = extent[2] - extent[0];
const hExtent = extent[3] - extent[1];
const xResolution = Math.abs(wExtent / mapSize.width);
const yResolution = Math.abs(hExtent / mapSize.height);
const extentResolution = Math.max(xResolution, yResolution);
const resolutions = mapResolutions || getResolutionsForScales(getGoogleMercatorScales(
minZoom, maxZoom, dpi || DEFAULT_SCREEN_DPI), "EPSG:3857", dpi);
const {zoom, ...other} = resolutions.reduce((previous, resolution, index) => {
const diff = Math.abs(resolution - extentResolution);
return diff > previous.diff ? previous : {diff: diff, zoom: index};
}, {diff: Number.POSITIVE_INFINITY, zoom: 0});
return Math.max(0, Math.min(zoom, maxZoom));
}
/**
* Calculates the best fitting zoom level for the given extent.
*
* @param extent {Array} [minx, miny, maxx, maxy]
* @param mapSize {Object} current size of the map.
* @param minZoom {number} min zoom level.
* @param maxZoom {number} max zoom level.
* @param dpi {number} screen resolution in dot per inch.
* @return {Number} the zoom level fitting th extent
*/
function getZoomForExtent(extent, mapSize, minZoom, maxZoom, dpi) {
if (getHook("EXTENT_TO_ZOOM_HOOK")) {
return getHook("EXTENT_TO_ZOOM_HOOK")(extent, mapSize, minZoom, maxZoom, dpi);
}
const resolutions = getHook("RESOLUTIONS_HOOK") ?
getHook("RESOLUTIONS_HOOK")(extent, mapSize, minZoom, maxZoom, dpi, dpi2dpm(dpi || DEFAULT_SCREEN_DPI)) : null;
return defaultGetZoomForExtent(extent, mapSize, minZoom, maxZoom, dpi, resolutions);
}
/**
* It returns the current resolution.
*
* @param currentZoom {number} the current zoom
* @param minZoom {number} min zoom level.
* @param maxZoom {number} max zoom level.
* @param dpi {number} screen resolution in dot per inch.
* @return {Number} the actual resolution
*/
function getCurrentResolution(currentZoom, minZoom, maxZoom, dpi) {
if (getHook("RESOLUTION_HOOK")) {
return getHook("RESOLUTION_HOOK")(currentZoom, minZoom, maxZoom, dpi);
}
/* if no hook is registered (leaflet) it is used the GoogleMercatorResolutions in
in order to get the list of resolutions */
return getGoogleMercatorResolutions(minZoom, maxZoom, dpi)[currentZoom];
}
/**
* Calculates the center for for the given extent.
*
* @param {Array} extent [minx, miny, maxx, maxy]
* @param {String} projection projection of the extent
* @return {object} center object
*/
function getCenterForExtent(extent, projection) {
var wExtent = extent[2] - extent[0];
var hExtent = extent[3] - extent[1];
var w = wExtent / 2;
var h = hExtent / 2;
return {
x: extent[0] + w,
y: extent[1] + h,
crs: projection
};
}
/**
* Calculates the bounding box for the given center and zoom.
*
* @param {object} center object
* @param {number} zoom level
*/
function getBbox(center, zoom) {
return executeHook("COMPUTE_BBOX_HOOK",
(hook) => {
return hook(center, zoom);
}
);
}
const isNearlyEqual = function(a, b) {
if (a === undefined || b === undefined) {
return false;
}
return a.toFixed(12) - b.toFixed(12) === 0;
};
function mapUpdated(oldMap, newMap) {
const centersEqual = isNearlyEqual(newMap.center.x, oldMap.center.x) &&
isNearlyEqual(newMap.center.y, oldMap.center.y);
return !centersEqual || newMap.zoom !== oldMap.zoom;
}
/* Transform width and height specified in meters to the units of the specified projection */
function transformExtent(projection, center, width, height) {
let units = CoordinatesUtils.getUnits(projection);
if (units === 'ft') {
return {width: width / METERS_PER_UNIT.ft, height: height / METERS_PER_UNIT.ft};
} else if (units === 'us-ft') {
return {width: width / METERS_PER_UNIT['us-ft'], height: height / METERS_PER_UNIT['us-ft']};
} else if (units === 'degrees') {
return {
width: width / (111132.92 - 559.82 * Math.cos(2 * center.y) + 1.175 * Math.cos(4 * center.y)),
height: height / (111412.84 * Math.cos(center.y) - 93.5 * Math.cos(3 * center.y))
};
}
return {width, height};
}
const groupSaveFormatted = (node) => {
if (isObject(node.title) && head(Object.keys(node.title).filter(t => node.title[t]))) {
return {id: node.id, title: node.title, expanded: node.expanded};
}
return {id: node.id, expanded: node.expanded};
};
function saveMapConfiguration(currentMap, currentLayers, currentGroups, textSearchConfig, additionalOptions) {
const map = {
center: currentMap.center,
maxExtent: currentMap.maxExtent,
projection: currentMap.projection,
units: currentMap.units,
zoom: currentMap.zoom,
mapOptions: currentMap.mapOptions || {}
};
const layers = currentLayers.map((layer) => {
return LayersUtils.saveLayer(layer);
});
const flatGroupId = currentGroups.reduce((a, b) => {
const flatGroups = a.concat(LayersUtils.getGroupNodes(b));
return flatGroups;
}, [].concat(currentGroups.map(g => g.id)));
const groups = flatGroupId.map(g => {
const node = LayersUtils.getNode(currentGroups, g);
return node && node.nodes ? groupSaveFormatted(node) : null;
}).filter(g => g);
// extract sources map
const sources = LayersUtils.extractSourcesFromLayers(layers);
/* removes tilematrixset from layers and reduced matrix ids to a list */
const formattedLayers = layers.map(l => {
return assign({}, l, {tileMatrixSet: l.tileMatrixSet && l.tileMatrixSet.length > 0, matrixIds: l.matrixIds && Object.keys(l.matrixIds)});
});
/* removes the geometryGeodesic property from the features in the annotations layer*/
let annotationsLayerIndex = findIndex(formattedLayers, layer => layer.id === "annotations");
if (annotationsLayerIndex !== -1) {
let featuresLayer = formattedLayers[annotationsLayerIndex].features.map(feature => {
if (feature.type === "FeatureCollection") {
return {
...feature,
features: feature.features.map(f => {
if (f.properties.geometryGeodesic) {
return set("properties.geometryGeodesic", null, f);
}
return f;
})
};
}
if (feature.properties.geometryGeodesic) {
return set("properties.geometryGeodesic", null, feature);
}
});
formattedLayers[annotationsLayerIndex] = set("features", featuresLayer, formattedLayers[annotationsLayerIndex]);
}
return {
version: 2,
// layers are defined inside the map object
map: assign({}, map, {layers: formattedLayers, groups, text_serch_config: textSearchConfig}, !isEmpty(sources) && {sources} || {}),
...additionalOptions
};
}
function isSimpleGeomType(geomType) {
switch (geomType) {
case "MultiPoint": case "MultiLineString": case "MultiPolygon": case "GeometryCollection": case "Text": return false;
case "Point": case "Circle": case "LineString": case "Polygon": default: return true;
}
}
function getSimpleGeomType(geomType = "Point") {
switch (geomType) {
case "Point": case "LineString": case "Polygon": case "Circle": return geomType;
case "MultiPoint": case "Marker": return "Point";
case "MultiLineString": return "LineString";
case "MultiPolygon": return "Polygon";
case "GeometryCollection": return "GeometryCollection";
case "Text": return "Point";
default: return geomType;
}
}
const getIdFromUri = (uri, regex = /data\/(\d+)/) => {
const decodedUri = decodeURIComponent(uri);
const findDataDigit = regex.exec(decodedUri);
return findDataDigit && findDataDigit.length && findDataDigit.length > 1 ? findDataDigit[1] : null;
};
/**
* Return parsed number from layout value
* if percentage returns percentage of second argument that should be a number
* eg. 20% of map height parseLayoutValue(20%, map.size.height)
* but if value is stored as number it will return the number
* eg. parseLayoutValue(50, map.size.height) returns 50
* @param value {number|string} number or percentage value string
* @param size {number} only in case of percentage
* @return {number}
*/
const parseLayoutValue = (value, size = 0) => {
if (isString(value) && value.indexOf('%') !== -1) {
return parseFloat(trim(value)) * size / 100;
}
return isNumber(value) ? value : 0;
};
module.exports = {
EXTENT_TO_ZOOM_HOOK,
RESOLUTIONS_HOOK,
RESOLUTION_HOOK,
COMPUTE_BBOX_HOOK,
GET_PIXEL_FROM_COORDINATES_HOOK,
GET_COORDINATES_FROM_PIXEL_HOOK,
DEFAULT_SCREEN_DPI,
ZOOM_TO_EXTENT_HOOK,
registerHook,
getHook,
dpi2dpm,
getSphericalMercatorScales,
getSphericalMercatorScale,
getGoogleMercatorScales,
getGoogleMercatorResolutions,
getGoogleMercatorScale,
getResolutionsForScales,
getZoomForExtent,
defaultGetZoomForExtent,
getCenterForExtent,
getResolutions,
getScales,
getBbox,
mapUpdated,
getCurrentResolution,
transformExtent,
saveMapConfiguration,
isSimpleGeomType,
getSimpleGeomType,
getIdFromUri,
parseLayoutValue
};