map-init.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. // Useful functions for our asset-specific Leaflet code
  2. function addTileLayer(leafletMap, mapboxAccessToken) {
  3. /*
  4. Add the tile layer for FlexMeasures.
  5. Configure tile size, Mapbox API access and attribution.
  6. */
  7. var tileLayer = new L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
  8. attribution: '© <a href="https://www.mapbox.com/about/maps/">Mapbox</a> © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> <strong><a href="https://www.mapbox.com/map-feedback/" target="_blank">Improve this map</a></strong>',
  9. tileSize: 512,
  10. maxZoom: 18,
  11. zoomOffset: -1,
  12. id: 'mapbox/streets-v11',
  13. accessToken: mapboxAccessToken
  14. });
  15. tileLayer.addTo(leafletMap);
  16. // add link for Mapbox logo (logo added via CSS)
  17. $("#" + leafletMap._container.id).append(
  18. '<a href="https://mapbox.com/about/maps" class="mapbox-logo" target="_blank">Mapbox</a>'
  19. );
  20. }
  21. function clickPan(e, data) {
  22. // set view such that the target asset lies slightly below the center of the map
  23. targetLatLng = e.target.getLatLng()
  24. targetZoom = assetMap.getZoom()
  25. targetPoint = assetMap.project(targetLatLng, targetZoom).subtract([0, 50]),
  26. targetLatLng = assetMap.unproject(targetPoint, targetZoom);
  27. assetMap.setView(targetLatLng, targetZoom);
  28. }
  29. /**
  30. * Injects a custom spiderfy layout function into the marker cluster, passing both
  31. * child markers and the cluster center point to the layout function.
  32. *
  33. * @param {L.MarkerCluster} markerCluster - The marker cluster instance to modify.
  34. */
  35. function passMarkersToSpiderfyShapePositions (markerCluster) {
  36. const childMarkers = markerCluster.getAllChildMarkers();
  37. const centerPt = markerCluster._group._map.latLngToLayerPoint(markerCluster._latlng);
  38. const shapeFn = markerCluster._group?.options?.spiderfyShapePositionsWithMarkers;
  39. if (typeof shapeFn === 'function') {
  40. markerCluster._group.options.spiderfyShapePositions = () =>
  41. shapeFn(childMarkers, centerPt);
  42. }
  43. }
  44. /**
  45. * Removes all spider legs (connecting lines) from the map for the given marker cluster.
  46. *
  47. * @param {L.MarkerCluster} markerCluster - The marker cluster from which to remove spider legs.
  48. */
  49. function removeSpiderLegs(markerCluster) {
  50. const map = markerCluster._group._map;
  51. for (const marker of markerCluster.getAllChildMarkers()) {
  52. if (marker._spiderLeg) {
  53. map.removeLayer(marker._spiderLeg);
  54. }
  55. }
  56. }
  57. /**
  58. * Computes a tree-based layout for markers, organizing them into a forest centered
  59. * around a given point. Markers must have `id` and `parentId` options.
  60. *
  61. * @param {Array<L.Marker>} markers - Array of markers with hierarchical relationships.
  62. * @param {L.Point} centerPt - The center point to base the layout around.
  63. * @param {number} [spacingX=50] - Horizontal spacing between sibling nodes.
  64. * @param {number} [spacingY=100] - Vertical spacing between levels.
  65. * @param {number} [treeSpacing=100] - Spacing between root trees.
  66. * @returns {Array<L.Point>} Array of new positions (as layer points) for the markers.
  67. */
  68. function computeCenteredTreeLayout(markers, centerPt, spacingX = 50, spacingY = 100, treeSpacing = 100) {
  69. const nodeMap = new Map();
  70. // Add virtual parent nodes if they are missing a marker (no lat/lng)
  71. const allParentIds = new Set(markers.map(m => m.options.parentId).filter(id => id !== null));
  72. for (const parentId of allParentIds) {
  73. if (!nodeMap.has(parentId)) {
  74. // Use the first child with this parent to determine location
  75. const child = markers.find(m => m.options.parentId === parentId);
  76. if (child) {
  77. nodeMap.set(parentId, {
  78. id: parentId,
  79. parentId: null,
  80. children: [],
  81. x: 0,
  82. y: 0,
  83. virtual: true // you can tag it if needed
  84. });
  85. }
  86. }
  87. }
  88. markers.forEach(marker => {
  89. const { id, parentId } = marker.options;
  90. nodeMap.set(id, { ...marker.options, children: [], x: 0, y: 0 });
  91. });
  92. let roots = [];
  93. nodeMap.forEach(node => {
  94. if (node.parentId === null) {
  95. roots.push(node);
  96. } else {
  97. const parent = nodeMap.get(node.parentId);
  98. if (parent) {
  99. parent.children.push(node);
  100. }
  101. }
  102. });
  103. const positionMap = new Map(); // id -> { dx, dy, level }
  104. let currentX = 0;
  105. function layoutTree(node, depth) {
  106. if (node.children.length === 0) {
  107. node.x = currentX;
  108. currentX += spacingX;
  109. } else {
  110. for (const child of node.children) {
  111. layoutTree(child, depth + 1);
  112. }
  113. const xs = node.children.map(child => child.x);
  114. node.x = (Math.min(...xs) + Math.max(...xs)) / 2;
  115. }
  116. node.y = depth * spacingY;
  117. positionMap.set(node.id, { dx: node.x, dy: node.y, level: depth });
  118. }
  119. let globalXOffset = 0;
  120. for (const root of roots) {
  121. const startX = currentX;
  122. layoutTree(root, 0);
  123. // Adjust all dx in this tree by (startX - minX)
  124. const treeNodes = [...nodeMap.values()].filter(n => positionMap.has(n.id));
  125. const minX = Math.min(...treeNodes.map(n => positionMap.get(n.id).dx));
  126. const offset = startX - minX;
  127. for (const n of treeNodes) {
  128. const pos = positionMap.get(n.id);
  129. pos.dx += offset;
  130. }
  131. // Update currentX for next tree
  132. const maxX = Math.max(...treeNodes.map(n => positionMap.get(n.id).dx));
  133. currentX = maxX + treeSpacing;
  134. }
  135. // === Center the forest around (0, 0) ===
  136. const allPositions = Array.from(positionMap.values());
  137. const minDx = Math.min(...allPositions.map(p => p.dx));
  138. const maxDx = Math.max(...allPositions.map(p => p.dx));
  139. const centerX = (minDx + maxDx) / 2;
  140. const maxLevel = Math.max(...allPositions.map(p => p.level));
  141. const centerLevel = maxLevel / 2;
  142. const centerY = centerLevel * spacingY;
  143. for (const pos of allPositions) {
  144. pos.dx -= centerX;
  145. pos.dy -= centerY;
  146. }
  147. // Final result in original order
  148. return markers.map(marker => {
  149. const { dx, dy } = positionMap.get(marker.options.id);
  150. // console.log(marker.options.id, ": ", dx, ", ", dy);
  151. return L.point(
  152. {
  153. x: centerPt.x + dx,
  154. y: centerPt.y + dy
  155. }
  156. );
  157. });
  158. }
  159. /**
  160. * Performs a tree-style animated spiderfy for a cluster, using parent-child relationships
  161. * between markers to create animated spider legs from parent to child.
  162. *
  163. * @param {Array<L.Marker>} childMarkers - The markers to be spiderfied.
  164. * @param {Array<L.Point>} positions - The target layer point positions for the markers.
  165. */
  166. function _animationTreeSpiderfy(childMarkers, positions) {
  167. var me = this,
  168. group = this._group,
  169. map = group._map,
  170. fg = group._featureGroup,
  171. thisLayerLatLng = this._latlng,
  172. thisLayerPos = map.latLngToLayerPoint(thisLayerLatLng),
  173. svg = L.Path.SVG,
  174. legOptions = L.extend({}, this._group.options.spiderLegPolylineOptions), // Copy the options so that we can modify them for animation.
  175. finalLegOpacity = legOptions.opacity,
  176. i, m, leg, legPath, legLength, newPos;
  177. if (finalLegOpacity === undefined) {
  178. finalLegOpacity = L.MarkerClusterGroup.prototype.options.spiderLegPolylineOptions.opacity;
  179. }
  180. if (svg) {
  181. // If the initial opacity of the spider leg is not 0 then it appears before the animation starts.
  182. legOptions.opacity = 0;
  183. // Add the class for CSS transitions.
  184. legOptions.className = (legOptions.className || '') + ' leaflet-cluster-spider-leg';
  185. } else {
  186. // Make sure we have a defined opacity.
  187. // legOptions.opacity = finalLegOpacity;
  188. legOptions.opacity = 0; // Seita monkeypatch
  189. }
  190. group._ignoreMove = true;
  191. // Seita monkeypatch
  192. // Build a quick lookup map by marker id
  193. const markerMap = new Map(childMarkers.map(m => [m.options.id, m]));
  194. // Add markers and spider legs to map, hidden at our center point.
  195. // Traverse in ascending order to make sure that inner circleMarkers are on top of further legs. Normal markers are re-ordered by newPosition.
  196. // The reverse order trick no longer improves performance on modern browsers.
  197. for (i = 0; i < childMarkers.length; i++) {
  198. m = childMarkers[i];
  199. childPos = positions[i]
  200. // Seita monkeypatch
  201. const parentId = m.options.parentId;
  202. var hasParentPos = true;
  203. if (parentId == null) {
  204. hasParentPos = false;
  205. };
  206. const parentMarker = markerMap.get(parentId);
  207. if (!parentMarker) {
  208. hasParentPos = false;
  209. };
  210. const parentPos = positions[childMarkers.indexOf(parentMarker)];
  211. if (!parentPos) {
  212. hasParentPos = false;
  213. };
  214. newPos = map.layerPointToLatLng(positions[i]);
  215. if (hasParentPos == true) {
  216. oldPos = map.layerPointToLatLng(parentPos);
  217. } else {
  218. oldPos = newPos;
  219. }
  220. // Add the leg before the marker, so that in case the latter is a circleMarker, the leg is behind it.
  221. leg = new L.Polyline([oldPos, newPos], legOptions);
  222. // leg = new L.Polyline([thisLayerLatLng, newPos], legOptions);
  223. map.addLayer(leg);
  224. m._spiderLeg = leg;
  225. // Explanations: https://jakearchibald.com/2013/animated-line-drawing-svg/
  226. // In our case the transition property is declared in the CSS file.
  227. if (svg) {
  228. legPath = leg._path;
  229. legLength = legPath.getTotalLength() + 0.1; // Need a small extra length to avoid remaining dot in Firefox.
  230. legPath.style.strokeDasharray = legLength; // Just 1 length is enough, it will be duplicated.
  231. legPath.style.strokeDashoffset = legLength;
  232. }
  233. }
  234. for (i = 0; i < childMarkers.length; i++) {
  235. m = childMarkers[i];
  236. // If it is a marker, add it now and we'll animate it out
  237. if (m.setZIndexOffset) {
  238. m.setZIndexOffset(1000000); // Make normal markers appear on top of EVERYTHING
  239. }
  240. if (m.clusterHide) {
  241. m.clusterHide();
  242. }
  243. // Vectors just get immediately added
  244. fg.addLayer(m);
  245. if (m._setPos) {
  246. m._setPos(thisLayerPos);
  247. }
  248. }
  249. group._forceLayout();
  250. group._animationStart();
  251. // Reveal markers and spider legs.
  252. for (i = childMarkers.length - 1; i >= 0; i--) {
  253. newPos = map.layerPointToLatLng(positions[i]);
  254. m = childMarkers[i];
  255. //Move marker to new position
  256. m._preSpiderfyLatlng = m._latlng;
  257. m.setLatLng(newPos);
  258. if (m.clusterShow) {
  259. m.clusterShow();
  260. }
  261. // Animate leg (animation is actually delegated to CSS transition).
  262. if (svg) {
  263. leg = m._spiderLeg;
  264. legPath = leg._path;
  265. legPath.style.strokeDashoffset = 0;
  266. //legPath.style.strokeOpacity = finalLegOpacity;
  267. leg.setStyle({opacity: finalLegOpacity});
  268. }
  269. }
  270. this.setOpacity(0.3);
  271. group._ignoreMove = false;
  272. setTimeout(function () {
  273. group._animationEnd();
  274. group.fire('spiderfied', {
  275. cluster: me,
  276. markers: childMarkers
  277. });
  278. // Seita monkeypatch
  279. for (i = childMarkers.length - 1; i >= 0; i--) {
  280. m = childMarkers[i];
  281. leg = m._spiderLeg;
  282. leg.setStyle({opacity: finalLegOpacity});
  283. }
  284. }, 200);
  285. }