map.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. define(["map/clientlayer", "map/labelslayer",
  2. "d3", "leaflet", "moment", "locationmarker", "rbush",
  3. "leaflet.label", "leaflet.providers"],
  4. function (ClientLayer, LabelsLayer, d3, L, moment, LocationMarker, rbush) {
  5. var options = { worldCopyJump: true,
  6. zoomControl: false
  7. }
  8. var AddLayerButton = L.Control.extend({
  9. options: {
  10. position: "bottomright"
  11. },
  12. initialize: function (f, options) {
  13. L.Util.setOptions(this, options)
  14. this.f = f
  15. },
  16. onAdd: function () {
  17. var button = L.DomUtil.create("button", "add-layer")
  18. button.textContent = ""
  19. L.DomEvent.disableClickPropagation(button)
  20. L.DomEvent.addListener(button, "click", this.f, this)
  21. this.button = button
  22. return button
  23. }
  24. })
  25. var LocateButton = L.Control.extend({
  26. options: {
  27. position: "bottomright"
  28. },
  29. active: false,
  30. button: undefined,
  31. initialize: function (f, options) {
  32. L.Util.setOptions(this, options)
  33. this.f = f
  34. },
  35. onAdd: function () {
  36. var button = L.DomUtil.create("button", "locate-user")
  37. button.textContent = ""
  38. L.DomEvent.disableClickPropagation(button)
  39. L.DomEvent.addListener(button, "click", this.onClick, this)
  40. this.button = button
  41. return button
  42. },
  43. update: function() {
  44. this.button.classList.toggle("active", this.active)
  45. },
  46. set: function(v) {
  47. this.active = v
  48. this.update()
  49. },
  50. onClick: function () {
  51. this.f(!this.active)
  52. }
  53. })
  54. function mkMarker(dict, iconFunc, router) {
  55. return function (d) {
  56. var m = L.circleMarker([d.nodeinfo.location.latitude, d.nodeinfo.location.longitude], iconFunc(d))
  57. m.resetStyle = function () {
  58. m.setStyle(iconFunc(d))
  59. }
  60. m.on("click", router.node(d))
  61. m.bindLabel(d.nodeinfo.hostname)
  62. dict[d.nodeinfo.node_id] = m
  63. return m
  64. }
  65. }
  66. function addLinksToMap(dict, linkScale, graph, router) {
  67. graph = graph.filter( function (d) {
  68. return "distance" in d && !d.vpn
  69. })
  70. var lines = graph.map( function (d) {
  71. var opts = { color: linkScale(d.tq).hex(),
  72. weight: 4,
  73. opacity: 0.5,
  74. dashArray: "none"
  75. }
  76. var line = L.polyline(d.latlngs, opts)
  77. line.resetStyle = function () {
  78. line.setStyle(opts)
  79. }
  80. line.bindLabel(d.source.node.nodeinfo.hostname + " – " + d.target.node.nodeinfo.hostname + "<br><strong>" + showDistance(d) + " / " + showTq(d) + "</strong>")
  81. line.on("click", router.link(d))
  82. dict[d.id] = line
  83. return line
  84. })
  85. return lines
  86. }
  87. var iconOnline = { color: "#1566A9", fillColor: "#1566A9", radius: 6, fillOpacity: 0.5, opacity: 0.5, weight: 2, className: "stroke-first" }
  88. var iconOffline = { color: "#D43E2A", fillColor: "#D43E2A", radius: 3, fillOpacity: 0.5, opacity: 0.5, weight: 1, className: "stroke-first" }
  89. var iconLost = { color: "#D43E2A", fillColor: "#D43E2A", radius: 6, fillOpacity: 0.8, opacity: 0.8, weight: 1, className: "stroke-first" }
  90. var iconAlert = { color: "#D43E2A", fillColor: "#D43E2A", radius: 6, fillOpacity: 0.8, opacity: 0.8, weight: 2, className: "stroke-first node-alert" }
  91. var iconNew = { color: "#1566A9", fillColor: "#93E929", radius: 6, fillOpacity: 1.0, opacity: 0.5, weight: 2 }
  92. return function (config, linkScale, sidebar, router, buttons) {
  93. var self = this
  94. var barycenter
  95. var groupOnline, groupOffline, groupNew, groupLost, groupLines
  96. var savedView
  97. var map, userLocation
  98. var layerControl
  99. var customLayers = new Set()
  100. var locateUserButton = new LocateButton(function (d) {
  101. if (d)
  102. enableTracking()
  103. else
  104. disableTracking()
  105. })
  106. var mybuttons = []
  107. function addButton(button) {
  108. var el = button.onAdd()
  109. mybuttons.push(el)
  110. buttons.appendChild(el)
  111. }
  112. function clearButtons() {
  113. mybuttons.forEach( function (d) {
  114. buttons.removeChild(d)
  115. })
  116. }
  117. function saveView() {
  118. savedView = {center: map.getCenter(),
  119. zoom: map.getZoom()}
  120. }
  121. function enableTracking() {
  122. map.locate({watch: true,
  123. enableHighAccuracy: true,
  124. setView: true
  125. })
  126. locateUserButton.set(true)
  127. }
  128. function disableTracking() {
  129. map.stopLocate()
  130. locationError()
  131. locateUserButton.set(false)
  132. }
  133. function locationFound(e) {
  134. if (!userLocation)
  135. userLocation = new LocationMarker(e.latlng).addTo(map)
  136. userLocation.setLatLng(e.latlng)
  137. userLocation.setAccuracy(e.accuracy)
  138. }
  139. function locationError() {
  140. if (userLocation) {
  141. map.removeLayer(userLocation)
  142. userLocation = null
  143. }
  144. }
  145. function addLayer(layerName) {
  146. if (customLayers.has(layerName))
  147. return
  148. try {
  149. var layer = L.tileLayer.provider(layerName)
  150. layerControl.addBaseLayer(layer, layerName)
  151. customLayers.add(layerName)
  152. if (!layerControl.added) {
  153. layerControl.addTo(map)
  154. layerControl.added = true
  155. }
  156. if (localStorageTest())
  157. localStorage.setItem("map/customLayers", JSON.stringify(Array.from(customLayers)))
  158. } catch (e) {
  159. return
  160. }
  161. }
  162. var el = document.createElement("div")
  163. el.classList.add("map")
  164. self.div = el
  165. map = L.map(el, options)
  166. var baseLayer = L.tileLayer("https://otile{s}-s.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.jpg", {
  167. subdomains: "1234",
  168. type: "osm",
  169. attribution: "Tiles &copy; <a href=\"https://www.mapquest.com/\" target=\"_blank\">MapQuest</a>, Data CC-BY-SA OpenStreetMap",
  170. maxZoom: 18
  171. }).addTo(map)
  172. map.on("locationfound", locationFound)
  173. map.on("locationerror", locationError)
  174. map.on("dragend", saveView)
  175. addButton(locateUserButton)
  176. addButton(new AddLayerButton(function () {
  177. /*eslint no-alert:0*/
  178. var layerName = prompt("Leaflet Provider:")
  179. addLayer(layerName)
  180. }))
  181. layerControl = L.control.layers({"MapQuest": baseLayer}, [], {position: "bottomright"})
  182. if (localStorageTest()) {
  183. var layers = JSON.parse(localStorage.getItem("map/customLayers"))
  184. if (layers)
  185. layers.forEach(addLayer)
  186. }
  187. var clientLayer = new ClientLayer({minZoom: 15})
  188. clientLayer.addTo(map)
  189. clientLayer.setZIndex(5)
  190. var labelsLayer = new LabelsLayer()
  191. labelsLayer.addTo(map)
  192. labelsLayer.setZIndex(6)
  193. var nodeDict = {}
  194. var linkDict = {}
  195. var highlight
  196. function resetMarkerStyles(nodes, links) {
  197. Object.keys(nodes).forEach( function (d) {
  198. nodes[d].resetStyle()
  199. })
  200. Object.keys(links).forEach( function (d) {
  201. links[d].resetStyle()
  202. })
  203. }
  204. function setView(bounds) {
  205. map.fitBounds(bounds, {paddingTopLeft: [sidebar.getWidth(), 0]})
  206. }
  207. function resetZoom() {
  208. setView(barycenter.getBounds())
  209. }
  210. function goto(m) {
  211. var bounds
  212. if ("getBounds" in m)
  213. bounds = m.getBounds()
  214. else
  215. bounds = L.latLngBounds([m.getLatLng()])
  216. setView(bounds)
  217. return m
  218. }
  219. function updateView(nopanzoom) {
  220. resetMarkerStyles(nodeDict, linkDict)
  221. var m
  222. if (highlight !== undefined)
  223. if (highlight.type === "node") {
  224. m = nodeDict[highlight.o.nodeinfo.node_id]
  225. if (m)
  226. m.setStyle({ color: "orange", weight: 20, fillOpacity: 1, opacity: 0.7, className: "stroke-first" })
  227. } else if (highlight.type === "link") {
  228. m = linkDict[highlight.o.id]
  229. if (m)
  230. m.setStyle({ weight: 7, opacity: 1, dashArray: "10, 10" })
  231. }
  232. if (!nopanzoom)
  233. if (m)
  234. goto(m)
  235. else if (savedView)
  236. map.setView(savedView.center, savedView.zoom)
  237. else
  238. resetZoom()
  239. }
  240. function calcBarycenter(nodes) {
  241. nodes = nodes.map(function (d) { return d.nodeinfo.location })
  242. var lats = nodes.map(function (d) { return d.latitude })
  243. var lngs = nodes.map(function (d) { return d.longitude })
  244. var barycenter = L.latLng(d3.median(lats), d3.median(lngs))
  245. var barycenterDev = [d3.deviation(lats), d3.deviation(lngs)]
  246. var barycenterCircle = L.latLng(barycenter.lat + barycenterDev[0],
  247. barycenter.lng + barycenterDev[1])
  248. var r = barycenter.distanceTo(barycenterCircle)
  249. return L.circle(barycenter, r * config.mapSigmaScale)
  250. }
  251. function mapRTree(d) {
  252. var o = [ d.nodeinfo.location.latitude, d.nodeinfo.location.longitude,
  253. d.nodeinfo.location.latitude, d.nodeinfo.location.longitude]
  254. o.node = d
  255. return o
  256. }
  257. self.setData = function (data) {
  258. nodeDict = {}
  259. linkDict = {}
  260. if (groupOffline)
  261. groupOffline.clearLayers()
  262. if (groupOnline)
  263. groupOnline.clearLayers()
  264. if (groupNew)
  265. groupNew.clearLayers()
  266. if (groupLost)
  267. groupLost.clearLayers()
  268. if (groupLines)
  269. groupLines.clearLayers()
  270. var lines = addLinksToMap(linkDict, linkScale, data.graph.links, router)
  271. groupLines = L.featureGroup(lines).addTo(map)
  272. barycenter = calcBarycenter(data.nodes.all.filter(has_location))
  273. var nodesOnline = subtract(data.nodes.all.filter(online), data.nodes.new)
  274. var nodesOffline = subtract(data.nodes.all.filter(offline), data.nodes.lost)
  275. var markersOnline = nodesOnline.filter(has_location)
  276. .map(mkMarker(nodeDict, function () { return iconOnline }, router))
  277. var markersOffline = nodesOffline.filter(has_location)
  278. .map(mkMarker(nodeDict, function () { return iconOffline }, router))
  279. var markersNew = data.nodes.new.filter(has_location)
  280. .map(mkMarker(nodeDict, function () { return iconNew }, router))
  281. var markersLost = data.nodes.lost.filter(has_location)
  282. .map(mkMarker(nodeDict, function (d) {
  283. if (d.lastseen.isAfter(moment(data.now).subtract(3, "days")))
  284. return iconAlert
  285. return iconLost
  286. }, router))
  287. groupOffline = L.featureGroup(markersOffline).addTo(map)
  288. groupOnline = L.featureGroup(markersOnline).addTo(map)
  289. groupLost = L.featureGroup(markersLost).addTo(map)
  290. groupNew = L.featureGroup(markersNew).addTo(map)
  291. var rtreeOnlineAll = rbush(9)
  292. rtreeOnlineAll.load(data.nodes.all.filter(online).filter(has_location).map(mapRTree))
  293. clientLayer.setData(rtreeOnlineAll)
  294. labelsLayer.setData({online: nodesOnline.filter(has_location),
  295. offline: nodesOffline.filter(has_location),
  296. new: data.nodes.new.filter(has_location),
  297. lost: data.nodes.lost.filter(has_location)
  298. })
  299. updateView(true)
  300. }
  301. self.resetView = function () {
  302. disableTracking()
  303. highlight = undefined
  304. updateView()
  305. }
  306. self.gotoNode = function (d) {
  307. disableTracking()
  308. highlight = {type: "node", o: d}
  309. updateView()
  310. }
  311. self.gotoLink = function (d) {
  312. disableTracking()
  313. highlight = {type: "link", o: d}
  314. updateView()
  315. }
  316. self.destroy = function () {
  317. clearButtons()
  318. map.remove()
  319. }
  320. return self
  321. }
  322. })