-
Notifications
You must be signed in to change notification settings - Fork 88
/
Service.js
596 lines (542 loc) · 19 KB
/
Service.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
// The MIT License (MIT)
//
// Copyright (c) 2015-2023 Camptocamp SA
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import angular from 'angular';
import ngeoPrintVectorEncoder from 'ngeo/print/VectorEncoder';
import ngeoMapLayerHelper from 'ngeo/map/LayerHelper';
import {stableSort} from 'ol/array';
import olLayerImage from 'ol/layer/Image';
import olLayerTile from 'ol/layer/WebGLTile';
import olLayerVector from 'ol/layer/Vector';
import * as olSize from 'ol/size';
import olSourceImageWMS from 'ol/source/ImageWMS';
import olSourceTileWMS from 'ol/source/TileWMS';
import olSourceWMTS from 'ol/source/WMTS';
import olTilegridWMTS from 'ol/tilegrid/WMTS';
/**
* @typedef {function(string): PrintService} CreatePrint
*/
/**
* Provides a function to create ngeo.print.Service objects used to
* interact with MapFish Print v3 services.
*
* ngeo.print.Service objects expose the following methods:
*
* - createSpec: create a report specification object
* - createReport: send a create report request
* - getStatus: get the status of a report
* - getReportUrl: get the URL of a report
* - getCapabilities: get the capabilities of the server
*
*
* let printBaseUrl = 'http://example.com/print';
* let print = new ngeo.print.Service(printBaseUrl);
*
* let scale = 5000;
* let dpi = 72;
* let layout = 'A4 portrait';
* let format = 'pdf';
* let reportSpec = print.createSpec(map, scale, dpi, layout, format, {
* 'title': 'A title for my report',
* 'rotation': 45 // degree
* });
*
* See our live example: [../examples/mapfishprint.html](../examples/mapfishprint.html)
*
* TODO and limitations:
*
* - createSpec should also accept a bbox instead of a center and a scale.
* - Add support for ol.style.RegularShape. MapFish Print supports symbols
* like crosses, stars and squares, so printing regular shapes should be
* possible.
* - ol.style.Icon may use a sprite image, and offsets to define to rectangle
* to use within the sprite. This type of icons won't be printed correctly
* as MapFish Print does not support sprite icons.
*
* @class
* @param {string} url URL to MapFish print web service.
* @param {angular.IHttpService} $http Angular $http service.
* @param {angular.gettext.gettextCatalog} gettextCatalog Gettext service.
* @param {import('ngeo/map/LayerHelper').LayerHelper} ngeoLayerHelper Ngeo Layer Helper service.
* @hidden
*/
export function PrintService(url, $http, gettextCatalog, ngeoLayerHelper) {
/**
* @type {string}
*/
this.url_ = url;
/**
* @type {angular.IHttpService}
*/
this.$http_ = $http;
/**
* @type {angular.gettext.gettextCatalog}
*/
this.gettextCatalog_ = gettextCatalog;
/**
* @type {import('ngeo/map/LayerHelper').LayerHelper}
*/
this.ngeoLayerHelper_ = ngeoLayerHelper;
/**
* @type {import('ngeo/print/VectorEncoder').default}
*/
this.vectorEncoder = new ngeoPrintVectorEncoder();
/**
* @type {boolean}
*/
this.printNativeAngle_ = true;
/**
* @type {number}
*/
this.goodnessOfFit_;
}
/**
* Cancel a report.
*
* @param {string} ref Print report reference.
* @param {angular.IRequestShortcutConfig} [opt_httpConfig] $http config object.
* @returns {angular.IHttpPromise<Object>} HTTP promise.
*/
PrintService.prototype.cancel = function (ref, opt_httpConfig) {
const httpConfig =
opt_httpConfig !== undefined ? opt_httpConfig : /** @type {angular.IRequestShortcutConfig} */ ({});
const url = `${this.url_}/cancel/${ref}`;
// "delete" is a reserved word, so use ['delete']
return this.$http_['delete'](url, httpConfig);
};
/**
* Create a report specification.
*
* @param {import('ol/Map').default} map Map.
* @param {number} scale Scale.
* @param {number} rotation Rotation.
* @param {number} dpi DPI.
* @param {string} layout Layout.
* @param {string} format Formats.
* @param {Object<string, *>} customAttributes Custom attributes.
* @param {string} [email] Email to send the file to.
* @param {number} [goodnessOfFit] Goodness of fit.
* @returns {import('ngeo/print/mapfish-print-v3').MapFishPrintSpec} The print spec.
*/
PrintService.prototype.createSpec = function (
map,
scale,
rotation,
dpi,
layout,
format,
customAttributes,
email,
goodnessOfFit
) {
const specMap = /** @type {import('ngeo/print/mapfish-print-v3').MapFishPrintMap} */ ({
dpi: dpi,
rotation: rotation,
});
if (goodnessOfFit) {
this.goodnessOfFit_ = goodnessOfFit;
}
this.encodeMap_(map, scale, specMap, dpi);
/** @type {import('ngeo/print/mapfish-print-v3').MapFishPrintAttributes} */
const attributes = {
map: specMap,
};
Object.assign(attributes, customAttributes);
const lang = this.gettextCatalog_.getCurrentLanguage();
/** @type {import('ngeo/print/mapfish-print-v3').MapFishPrintSpec} */
const spec = {
attributes,
format,
lang,
layout,
};
if (email) {
spec.smtp = {to: email};
}
return spec;
};
/**
* @param {import('ol/Map').default} map Map.
* @param {number} scale Scale.
* @param {import('ngeo/print/mapfish-print-v3').MapFishPrintMap} object Object.
* @param {number} destinationPrintDpi The destination print DPI.
*/
PrintService.prototype.encodeMap_ = function (map, scale, object, destinationPrintDpi) {
const view = map.getView();
const viewCenter = view.getCenter();
const viewProjection = view.getProjection();
const viewResolution = view.getResolution();
if (!viewCenter) {
throw new Error('Missing viewCenter');
}
if (!viewProjection) {
throw new Error('Missing viewProjection');
}
if (!viewResolution) {
throw new Error('Missing viewResolution');
}
object.center = viewCenter;
object.projection = viewProjection.getCode();
object.scale = scale;
object.useNearestScale = false;
object.layers = [];
const mapLayerGroup = map.getLayerGroup();
if (!mapLayerGroup) {
throw new Error('Missing mapLayerGroup');
}
this.printNativeAngle_ = mapLayerGroup.get('printNativeAngle') !== false;
let layers = this.ngeoLayerHelper_.getFlatLayers(mapLayerGroup);
// Sort the layer by ZIndex
stableSort(layers, (layer_a, layer_b) => (layer_a.getZIndex() || 0) - (layer_b.getZIndex() || 0));
layers = layers.slice().reverse();
layers.forEach((layer) => {
if (layer.getVisible()) {
this.encodeLayer(object.layers, layer, viewResolution, destinationPrintDpi);
}
});
};
/**
* @param {import('ngeo/print/mapfish-print-v3').MapFishPrintLayer[]} arr Array.
* @param {import('ol/layer/Base').default} layer Layer.
* @param {number} resolution Resolution.
* @param {number} destinationPrintDpi The destination print DPI.
*/
PrintService.prototype.encodeLayer = function (arr, layer, resolution, destinationPrintDpi) {
if (layer instanceof olLayerImage) {
this.encodeImageLayer_(arr, layer);
} else if (layer instanceof olLayerTile) {
this.encodeTileLayer_(arr, layer);
} else if (layer instanceof olLayerVector) {
this.encodeVectorLayer(arr, layer, resolution, destinationPrintDpi);
}
};
/**
* @param {import('ngeo/print/mapfish-print-v3').MapFishPrintLayer[]} arr Array.
* @param {olLayerVector<import('ol/source/Vector').default<import('ol/geom/Geometry').default>>} layer Layer.
* @param {number} resolution Resolution.
* @param {number} destinationPrintDpi The destination print DPI.
*/
PrintService.prototype.encodeVectorLayer = function (arr, layer, resolution, destinationPrintDpi) {
this.vectorEncoder.encodeVectorLayer(arr, layer, resolution, destinationPrintDpi, this.goodnessOfFit_);
};
/**
* @param {import('ngeo/print/mapfish-print-v3').MapFishPrintLayer[]} arr Array.
* @param {import('ol/layer/Image').default<import('ol/source/Image').default>} layer Layer.
*/
PrintService.prototype.encodeImageLayer_ = function (arr, layer) {
if (!(layer instanceof olLayerImage)) {
throw new Error('layer not instance of olLayerImage');
}
const source = layer.getSource();
if (source instanceof olSourceImageWMS) {
this.encodeImageWmsLayer_(arr, layer);
}
};
/**
* @param {import('ngeo/print/mapfish-print-v3').MapFishPrintLayer[]} arr Array.
* @param {import('ol/layer/Image').default<import('ol/source/Image').default>} layer Layer.
*/
PrintService.prototype.encodeImageWmsLayer_ = function (arr, layer) {
if (!(layer instanceof olLayerImage)) {
throw new Error('layer not instance of olLayerImage');
}
const source = layer.getSource();
if (!(source instanceof olSourceImageWMS)) {
throw new Error('source not instance of olSourceImageWMS');
}
const url = source.getUrl();
if (url !== undefined) {
this.encodeWmsLayer_(arr, layer, url, source.getParams());
}
};
/**
* @param {import('ngeo/print/mapfish-print-v3').MapFishPrintLayer[]} arr Array.
* @param {import('ol/layer/Image').default<import('ol/source/Image').default>|import('ol/layer/WebGLTile').default<import('ol/source/Tile').default>} layer The layer.
* @param {string} url URL of the WMS server.
* @param {Object<string, string>} params URL parameters
*/
PrintService.prototype.encodeWmsLayer_ = function (arr, layer, url, params) {
if (url.startsWith('//')) {
url = window.location.protocol + url;
}
const url_url = new URL(url);
/** @type {Object<string, string>} */
const customParams = {'TRANSPARENT': 'true'};
if (url_url.searchParams) {
url_url.searchParams.forEach(
/**
* @param {string} value
* @param {string} key
*/
(value, key) => {
customParams[key] = value;
}
);
}
for (const key in params) {
const value = params[key];
// remove empty params
if (value !== null && value !== undefined) {
customParams[key] = value;
}
}
delete customParams.LAYERS;
delete customParams.FORMAT;
delete customParams.SERVERTYPE;
delete customParams.VERSION;
delete customParams.STYLES;
let serverType = undefined;
if (params.SERVERTYPE !== 'arcgis') {
serverType = params.SERVERTYPE;
}
// Add empty styles if needed
if (!params.STYLES) {
params.STYLES = '';
}
// Get the same amount of styles than layers to print
while (params.LAYERS.split(',').length > params.STYLES.split(',').length) {
params.STYLES += ',';
}
/** @type {import('ngeo/print/mapfish-print-v3').MapFishPrintWmsLayer} */
const object = {
baseURL: getAbsoluteUrl_(url_url.origin + url_url.pathname),
imageFormat: 'FORMAT' in params ? params.FORMAT : 'image/png',
layers: params.LAYERS.split(','),
customParams: customParams,
serverType,
type: 'wms',
opacity: this.getOpacityOrInherited_(layer),
version: params.VERSION,
useNativeAngle: this.printNativeAngle_,
styles: params.STYLES ? params.STYLES.split(',') : [''],
};
arr.push(object);
};
/**
* @param {string} url URL.
* @returns {string} Absolute URL.
* @private
* @hidden
*/
function getAbsoluteUrl_(url) {
const a = document.createElement('a');
a.href = encodeURI(url);
return decodeURI(a.href);
}
/**
* @param {import('ngeo/print/mapfish-print-v3').MapFishPrintLayer[]} arr Array.
* @param {import('ol/layer/WebGLTile').default<import('ol/source/Tile').default>} layer Layer.
*/
PrintService.prototype.encodeTileLayer_ = function (arr, layer) {
if (!(layer instanceof olLayerTile)) {
throw new Error('layer not instance of olLayerTile');
}
const source = layer.getSource();
if (source instanceof olSourceWMTS) {
this.encodeTileWmtsLayer_(arr, layer);
} else if (source instanceof olSourceTileWMS) {
this.encodeTileWmsLayer_(arr, layer);
}
};
/**
* @param {import('ngeo/print/mapfish-print-v3').MapFishPrintLayer[]} arr Array.
* @param {import('ol/layer/WebGLTile').default<import('ol/source/Tile').default>} layer Layer.
*/
PrintService.prototype.encodeTileWmtsLayer_ = function (arr, layer) {
if (!(layer instanceof olLayerTile)) {
throw new Error('layer not instance of olLayerTile');
}
const source = layer.getSource();
if (!(source instanceof olSourceWMTS)) {
throw new Error('source not instance of olSourceWMTS');
}
const projection = source.getProjection();
if (!projection) {
throw new Error('Missing projection');
}
const metersPerUnit = projection.getMetersPerUnit();
if (!metersPerUnit) {
throw new Error('Missing metersPerUnit');
}
const tileGrid = source.getTileGrid();
if (!(tileGrid instanceof olTilegridWMTS)) {
throw new Error('tileGrid not instance of olTilegridWMTS');
}
const matrixIds = tileGrid.getMatrixIds();
/** @type {import('ngeo/print/mapfish-print-v3').MapFishPrintWmtsMatrix[]} */
const matrices = [];
for (let i = 0, ii = matrixIds.length; i < ii; ++i) {
const tileRange = tileGrid.getFullTileRange(i);
matrices.push(
/** @type {import('ngeo/print/mapfish-print-v3').MapFishPrintWmtsMatrix} */ ({
identifier: matrixIds[i],
scaleDenominator: (tileGrid.getResolution(i) * metersPerUnit) / 0.28e-3,
tileSize: olSize.toSize(tileGrid.getTileSize(i)),
topLeftCorner: tileGrid.getOrigin(i),
matrixSize: [tileRange.maxX - tileRange.minX, tileRange.maxY - tileRange.minY],
})
);
}
const dimensions = source.getDimensions();
const dimensionKeys = Object.keys(dimensions);
const object = /** @type {import('ngeo/print/mapfish-print-v3').MapFishPrintWmtsLayer} */ ({
baseURL: this.getWmtsUrl_(source),
dimensions: dimensionKeys,
dimensionParams: dimensions,
imageFormat: source.getFormat(),
layer: source.getLayer(),
matrices: matrices,
matrixSet: source.getMatrixSet(),
opacity: this.getOpacityOrInherited_(layer),
requestEncoding: source.getRequestEncoding(),
style: source.getStyle(),
type: 'WMTS',
version: source.getVersion(),
});
arr.push(object);
};
/**
* @param {import('ngeo/print/mapfish-print-v3').MapFishPrintLayer[]} arr Array.
* @param {import('ol/layer/WebGLTile').default<import('ol/source/Tile').default>} layer Layer.
*/
PrintService.prototype.encodeTileWmsLayer_ = function (arr, layer) {
if (!(layer instanceof olLayerTile)) {
throw new Error('layer not instance of olLayerTile');
}
const source = layer.getSource();
if (!(source instanceof olSourceTileWMS)) {
throw new Error('source not instance of olSourceTileWMS');
}
const urls = source.getUrls();
if (!urls) {
throw new Error('Missing urls');
}
this.encodeWmsLayer_(arr, layer, urls[0], source.getParams());
};
/**
* Return the WMTS URL to use in the print spec.
*
* @param {import('ol/source/WMTS').default} source The WMTS source.
* @returns {string} URL.
*/
PrintService.prototype.getWmtsUrl_ = function (source) {
const urls = source.getUrls();
if (!urls) {
throw new Error('Missing urls');
}
return getAbsoluteUrl_(urls[0]);
};
/**
* Return an opacity value for the specified layer.
*
* @param {import('ol/layer/Base').default} layer Layer.
* @returns {number} opacity Opacity value.
*/
PrintService.prototype.getOpacityOrInherited_ = function (layer) {
if (layer.get('inheritedOpacity') !== undefined) {
return layer.get('inheritedOpacity');
}
return layer.getOpacity();
};
/**
* Send a create report request to the MapFish Print service.
*
* @param {import('ngeo/print/mapfish-print-v3').MapFishPrintSpec} printSpec Print specification.
* @param {angular.IRequestShortcutConfig} [opt_httpConfig] $http config object.
* @returns {angular.IHttpPromise<import('ngeo/print/mapfish-print-v3').MapFishPrintReportResponse>} HTTP promise.
*/
PrintService.prototype.createReport = function (printSpec, opt_httpConfig) {
const format = printSpec.format || 'pdf';
const url = `${this.url_}/report.${format}`;
const httpConfig = /** @type {angular.IRequestShortcutConfig} */ ({
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
});
Object.assign(httpConfig, opt_httpConfig !== undefined ? opt_httpConfig : {});
return this.$http_.post(url, printSpec, httpConfig);
};
/**
* Get the status of a report.
*
* @param {string} ref Print report reference.
* @param {angular.IRequestShortcutConfig} [opt_httpConfig] $http config object.
* @returns {angular.IHttpPromise<import('ngeo/print/mapfish-print-v3').MapFishPrintStatusResponse>} HTTP promise.
*/
PrintService.prototype.getStatus = function (ref, opt_httpConfig) {
const httpConfig =
opt_httpConfig !== undefined ? opt_httpConfig : /** @type {angular.IRequestShortcutConfig} */ ({});
const url = `${this.url_}/status/${ref}.json`;
return this.$http_.get(url, httpConfig);
};
/**
* Get the URL of a report.
*
* @param {string} ref Print report reference.
* @returns {string} The report URL for this ref.
*/
PrintService.prototype.getReportUrl = function (ref) {
return `${this.url_}/report/${ref}`;
};
/**
* Get the print capabilities from MapFish Print.
*
* @param {angular.IRequestShortcutConfig} [opt_httpConfig] $http config object.
* @returns {angular.IHttpPromise<import('ngeo/print/mapfish-print-v3').MapFishPrintCapabilities>} HTTP promise.
*/
PrintService.prototype.getCapabilities = function (opt_httpConfig) {
const httpConfig =
opt_httpConfig !== undefined
? opt_httpConfig
: /** @type {angular.IRequestShortcutConfig} */ ({
withCredentials: true,
});
const url = `${this.url_}/capabilities.json`;
return this.$http_.get(url, httpConfig);
};
/**
* @param {angular.IHttpService} $http Angular $http service.
* @param {angular.gettext.gettextCatalog} gettextCatalog Gettext service.
* @param {import('ngeo/map/LayerHelper').LayerHelper} ngeoLayerHelper Ngeo Layer Helper.
* @returns {CreatePrint} The function to create a print service.
* @ngInject
* @ngdoc service
* @ngname ngeoCreatePrint
* @hidden
*/
export function createPrintServiceFactory($http, gettextCatalog, ngeoLayerHelper) {
return (
/**
* @param {string} url URL to MapFish print service.
* @returns {PrintService} The print service
*/
function (url) {
return new PrintService(url, $http, gettextCatalog, ngeoLayerHelper);
}
);
}
/**
* @type {angular.IModule}
* @hidden
*/
const myModule = angular.module('ngeoPrint', [ngeoMapLayerHelper.name]);
myModule.service('ngeoPrintService', PrintService);
myModule.factory('ngeoCreatePrint', createPrintServiceFactory);
export default myModule;