-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathLegendTool.js
More file actions
497 lines (459 loc) · 19.3 KB
/
LegendTool.js
File metadata and controls
497 lines (459 loc) · 19.3 KB
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
import $ from 'jquery'
import * as d3 from 'd3'
import L_ from '../../Basics/Layers_/Layers_'
import Map_ from '../../Basics/Map_/Map_'
import ToolController_ from '../../Basics/ToolController_/ToolController_'
//Add the tool markup if you want to do it this way
var markup = [].join('\n')
var LegendTool = {
height: 0,
width: 200,
activeLayerNames: null,
MMWebGISInterface: null,
targetId: null,
made: false,
displayOnStart: false,
justification: 'left',
initialize: function () {
//Get tool variables
this.displayOnStart = L_.getToolVars('legend')['displayOnStart']
this.justification = L_.getToolVars('legend')['justification']
if (this.justification == 'right') {
const toolController = d3.select('#toolcontroller_sepdiv')
const toolContent = d3.select('#toolContentSeparated_Legend')
toolController.style('top', '110px')
toolController.style('left', null)
toolController.style('right', '5px')
toolContent.style('left', null)
toolContent.style('right', '0px')
} else {
const toolController = d3
.select('#toolcontroller_sepdiv')
.clone(false)
.attr('id', 'toolcontroller_sepdiv_left')
$('#toolSeparated_Legend').appendTo('#toolcontroller_sepdiv_left')
toolController.style(
'top',
(L_.getToolVars('identifier')['justification'] || 'left') ==
'left'
? '75px'
: '40px'
)
toolController.style('left', '5px')
toolController.style('right', null)
}
},
make: function (targetId) {
this.targetId =
typeof targetId === 'string'
? targetId
: '__LegendTool_missing_targetId'
this.MMWebGISInterface = new interfaceWithMMWebGIS()
this.activeLayerNames = []
L_.subscribeOnLayerToggle('LegendTool', () => {
this.MMWebGISInterface = new interfaceWithMMWebGIS()
})
this.made = true
},
destroy: function () {
this.MMWebGISInterface.separateFromMMWebGIS()
this.targetId = null
L_.unsubscribeOnLayerToggle('LegendTool')
this.made = false
},
refreshLegends: refreshLegends,
overwriteLegends: overwriteLegends,
}
//
function interfaceWithMMWebGIS() {
this.separateFromMMWebGIS = function () {
separateFromMMWebGIS()
}
separateFromMMWebGIS()
LegendTool.tools = drawLegendHeader()
//Add the markup to tools or do it manually
//tools.html( markup );
//Add event functions and whatnot
//Draw legends
LegendTool.refreshLegends()
//Share everything. Don't take things that aren't yours.
// Put things back where you found them.
function separateFromMMWebGIS() {
let tools = d3.select(
LegendTool.targetId ? `#${LegendTool.targetId}` : '#toolPanel'
)
tools.style('background', 'var(--color-k)')
//Clear it
tools.selectAll('*').remove()
}
}
function refreshLegends() {
$('#LegendTool').empty()
for (let l in L_.layers.on) {
if (L_.layers.on[l] == true) {
if (L_.layers.data[l].type != 'header') {
if (L_.layers.data[l]?._legend === undefined
&& ((['image', 'tile'].includes(L_.layers.data[l].type) && L_.layers.data[l].cogTransform)
|| L_.layers.data[l].type === 'velocity')) {
const layersTool = ToolController_.getTool('LayersTool')
layersTool.populateCogScale(L_.layers.data[l].name)
}
// Check if there's a legend URL that points to an image
const legendURL = L_.layers.data[l]?.legend
if (legendURL && typeof legendURL === 'string') {
let isImageUrl = false
// First check for file extensions
const fileExtension = legendURL.toLowerCase().split('.').pop().split('?')[0] // Remove query params
const imageExtensions = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'tiff', 'tif', 'bmp', 'ico', 'avif']
if (imageExtensions.includes(fileExtension)) {
isImageUrl = true
} else if (['csv'].includes(fileExtension)) {
isImageUrl = false
} else {
// If no file extension and not a csv, check for image MIME types in URL parameters (e.g., WMS GetLegendGraphic)
try {
const url = new URL(legendURL)
const formatParam = url.searchParams.get('FORMAT') || url.searchParams.get('format')
if (formatParam) {
const imageMimeTypes = [
'image/png', 'image/jpeg', 'image/jpg', 'image/gif',
'image/svg+xml', 'image/webp', 'image/tiff',
'image/bmp', 'image/ico', 'image/avif'
]
const decodedFormat = decodeURIComponent(formatParam).toLowerCase()
if (imageMimeTypes.includes(decodedFormat)) {
isImageUrl = true
}
}
} catch (e) {
// URL parsing failed, treat as non-image
console.warn('Failed to parse legend URL:', legendURL)
}
}
if (isImageUrl) {
// Handle image legend directly
drawLegends(
LegendTool.tools,
legendURL, // Pass the URL string directly
l,
L_.layers.data[l].display_name,
L_.layers.opacity[l]
)
continue; // Skip the CSV processing below
}
}
if (L_.layers.data[l]?._legend != undefined) {
drawLegends(
LegendTool.tools,
L_.layers.data[l]?._legend,
l,
L_.layers.data[l].display_name,
L_.layers.opacity[l]
)
}
}
}
}
}
// The legends parameter should be an array of objects, where each object must contain
// the following keys: legend, layerUUID, display_name, opacity.
// The value for the legend key should be in the same format as what is stored in the
// layers data under the `_legend` key (i.e. `L_.layers.data[layerName]._legend`).
// layerUUID and display_name should be strings and opacity should be a number between 0 and 1.
function overwriteLegends(legends) {
if (!Array.isArray(legends)) {
console.warn('legends parameter must be an array.', legends)
return
}
if (legends.length < 1) {
console.warn('legends array is empty.', legends)
return
}
var tools = drawLegendHeader()
for (let l in legends) {
const { legend, layerUUID, display_name, opacity } = legends[l]
if (!legend || !layerUUID || !display_name || !opacity) {
console.warn('Unable to overwrite legends in LegendTool.', legends)
return
}
drawLegends(tools, legend, layerUUID, display_name, opacity)
}
}
function drawLegendHeader() {
//MMWebGIS should always have a div with id 'tools'
let tools = d3.select(
LegendTool.targetId ? `#${LegendTool.targetId}` : '#toolPanel'
)
tools.style('background', 'var(--color-k)')
//Clear it
tools.selectAll('*').remove()
tools
.append('div')
.style('height', '30px')
.style('line-height', '30px')
.style('font-size', '13px')
.style(
'padding-right',
LegendTool.justification === 'right' ? '30px' : '8px'
)
.style(
'padding-left',
LegendTool.justification === 'right' ? '10px' : '30px'
)
.style('color', 'var(--color-l)')
.style('background', 'var(--color-i)')
.style('font-family', 'lato-light')
.style('text-transform', 'uppercase')
.style('border-top-left-radius', '3px')
.style('border-top-right-radius', '3px')
.style('border-bottom', '1px solid var(--color-i)')
.html('Legend')
//Add a semantic container
tools = tools
.append('div')
.attr('id', 'LegendTool')
.style('color', '#dcdcdc')
.style('height', 'calc(100% - 40px)')
.style('max-height', 'calc(100vh - 185px)')
.style('border-bottom-left-radius', '3px')
.style('border-bottom-right-radius', '3px')
.style('overflow-y', 'auto')
return tools
}
function drawLegends(tools, _legend, layerUUID, display_name, opacity) {
if (tools == null) return
var c = tools
.append('div')
.attr('class', 'mmgisScrollbar')
.style('width', '100%')
.style('display', 'inline-block')
.style('padding-top', '5px')
.style('padding-right', '12px')
.style('border-bottom', '1px solid var(--color-i)')
c.append('div')
.attr('class', 'row')
.append('p')
.style('font-size', '13px')
.style('color', 'var(--color-f)')
.style('margin-bottom', '5px')
.style('padding-left', '8px')
.text(display_name)
let lastContinues = []
let lastShape = ''
// Check if _legend is an image URL (string)
if (typeof _legend === 'string') {
// Render image directly
const imageContainer = c
.append('div')
.attr('class', 'legend-image-container')
.style('display', 'flex')
.style('justify-content', 'center')
.style('margin', '4px')
.style('padding', '4px')
.style('overflow-x', 'hidden')
imageContainer
.append('img')
.attr('src', _legend.startsWith('http') ? _legend : L_.missionPath + _legend)
.attr('alt', `Legend for ${display_name}`)
.style('max-width', '300px')
.style('max-height', '220px')
.style('height', 'auto')
.style('background-color', 'white')
.style('border', '1px solid var(--color-i)')
.style('border-radius', '3px')
.style('opacity', opacity)
.on('load', function() {
// Set container max-width to image width (capped at 300px)
const maxImageWidth = Math.min(this.naturalWidth, 300)
imageContainer
.style('max-width', maxImageWidth + 'px')
.style('width', 'fit-content')
})
.on('error', function() {
// Handle image load error
d3.select(this.parentNode)
.append('div')
.style('color', '#ff6b6b')
.style('padding', '8px')
.style('text-align', 'center')
.style('font-size', '12px')
.text('Failed to load legend.')
d3.select(this).remove()
})
return // Exit early since we've rendered the image
}
for (let d in _legend) {
var shape = _legend[d].shapeImage && _legend[d].shapeImage.trim()
? _legend[d].shapeImage : _legend[d].shapeIcon && _legend[d].shapeIcon.trim()
? _legend[d].shapeIcon : _legend[d].shape
if (shape == 'continuous' || shape == 'discreet') {
if (lastShape != shape) {
if (lastContinues.length > 0) {
pushScale(lastContinues)
lastContinues = []
}
}
lastContinues.push({
color: _legend[d].color,
shape: shape,
value: _legend[d].value,
})
lastShape = shape
} else {
// finalize discreet and continuous
if (lastContinues.length > 0) {
pushScale(lastContinues)
lastContinues = []
}
var r = c
.append('div')
.attr('class', 'row')
.style('display', 'flex')
.style('margin', '0px 0px 8px 9px')
if (
shape == 'circle' ||
shape == 'square' ||
shape == 'rect'
) {
switch (shape) {
case 'circle':
r.append('div')
.attr('class', layerUUID + '_legendshape')
.style('width', '18px')
.style('height', '18px')
.style('background', _legend[d].color)
.style('opacity', opacity)
.style('border', `1px solid ${_legend[d].strokecolor}`)
.style('border-radius', '50%')
break
case 'square':
r.append('div')
.attr('class', layerUUID + '_legendshape')
.style('width', '18px')
.style('height', '18px')
.style('background', _legend[d].color)
.style('opacity', opacity)
.style('border', `1px solid ${_legend[d].strokecolor}`)
break
case 'rect':
r.append('div')
.attr('class', layerUUID + '_legendshape')
.style('width', '18px')
.style('height', '8px')
.style('margin', '5px 0px 5px 0px')
.style('background', _legend[d].color)
.style('opacity', opacity)
.style('border', `1px solid ${_legend[d].strokecolor}`)
break
default:
}
} else if (String(shape).toLowerCase().match(/\.(jpeg|jpg|gif|png|svg|webp)$/) != null) {
// Image markers
r.append('div')
.attr('class', layerUUID + '_legendcustom')
.style('width', '24px')
.style('height', '24px')
.style('background', _legend[d].color)
.style('opacity', opacity)
.style('border', `1px solid ${_legend[d].strokecolor}`)
.style('background-image', `url(${shape.startsWith("http")
? shape : L_.missionPath + shape})`)
.style('background-size', 'contain')
.style('background-repeat', 'no-repeat')
} else { // try using shape from Material Design Icon (mdi) library
r.append('div')
.attr('class', layerUUID + '_legendicon')
.style('width', '18px')
.style('height', '18px')
.append('i')
.attr('class', 'mdi mdi-18px mdi-' + shape)
.style('color', _legend[d].color)
.style('opacity', opacity)
.style('border', `1px solid ${_legend[d].strokecolor}`)
}
r.append('div')
.style('margin-left', '5px')
.style('height', '100%')
.style('line-height', '19px')
.style('font-size', '14px')
.style('overflow', 'hidden')
.style('white-space', 'nowrap')
.style('max-width', '270px')
.style('text-overflow', 'ellipsis')
.attr('title', _legend[d].value)
.text(_legend[d].value)
}
}
if (lastContinues.length > 0) {
pushScale(lastContinues)
lastContinues = []
}
function pushScale(lastContinues) {
var r = c
.append('div')
.attr('class', 'row')
.style('display', 'flex')
.style('margin', '0px 0px 8px 8px')
var gradient = r
.append('div')
.style('width', '19px')
.style('height', 19 * lastContinues.length + 'px')
.style('border', '1px solid black')
var values = r.append('div')
var gradientArray = []
for (let i = 0; i < lastContinues.length; i++) {
let v = values
.append('div')
.style('margin-left', '5px')
.style('height', '19px')
.style('line-height', '19px')
.style('font-size', '14px')
.style('position', 'relative')
.style('white-space', 'nowrap')
.text(lastContinues[i].value)
if (lastContinues[i].shape == 'continuous') {
v.append('div')
.style('position', 'absolute')
.style('width', '3px')
.style('height', '1px')
.style('background', 'white')
.style('left', '-23px')
.style('top', '10px')
.style('mix-blend-mode', 'difference')
v.append('div')
.style('position', 'absolute')
.style('width', '3px')
.style('height', '1px')
.style('background', 'white')
.style('left', '-9px')
.style('top', '10px')
.style('mix-blend-mode', 'difference')
let color = lastContinues[i].color
if (i === 0)
color += ' ' + (1 / lastContinues.length) * 50 + '%'
else if (i === lastContinues.length - 1)
color += ' ' + (100 - (1 / lastContinues.length) * 50) + '%'
gradientArray.push(color)
} else {
gradientArray.push(
lastContinues[i].color +
' ' +
(i / lastContinues.length) * 100 +
'%'
)
gradientArray.push(
lastContinues[i].color +
' ' +
((i + 1) / lastContinues.length) * 100 +
'%'
)
}
}
gradient.style(
'background',
'linear-gradient(to bottom, ' + gradientArray.join(',') + ')'
)
}
}
//Other functions
export default LegendTool