maplair 4.4.0 → 4.5.0

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.
Files changed (121) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/esm/control/AttributionControl.js +20 -3
  3. package/dist/esm/control/AttributionControl.js.map +1 -1
  4. package/dist/esm/control/LayersControl.js +35 -20
  5. package/dist/esm/control/LayersControl.js.map +1 -1
  6. package/dist/esm/control/ScaleControl.js +3 -3
  7. package/dist/esm/control/ScaleControl.js.map +1 -1
  8. package/dist/esm/control/ZoomControl.js +1 -0
  9. package/dist/esm/control/ZoomControl.js.map +1 -1
  10. package/dist/esm/core/Util.js +1 -1
  11. package/dist/esm/core/Util.js.map +1 -1
  12. package/dist/esm/dom/DomEvent.PointerEvents.js +19 -2
  13. package/dist/esm/dom/DomEvent.PointerEvents.js.map +1 -1
  14. package/dist/esm/dom/Draggable.js +6 -2
  15. package/dist/esm/dom/Draggable.js.map +1 -1
  16. package/dist/esm/geo/LatLng.js +1 -1
  17. package/dist/esm/geo/LatLng.js.map +1 -1
  18. package/dist/esm/geo/LatLngBounds.js +1 -1
  19. package/dist/esm/geo/LatLngBounds.js.map +1 -1
  20. package/dist/esm/geometry/Bounds.js +1 -1
  21. package/dist/esm/geometry/Bounds.js.map +1 -1
  22. package/dist/esm/geometry/Point.js +4 -2
  23. package/dist/esm/geometry/Point.js.map +1 -1
  24. package/dist/esm/geometry/PolyUtil.js +10 -3
  25. package/dist/esm/geometry/PolyUtil.js.map +1 -1
  26. package/dist/esm/layer/BlanketOverlay.js +2 -1
  27. package/dist/esm/layer/BlanketOverlay.js.map +1 -1
  28. package/dist/esm/layer/DivOverlay.js +3 -3
  29. package/dist/esm/layer/DivOverlay.js.map +1 -1
  30. package/dist/esm/layer/ImageOverlay.js +1 -1
  31. package/dist/esm/layer/ImageOverlay.js.map +1 -1
  32. package/dist/esm/layer/Layer.js +1 -1
  33. package/dist/esm/layer/Layer.js.map +1 -1
  34. package/dist/esm/layer/Popup.js +3 -4
  35. package/dist/esm/layer/Popup.js.map +1 -1
  36. package/dist/esm/layer/Tooltip.js +31 -22
  37. package/dist/esm/layer/Tooltip.js.map +1 -1
  38. package/dist/esm/layer/marker/Icon.js +25 -6
  39. package/dist/esm/layer/marker/Icon.js.map +1 -1
  40. package/dist/esm/layer/marker/Marker.Drag.js +5 -5
  41. package/dist/esm/layer/marker/Marker.Drag.js.map +1 -1
  42. package/dist/esm/layer/marker/Marker.js +5 -5
  43. package/dist/esm/layer/marker/Marker.js.map +1 -1
  44. package/dist/esm/layer/tile/GridLayer.js +11 -5
  45. package/dist/esm/layer/tile/GridLayer.js.map +1 -1
  46. package/dist/esm/layer/tile/TileLayer.js +10 -6
  47. package/dist/esm/layer/tile/TileLayer.js.map +1 -1
  48. package/dist/esm/layer/tile/WMSTileLayer.js +7 -3
  49. package/dist/esm/layer/tile/WMSTileLayer.js.map +1 -1
  50. package/dist/esm/layer/vector/Canvas.js +2 -2
  51. package/dist/esm/layer/vector/Canvas.js.map +1 -1
  52. package/dist/esm/layer/vector/Circle.js +2 -3
  53. package/dist/esm/layer/vector/Circle.js.map +1 -1
  54. package/dist/esm/layer/vector/CircleMarker.js +6 -3
  55. package/dist/esm/layer/vector/CircleMarker.js.map +1 -1
  56. package/dist/esm/layer/vector/Path.ZoomStyles.js +4 -1
  57. package/dist/esm/layer/vector/Path.ZoomStyles.js.map +1 -1
  58. package/dist/esm/map/Map.Rotation.js +3 -2
  59. package/dist/esm/map/Map.Rotation.js.map +1 -1
  60. package/dist/esm/map/Map.js +58 -26
  61. package/dist/esm/map/Map.js.map +1 -1
  62. package/dist/esm/map/MapSync.js +1 -1
  63. package/dist/esm/map/MapSync.js.map +1 -1
  64. package/dist/esm/map/handler/BoxZoomHandler.js +2 -0
  65. package/dist/esm/map/handler/BoxZoomHandler.js.map +1 -1
  66. package/dist/esm/map/handler/DragHandler.js +7 -2
  67. package/dist/esm/map/handler/DragHandler.js.map +1 -1
  68. package/dist/esm/map/handler/PinchZoomHandler.js +1 -1
  69. package/dist/esm/map/handler/PinchZoomHandler.js.map +1 -1
  70. package/dist/esm/map/handler/ScrollWheelZoomHandler.js +1 -1
  71. package/dist/esm/map/handler/ScrollWheelZoomHandler.js.map +1 -1
  72. package/dist/esm/map/handler/TapDragZoomHandler.js +1 -1
  73. package/dist/esm/map/handler/TapDragZoomHandler.js.map +1 -1
  74. package/dist/esm/package.js +1 -1
  75. package/dist/maplair-global-src.js +289 -140
  76. package/dist/maplair-global-src.js.map +1 -1
  77. package/dist/maplair-global.js +2 -2
  78. package/dist/maplair-global.js.map +1 -1
  79. package/dist/maplair-src.js +289 -140
  80. package/dist/maplair-src.js.map +1 -1
  81. package/dist/maplair.css +1 -1
  82. package/dist/maplair.js +2 -2
  83. package/dist/maplair.js.map +1 -1
  84. package/package.json +1 -1
  85. package/src/control/AttributionControl.js +29 -3
  86. package/src/control/LayersControl.js +47 -27
  87. package/src/control/ScaleControl.js +6 -3
  88. package/src/control/ZoomControl.js +1 -0
  89. package/src/core/Util.js +1 -1
  90. package/src/dom/DomEvent.PointerEvents.js +22 -2
  91. package/src/dom/Draggable.js +6 -2
  92. package/src/geo/LatLng.js +2 -1
  93. package/src/geo/LatLngBounds.js +1 -1
  94. package/src/geometry/Bounds.js +1 -1
  95. package/src/geometry/Point.js +4 -2
  96. package/src/geometry/PolyUtil.js +12 -3
  97. package/src/layer/BlanketOverlay.js +5 -2
  98. package/src/layer/DivOverlay.js +3 -3
  99. package/src/layer/ImageOverlay.js +3 -2
  100. package/src/layer/Layer.js +1 -1
  101. package/src/layer/Popup.js +3 -4
  102. package/src/layer/Tooltip.js +34 -27
  103. package/src/layer/marker/Icon.js +25 -5
  104. package/src/layer/marker/Marker.Drag.js +6 -6
  105. package/src/layer/marker/Marker.js +5 -5
  106. package/src/layer/tile/GridLayer.js +20 -7
  107. package/src/layer/tile/TileLayer.js +14 -7
  108. package/src/layer/tile/WMSTileLayer.js +4 -2
  109. package/src/layer/vector/Canvas.js +2 -2
  110. package/src/layer/vector/Circle.js +3 -5
  111. package/src/layer/vector/CircleMarker.js +5 -2
  112. package/src/layer/vector/Path.ZoomStyles.js +5 -3
  113. package/src/map/Map.Rotation.js +6 -3
  114. package/src/map/Map.js +63 -32
  115. package/src/map/MapSync.js +1 -1
  116. package/src/map/handler/BoxZoomHandler.js +3 -0
  117. package/src/map/handler/DragHandler.js +5 -5
  118. package/src/map/handler/PinchZoomHandler.js +1 -1
  119. package/src/map/handler/ScrollWheelZoomHandler.js +1 -1
  120. package/src/map/handler/TapDragZoomHandler.js +1 -1
  121. package/src/maplair.css +12 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maplair",
3
- "version": "4.4.0",
3
+ "version": "4.5.0",
4
4
  "homepage": "https://maplair.org/",
5
5
  "description": "JavaScript library for mobile-friendly interactive maps",
6
6
  "author": "Simon Legner",
@@ -64,6 +64,7 @@ export class AttributionControl extends Control {
64
64
  this._attributions = {};
65
65
  this._orders = {};
66
66
  this._layerAttributions = new Map();
67
+ this._shownLayers = new Set();
67
68
 
68
69
  this.callInitHooks(AttributionControl);
69
70
  }
@@ -93,7 +94,7 @@ export class AttributionControl extends Control {
93
94
  * @returns {Record<string, Function>}
94
95
  */
95
96
  getEvents() {
96
- return {layeradd: this._addLayer, layerremove: this._removeLayer};
97
+ return {layeradd: this._addLayer, layerremove: this._removeLayer, zoomend: this._onZoomEnd};
97
98
  }
98
99
 
99
100
  /**
@@ -110,14 +111,39 @@ export class AttributionControl extends Control {
110
111
  if (!text || this._layerAttributions.has(layer)) { return; }
111
112
 
112
113
  this._layerAttributions.set(layer, text);
113
- this.addAttribution(text, layer.options?.attributionOrder);
114
+ this._updateLayer(layer);
114
115
  }
115
116
 
116
117
  _removeLayer({layer}) {
117
- this.removeAttribution(this._layerAttributions.get(layer));
118
+ if (this._shownLayers.delete(layer)) {
119
+ this.removeAttribution(this._layerAttributions.get(layer));
120
+ }
118
121
  this._layerAttributions.delete(layer);
119
122
  }
120
123
 
124
+ _onZoomEnd() {
125
+ for (const layer of this._layerAttributions.keys()) {
126
+ this._updateLayer(layer);
127
+ }
128
+ }
129
+
130
+ // Layers with `minZoom`/`maxZoom` options (e.g. tile layers) aren't displayed outside that range.
131
+ _updateLayer(layer) {
132
+ const {minZoom = -Infinity, maxZoom = Infinity} = layer.options ?? {},
133
+ zoom = this._map.getZoom(),
134
+ show = zoom >= minZoom && zoom <= maxZoom;
135
+ if (show === this._shownLayers.has(layer)) { return; }
136
+
137
+ const text = this._layerAttributions.get(layer);
138
+ if (show) {
139
+ this._shownLayers.add(layer);
140
+ this.addAttribution(text, layer.options?.attributionOrder);
141
+ } else {
142
+ this._shownLayers.delete(layer);
143
+ this.removeAttribution(text);
144
+ }
145
+ }
146
+
121
147
  /**
122
148
  * The HTML text shown before the attributions. Pass `false` to disable.
123
149
  * @param {string|false} prefix
@@ -160,6 +160,7 @@ export class LayersControl extends Control {
160
160
  this._lastZIndex = 0;
161
161
  this._handlingClick = false;
162
162
  this._preventClick = false;
163
+ this._needsUpdate = false;
163
164
 
164
165
  for (const [name, layer] of Object.entries(baseLayers ?? {})) {
165
166
  this._addLayer(layer, name);
@@ -271,6 +272,8 @@ export class LayersControl extends Control {
271
272
  * @returns {this}
272
273
  */
273
274
  selectLayer(layer) {
275
+ // the list isn't rebuilt while collapsed
276
+ if (this._needsUpdate) { this._update(true); }
274
277
  const input = this._layerControlInputs.find(input => input._layer === layer);
275
278
  if (input && !input.checked) {
276
279
  input.checked = true;
@@ -287,6 +290,7 @@ export class LayersControl extends Control {
287
290
  clearTimeout(this._collapseDelayTimeout);
288
291
 
289
292
  this._container.classList.add('maplair-control-layers-expanded');
293
+ if (this._needsUpdate) { this._update(); }
290
294
  this._section.style.height = '';
291
295
  const acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
292
296
  if (acceptableHeight < this._section.clientHeight) {
@@ -307,6 +311,7 @@ export class LayersControl extends Control {
307
311
  if (this.options.inline) {
308
312
  return this;
309
313
  }
314
+ clearTimeout(this._collapseDelayTimeout);
310
315
  if (this.options.collapseDelay > 0) {
311
316
  this._collapseDelayTimeout = setTimeout(() => {
312
317
  this._container.classList.remove('maplair-control-layers-expanded');
@@ -335,21 +340,11 @@ export class LayersControl extends Control {
335
340
 
336
341
  const section = this._section = DomUtil.create('fieldset', `${className}-list`);
337
342
  section.setAttribute('aria-label', this._getTitle());
343
+ section.tabIndex = -1;
338
344
 
339
- if (collapsed) {
340
- this._map.on('click', this.collapse, this);
341
-
342
- DomEvent.on(container, {
343
- pointerenter: this._expandSafely,
344
- // on touch devices, pointerleave fires while clicking a checkbox, which shouldn't collapse the control
345
- pointerleave(e) {
346
- if (e.pointerType !== 'touch') { this.collapse(); }
347
- }
348
- }, this);
349
- }
350
-
345
+ let link;
351
346
  if (!this.options.inline) {
352
- const link = this._layersLink = DomUtil.create('button', `${className}-toggle`, container);
347
+ link = this._layersLink = DomUtil.create('button', `${className}-toggle`, container);
353
348
  link.type = 'button';
354
349
  link.title = this._getTitle();
355
350
  link.setAttribute('aria-label', link.title);
@@ -361,21 +356,36 @@ export class LayersControl extends Control {
361
356
  link.replaceChildren(toggleContent);
362
357
  }
363
358
 
364
- DomEvent.on(link, {
365
- keydown(e) {
366
- if (e.code === 'Enter') {
367
- this._expandSafely();
368
- }
369
- },
370
- // Certain screen readers intercept the key event and instead send a click event
371
- click(e) {
372
- e.preventDefault();
373
- this._expandSafely();
359
+ // also for Enter and Space, and for screen readers that send a click instead of the key event
360
+ DomEvent.on(link, 'click', (e) => {
361
+ e.preventDefault();
362
+ const focused = document.activeElement === link;
363
+ this._expandSafely();
364
+ if (focused) { section.focus(); }
365
+ });
366
+ }
367
+
368
+ if (collapsed) {
369
+ this._map.on('click', this.collapse, this);
370
+
371
+ DomEvent.on(container, {
372
+ pointerenter: this._expandSafely,
373
+ // on touch devices, pointerleave fires while clicking a checkbox, which shouldn't collapse the control
374
+ pointerleave(e) {
375
+ if (e.pointerType !== 'touch') { this.collapse(); }
374
376
  }
375
377
  }, this);
376
- }
377
378
 
378
- if (!collapsed) {
379
+ // the list only takes focus while expanded; skip `collapseDelay`, as the toggle is hidden until then
380
+ DomEvent.on(section, 'keydown', (e) => {
381
+ if (e.key === 'Escape') {
382
+ clearTimeout(this._collapseDelayTimeout);
383
+ container.classList.remove(`${className}-expanded`);
384
+ link.focus();
385
+ e.preventDefault();
386
+ }
387
+ });
388
+ } else {
379
389
  this.expand();
380
390
  }
381
391
 
@@ -409,9 +419,17 @@ export class LayersControl extends Control {
409
419
  this._expandIfNotCollapsed();
410
420
  }
411
421
 
412
- _update() {
422
+ _update(force) {
413
423
  if (!this._container) { return this; }
414
424
 
425
+ // Rebuilding on every layer change makes adding n layers O(n²). The list is hidden
426
+ // while collapsed, so leave it until `expand()` shows it.
427
+ if (!force && !this._container.classList.contains('maplair-control-layers-expanded')) {
428
+ this._needsUpdate = true;
429
+ return this;
430
+ }
431
+ this._needsUpdate = false;
432
+
415
433
  this._baseLayersList.replaceChildren();
416
434
  this._overlaysList.replaceChildren();
417
435
 
@@ -434,6 +452,9 @@ export class LayersControl extends Control {
434
452
 
435
453
  this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
436
454
 
455
+ // once for the whole list, as it loops over every input
456
+ this._checkDisabledLayers();
457
+
437
458
  return this;
438
459
  }
439
460
 
@@ -486,7 +507,6 @@ export class LayersControl extends Control {
486
507
  const container = group ? this._getGroupContainer(list, group.group) : list;
487
508
  container.append(label);
488
509
 
489
- this._checkDisabledLayers();
490
510
  return label;
491
511
  }
492
512
 
@@ -134,14 +134,17 @@ export class ScaleControl extends Control {
134
134
  }
135
135
 
136
136
  _getRoundNum(num) {
137
- const pow10 = 10 ** ((`${Math.floor(num)}`).length - 1);
138
- let d = num / pow10;
137
+ // Below 1, count the zeros after the decimal point instead, so that 0.35 gives 0.3 rather than 1
138
+ // (which would draw the scale wider than maxWidth)
139
+ const exponent = num < 1 ? Math.floor(Math.log10(num)) : (`${Math.floor(num)}`).length - 1;
140
+ let d = num / 10 ** exponent;
139
141
 
140
142
  d = d >= 10 ? 10 :
141
143
  d >= 5 ? 5 :
142
144
  d >= 3 ? 3 :
143
145
  d >= 2 ? 2 : 1;
144
146
 
145
- return pow10 * d;
147
+ // dividing by a power of ten keeps 0.3 exact, where 3 * 0.1 gives 0.30000000000000004
148
+ return exponent < 0 ? d / 10 ** -exponent : d * 10 ** exponent;
146
149
  }
147
150
  }
@@ -129,6 +129,7 @@ export class ZoomControl extends Control {
129
129
 
130
130
  _updateDisabled() {
131
131
  const map = this._map;
132
+ if (!map) { return; } // `onAdd` applies the state
132
133
  for (const [button, limit] of [[this._zoomInButton, map.getMaxZoom()], [this._zoomOutButton, map.getMinZoom()]]) {
133
134
  const disabled = this._disabled || map._zoom === limit;
134
135
  button.classList.toggle('maplair-disabled', disabled);
package/src/core/Util.js CHANGED
@@ -154,7 +154,7 @@ function getDefaultOptions(cls) {
154
154
  return defaults;
155
155
  }
156
156
 
157
- const templateRe = /\{ *([\w_ -]+) *\}/g;
157
+ const templateRe = /\{ *([\w_ -]+?) *\}/g;
158
158
 
159
159
  /**
160
160
  * Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
@@ -32,11 +32,30 @@ function disablePointerDetection(el) {
32
32
  el.removeEventListener('pointercancel', _onDelete, {capture: true});
33
33
  }
34
34
 
35
- // capturing throws for synthetic pointers the browser doesn't know about, so only capture real ones
35
+ /**
36
+ * Whether `el` is inside an element that `DomEvent.disableClickPropagation` was called
37
+ * on (before reaching `container`), or detached from the DOM.
38
+ * @internal
39
+ * @param {Node|null} el
40
+ * @param {EventTarget|null} container
41
+ * @returns {boolean}
42
+ */
43
+ function isClickDisabled(el, container) {
44
+ while (el && el !== container) {
45
+ if (el['_maplair_disable_click'] || !el.parentNode) { return true; }
46
+ el = el.parentNode;
47
+ }
48
+ return false;
49
+ }
50
+
36
51
  function _onSet(e) {
52
+ lastPointerType = e.pointerType;
53
+ // pointers in controls and popups can't start map interactions, and capturing them breaks native widgets there
54
+ // (like the clear button of a search input), so leave them to the browser
55
+ if (isClickDisabled(e.target, e.currentTarget)) { return; }
56
+ // capturing throws for synthetic pointers the browser doesn't know about, so only capture real ones
37
57
  if (e.isTrusted) { e.target.setPointerCapture(e.pointerId); }
38
58
  activePointers.set(e.pointerId, e);
39
- lastPointerType = e.pointerType;
40
59
  }
41
60
 
42
61
  function _onUpdate(e) {
@@ -108,6 +127,7 @@ export {
108
127
  enablePointerDetection,
109
128
  disablePointerDetection,
110
129
  getPointers,
130
+ isClickDisabled,
111
131
  simulateDblclick
112
132
  };
113
133
 
@@ -15,9 +15,13 @@ import * as PointerEvents from './DomEvent.PointerEvents.js';
15
15
  */
16
16
 
17
17
  /**
18
- * The event object of `dragstart`, `predrag` and `drag` of `Draggable`.
18
+ * The event object of `dragstart`, `predrag` and `drag` of `Draggable`, and of
19
+ * `movestart` and `dragstart` of draggable markers.
19
20
  * @typedef {object} DraggableEvent
20
- * @property {PointerEvent} originalEvent The DOM event of the pointer which drags.
21
+ * @property {PointerEvent|KeyboardEvent} originalEvent The DOM event of the pointer which
22
+ * drags: for `dragstart`, the `pointermove` that moved the pointer past `clickTolerance`
23
+ * (not the `pointerdown`), or the `keydown` of an arrow key that moves a focused
24
+ * draggable marker.
21
25
  * @extends MaplairEvent
22
26
  */
23
27
 
package/src/geo/LatLng.js CHANGED
@@ -256,7 +256,8 @@ export function haversineDistance(latlng1, latlng2, R) {
256
256
  lat2 = latlng2.lat * rad,
257
257
  sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
258
258
  sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
259
- a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
259
+ // clamp, since rounding can push this slightly above 1 for antipodal points and make `sqrt(1 - a)` NaN
260
+ a = Math.min(sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon, 1),
260
261
  c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
261
262
  return R * c;
262
263
  }
@@ -314,6 +314,6 @@ export class LatLngBounds {
314
314
 
315
315
  // Whether `obj` has the shape of a `LatLngExpression` rather than of bounds.
316
316
  function isLatLngExpression(obj) {
317
- return obj instanceof LatLng || (Array.isArray(obj) ? typeof obj[0] !== 'object' :
317
+ return obj instanceof LatLng || (Array.isArray(obj) ? obj.length > 0 && typeof obj[0] !== 'object' :
318
318
  typeof obj === 'object' && obj !== null && 'lat' in obj);
319
319
  }
@@ -258,5 +258,5 @@ export class Bounds {
258
258
 
259
259
  // Whether `obj` is a point (or an array or object literal of one) rather than bounds
260
260
  function isPointExpression(obj) {
261
- return obj instanceof Point || (Array.isArray(obj) ? typeof obj[0] !== 'object' : 'x' in obj);
261
+ return obj instanceof Point || (Array.isArray(obj) ? obj.length > 0 && typeof obj[0] !== 'object' : 'x' in obj);
262
262
  }
@@ -167,20 +167,22 @@ export class Point {
167
167
  * `scale`. In linear algebra terms, multiply the point by the
168
168
  * [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
169
169
  * defined by `scale`.
170
- * @param {Point} point The scale.
170
+ * @param {PointExpression} point The scale.
171
171
  * @returns {Point}
172
172
  */
173
173
  scaleBy(point) {
174
+ point = Point.from(point);
174
175
  return new Point(this.x * point.x, this.y * point.y);
175
176
  }
176
177
 
177
178
  /**
178
179
  * Inverse of `scaleBy`. Divide each coordinate of the current point by
179
180
  * each coordinate of `scale`.
180
- * @param {Point} point The scale.
181
+ * @param {PointExpression} point The scale.
181
182
  * @returns {Point}
182
183
  */
183
184
  unscaleBy(point) {
185
+ point = Point.from(point);
184
186
  return new Point(this.x / point.x, this.y / point.y);
185
187
  }
186
188
 
@@ -1,8 +1,8 @@
1
1
  import * as LineUtil from './LineUtil.js';
2
2
  import {LatLng} from '../geo/LatLng.js';
3
3
  import {Point} from './Point.js';
4
+ import {Bounds} from './Bounds.js';
4
5
  /** @import {LatLngExpression} from '../geo/LatLng.js' */
5
- /** @import {Bounds} from './Bounds.js' */
6
6
  /** @import {CRS} from '../geo/crs/CRS.js' */
7
7
 
8
8
  // PolyUtil: various utility functions for polygon geometries.
@@ -81,8 +81,17 @@ export function polygonCenter(latlngs, crs) {
81
81
  area += f;
82
82
  }
83
83
 
84
- // area is 0 when the polygon is so small that all points are on the same pixel
85
- return crs.unproject(area === 0 ? origin : new Point(x / (3 * area), y / (3 * area))._add(origin));
84
+ if (area !== 0) { return crs.unproject(new Point(x / (3 * area), y / (3 * area))._add(origin)); }
85
+
86
+ // area is 0 when all points lie on one line (or on the same spot), or when the ring goes back over its own edges;
87
+ // take the middle of the points' extent and snap it to the closest point of the ring so it stays on the shape
88
+ const mid = new Bounds(points).getCenter();
89
+ let center = points[0];
90
+ for (let i = 0, j = len - 1; i < len; j = i++) {
91
+ const p = LineUtil._sqClosestPointOnSegment(mid, points[j], points[i]);
92
+ if (p.distanceTo(mid) < center.distanceTo(mid)) { center = p; }
93
+ }
94
+ return crs.unproject(center._add(origin));
86
95
  }
87
96
 
88
97
  /**
@@ -117,8 +117,11 @@ export class BlanketOverlay extends Layer {
117
117
  viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
118
118
  currentCenterPoint = this._map.project(this._center, zoom),
119
119
  topLeftOffset = viewHalf.multiplyBy(-scale)._add(currentCenterPoint)
120
- ._subtract(this._map._getNewPixelOrigin(center, zoom))
121
- ._round();
120
+ ._subtract(this._map._getNewPixelOrigin(center, zoom));
121
+
122
+ // a scaled container is resampled anyway, and rounding where its corner lands would make its content away
123
+ // from the corner jitter against the zoom motion
124
+ if (scale === 1) { this._map._snapLayerPoint(topLeftOffset); }
122
125
 
123
126
  DomUtil.setTransform(this._container, topLeftOffset, scale);
124
127
  }
@@ -284,8 +284,8 @@ export class DivOverlay extends Layer {
284
284
 
285
285
  /**
286
286
  * Sets the HTML content of the overlay. A `String` argument is rendered as
287
- * HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify)
288
- * or pass an `HTMLElement` with safe `textContent` instead. A `DocumentFragment`
287
+ * HTML; if it may contain untrusted input, sanitize it or pass an `HTMLElement`
288
+ * with safe `textContent` instead. A `DocumentFragment`
289
289
  * can be passed as well. If a function is passed the source layer will be passed
290
290
  * to the function. The function should return a `String`, `HTMLElement` or
291
291
  * `DocumentFragment` to be used in the overlay.
@@ -441,7 +441,7 @@ export class DivOverlay extends Layer {
441
441
  _updatePosition() {
442
442
  if (!this._map) { return; }
443
443
 
444
- const pos = this._map.latLngToLayerPoint(this._latlng)._round(),
444
+ const pos = this._map._snapLayerPoint(this._map.latLngToLayerPoint(this._latlng)),
445
445
  offset = Point.from(this.options.offset);
446
446
 
447
447
  this._setContainerPosition(pos.add(this._getAnchor()));
@@ -284,9 +284,10 @@ export class ImageOverlay extends Layer {
284
284
 
285
285
  _reset() {
286
286
  const image = this._image,
287
+ map = this._map,
287
288
  bounds = new Bounds(
288
- this._map.latLngToLayerPoint(this._bounds.getNorthWest())._round(),
289
- this._map.latLngToLayerPoint(this._bounds.getSouthEast())._round()),
289
+ map._snapLayerPoint(map.latLngToLayerPoint(this._bounds.getNorthWest())),
290
+ map._snapLayerPoint(map.latLngToLayerPoint(this._bounds.getSouthEast()))),
290
291
  size = bounds.getSize();
291
292
 
292
293
  DomUtil.setPosition(image, bounds.min);
@@ -185,7 +185,7 @@ const mapLayerMethods = {
185
185
  this.fire('zoomlevelschange');
186
186
  }
187
187
 
188
- if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
188
+ if (this.options.maxZoom === undefined && this._layersMaxZoom !== undefined && this.getZoom() > this._layersMaxZoom) {
189
189
  this.setZoom(this._layersMaxZoom);
190
190
  }
191
191
  if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
@@ -124,8 +124,8 @@ const layerPopupMethods = {
124
124
  /**
125
125
  * Binds a popup to the layer with the passed `content` and sets up the
126
126
  * necessary event listeners. A `String` argument is rendered as HTML; if it
127
- * may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an
128
- * `HTMLElement` with safe `textContent` instead. If a `Function` is passed
127
+ * may contain untrusted input, sanitize it or pass an `HTMLElement` with safe
128
+ * `textContent` instead. If a `Function` is passed
129
129
  * it will receive the layer as the first argument and should return a
130
130
  * `String`, `HTMLElement` or `DocumentFragment`.
131
131
  * @group Popup methods
@@ -289,8 +289,7 @@ const layerPopupMethods = {
289
289
  *
290
290
  * **Security note.** Popup string content is rendered as HTML. If your content
291
291
  * may include untrusted input (e.g. data from users or external APIs), sanitize
292
- * it with a library like [DOMPurify](https://github.com/cure53/DOMPurify), or
293
- * build a DOM element using `textContent` to render it as plain text:
292
+ * it first, or build a DOM element using `textContent` to render it as plain text:
294
293
  *
295
294
  * ```js
296
295
  * const el = document.createElement('div');
@@ -35,7 +35,8 @@ function clampTip(tipShift, size) {
35
35
  * Options of `Tooltip`.
36
36
  * @typedef {object} TooltipOptions
37
37
  * @property {string} [pane='tooltipPane'] `Map pane` where the tooltip will be added.
38
- * @property {PointExpression} [offset=[0, 0]] Optional offset of the tooltip position.
38
+ * @property {PointExpression} [offset=[0, 0]] Optional offset of the tooltip position, in
39
+ * pixels. Mirrored horizontally when an `auto` tooltip opens to the left.
39
40
  * @property {'right'|'left'|'top'|'bottom'|'center'|'auto'} [direction='auto']
40
41
  * Direction where to open the tooltip. Possible values are: `right`, `left`, `top`,
41
42
  * `bottom`, `center`, `auto`. `auto` chooses the direction with enough space when
@@ -112,8 +113,8 @@ const layerTooltipMethods = {
112
113
  /**
113
114
  * Binds a tooltip to the layer with the passed `content` and sets up the
114
115
  * necessary event listeners. A `String` argument is rendered as HTML; if it
115
- * may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an
116
- * `HTMLElement` with safe `textContent` instead. If a `Function` is passed
116
+ * may contain untrusted input, sanitize it or pass an `HTMLElement` with safe
117
+ * `textContent` instead. If a `Function` is passed
117
118
  * it will receive the layer as the first argument and should return a
118
119
  * `String`, `HTMLElement` or `DocumentFragment`.
119
120
  * @group Tooltip methods
@@ -342,8 +343,7 @@ const layerTooltipMethods = {
342
343
  *
343
344
  * **Security note.** Tooltip string content is rendered as HTML. If your content
344
345
  * may include untrusted input (e.g. data from users or external APIs), sanitize
345
- * it with a library like [DOMPurify](https://github.com/cure53/DOMPurify), or
346
- * build a DOM element using `textContent` to render it as plain text:
346
+ * it first, or build a DOM element using `textContent` to render it as plain text:
347
347
  *
348
348
  * ```js
349
349
  * const el = document.createElement('div');
@@ -405,7 +405,8 @@ export class Tooltip extends DivOverlay {
405
405
 
406
406
  if (this._source) {
407
407
  this.addEventParent(this._source);
408
- this._source.getElement?.()?.setAttribute('aria-describedby', this._container.id);
408
+ this._ariaSource = this._source.getElement?.();
409
+ this._ariaSource?.setAttribute('aria-describedby', this._container.id);
409
410
 
410
411
  this._source.fire('tooltipopen', {tooltip: this}, true);
411
412
  }
@@ -423,6 +424,11 @@ export class Tooltip extends DivOverlay {
423
424
  if (this._source) {
424
425
  this.removeEventParent(this._source);
425
426
 
427
+ // drop the reference to the removed tooltip unless something else replaced it since
428
+ const el = this._ariaSource;
429
+ if (el?.getAttribute('aria-describedby') === this._container.id) { el.removeAttribute('aria-describedby'); }
430
+ this._ariaSource = null;
431
+
426
432
  this._source.fire('tooltipclose', {tooltip: this}, true);
427
433
  }
428
434
  }
@@ -472,17 +478,14 @@ export class Tooltip extends DivOverlay {
472
478
  const container = this._container,
473
479
  tooltipWidth = container.offsetWidth,
474
480
  tooltipHeight = container.offsetHeight,
475
- offset = new Point(this.options.offset),
476
- anchor = this._getAnchor();
481
+ offset = new Point(this.options.offset);
477
482
 
478
483
  if (!(direction in directions)) {
479
- ({direction, shift} = this._getAutoPlacement(pos, offset, anchor, tooltipWidth, tooltipHeight));
480
- if (direction === 'left') {
481
- // mirror the offset and anchor, which are meant for the right side
482
- offset.x = -offset.x;
483
- anchor.x = -anchor.x;
484
- }
484
+ ({direction, shift} = this._getAutoPlacement(pos, offset, tooltipWidth, tooltipHeight));
485
+ // mirror the offset, which is meant for the right side
486
+ if (direction === 'left') { offset.x = -offset.x; }
485
487
  }
488
+ const anchor = this._getAnchor(direction);
486
489
 
487
490
  const [fx, fy] = directions[direction];
488
491
  pos = pos.subtract(new Point(tooltipWidth * fx, tooltipHeight * fy, true)).add(offset).add(anchor).add(shift);
@@ -507,17 +510,20 @@ export class Tooltip extends DivOverlay {
507
510
  // Chooses the direction of an `auto` tooltip by the available space:
508
511
  // preferably the side towards the center, otherwise the opposite side,
509
512
  // above or below. The tooltip is shifted along that side to stay in view.
510
- _getAutoPlacement(pos, offset, anchor, width, height) {
513
+ _getAutoPlacement(pos, offset, width, height) {
511
514
  const area = this._getAutoArea(),
512
515
  point = this._map.layerPointToContainerPoint(pos),
513
- x = point.x + offset.x + anchor.x,
514
- y = point.y + offset.y + anchor.y,
515
- // the space for each direction, see `direction` for the mirrored left side
516
- space = {
517
- right: area.max.x - x - width - tipSize,
518
- left: point.x - offset.x - anchor.x - area.min.x - width - tipSize,
519
- top: y - area.min.y - height - tipSize,
520
- bottom: area.max.y - y - height - tipSize
516
+ // where the tooltip attaches for each direction, with the offset mirrored on the left side
517
+ at = {};
518
+ for (const d of ['right', 'left', 'top', 'bottom']) {
519
+ at[d] = point.add(this._getAnchor(d)).add(d === 'left' ? [-offset.x, offset.y] : offset);
520
+ }
521
+ // the space for each direction
522
+ const space = {
523
+ right: area.max.x - at.right.x - width - tipSize,
524
+ left: at.left.x - area.min.x - width - tipSize,
525
+ top: at.top.y - area.min.y - height - tipSize,
526
+ bottom: area.max.y - at.bottom.y - height - tipSize
521
527
  };
522
528
 
523
529
  if (!this._autoDirection) {
@@ -529,6 +535,7 @@ export class Tooltip extends DivOverlay {
529
535
  }
530
536
 
531
537
  const direction = this._autoDirection,
538
+ {x, y} = at[direction],
532
539
  shift = direction === 'top' || direction === 'bottom' ?
533
540
  new Point(shiftInto(x - width / 2, width, area.min.x, area.max.x), 0) :
534
541
  new Point(0, shiftInto(y - height / 2, height, area.min.y, area.max.y));
@@ -555,7 +562,7 @@ export class Tooltip extends DivOverlay {
555
562
  }
556
563
 
557
564
  _updatePosition() {
558
- const pos = this._map.latLngToLayerPoint(this._latlng)._round();
565
+ const pos = this._map._snapLayerPoint(this._map.latLngToLayerPoint(this._latlng));
559
566
  this._setPosition(pos);
560
567
  }
561
568
 
@@ -577,9 +584,9 @@ export class Tooltip extends DivOverlay {
577
584
  this._setPosition(pos);
578
585
  }
579
586
 
580
- _getAnchor() {
581
- // Where should we anchor the tooltip on the source layer?
582
- return new Point(this._source?._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
587
+ // Where the tooltip opening in the given direction attaches on the source layer
588
+ _getAnchor(direction) {
589
+ return new Point(this._source?._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor(direction) : [0, 0]);
583
590
  }
584
591
 
585
592
  /**