bigemap-velocity2.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. "use strict";
  2. /*
  3. Generic Canvas Layer for bigemap 0.7 and 1.0-rc,
  4. copyright Stanislav Sumbera, 2016 , sumbera.com , license MIT
  5. originally created and motivated by BM.CanvasOverlay available here: https://gist.github.com/Sumbera/11114288
  6. */
  7. // -- BM.DomUtil.setTransform from bigemap 1.0.0 to work on 0.0.7
  8. //------------------------------------------------------------------------------
  9. if (!BM.DomUtil.setTransform) {
  10. BM.DomUtil.setTransform = function (el, offset, scale) {
  11. var pos = offset || new BM.Point(0, 0);
  12. el.style[BM.DomUtil.TRANSFORM] = (BM.Browser.ie3d ? "translate(" + pos.x + "px," + pos.y + "px)" : "translate3d(" + pos.x + "px," + pos.y + "px,0)") + (scale ? " scale(" + scale + ")" : "");
  13. };
  14. }
  15. // -- support for both 0.0.7 and 1.0.0 rc2 bigemap
  16. BM.CanvasLayer = (BM.Layer ? BM.Layer : BM.Class).extend({
  17. // -- initialized is called on prototype
  18. initialize: function initialize(options) {
  19. this._map = null;
  20. this._canvas = null;
  21. this._frame = null;
  22. this._delegate = null;
  23. BM.setOptions(this, options);
  24. },
  25. delegate: function delegate(del) {
  26. this._delegate = del;
  27. return this;
  28. },
  29. needRedraw: function needRedraw() {
  30. if (!this._frame) {
  31. this._frame = BM.Util.requestAnimFrame(this.drawLayer, this);
  32. }
  33. return this;
  34. },
  35. //-------------------------------------------------------------
  36. _onLayerDidResize: function _onLayerDidResize(resizeEvent) {
  37. this._canvas.width = resizeEvent.newSize.x;
  38. this._canvas.height = resizeEvent.newSize.y;
  39. },
  40. //-------------------------------------------------------------
  41. _onLayerDidMove: function _onLayerDidMove() {
  42. var topLeft = this._map.containerPointToLayerPoint([0, 0]);
  43. BM.DomUtil.setPosition(this._canvas, topLeft);
  44. this.drawLayer();
  45. },
  46. //-------------------------------------------------------------
  47. getEvents: function getEvents() {
  48. var events = {
  49. resize: this._onLayerDidResize,
  50. moveend: this._onLayerDidMove
  51. };
  52. if (this._map.options.zoomAnimation && BM.Browser.any3d) {
  53. events.zoomanim = this._animateZoom;
  54. }
  55. return events;
  56. },
  57. //-------------------------------------------------------------
  58. onAdd: function onAdd(map) {
  59. this._map = map;
  60. this._canvas = BM.DomUtil.create("canvas", "bigemap-layer");
  61. this.tiles = {};
  62. var size = this._map.getSize();
  63. this._canvas.width = size.x;
  64. this._canvas.height = size.y;
  65. var animated = this._map.options.zoomAnimation && BM.Browser.any3d;
  66. BM.DomUtil.addClass(this._canvas, "bigemap-zoom-" + (animated ? "animated" : "hide"));
  67. this.options.pane.appendChild(this._canvas);
  68. map.on(this.getEvents(), this);
  69. var del = this._delegate || this;
  70. del.onLayerDidMount && del.onLayerDidMount(); // -- callback
  71. this.needRedraw();
  72. var self = this;
  73. setTimeout(function () {
  74. self._onLayerDidMove();
  75. }, 0);
  76. },
  77. //-------------------------------------------------------------
  78. onRemove: function onRemove(map) {
  79. var del = this._delegate || this;
  80. del.onLayerWillUnmount && del.onLayerWillUnmount(); // -- callback
  81. this.options.pane.removeChild(this._canvas);
  82. map.off(this.getEvents(), this);
  83. this._canvas = null;
  84. },
  85. //------------------------------------------------------------
  86. addTo: function addTo(map) {
  87. map.addLayer(this);
  88. return this;
  89. },
  90. //------------------------------------------------------------------------------
  91. drawLayer: function drawLayer() {
  92. // -- todo make the viewInfo properties flat objects.
  93. var size = this._map.getSize();
  94. var bounds = this._map.getBounds();
  95. var zoom = this._map.getZoom();
  96. var center = this._map.options.crs.project(this._map.getCenter());
  97. var corner = this._map.options.crs.project(this._map.containerPointToLatLng(this._map.getSize()));
  98. var del = this._delegate || this;
  99. del.onDrawLayer && del.onDrawLayer({
  100. layer: this,
  101. canvas: this._canvas,
  102. bounds: bounds,
  103. size: size,
  104. zoom: zoom,
  105. center: center,
  106. corner: corner
  107. });
  108. this._frame = null;
  109. },
  110. // -- BM.DomUtil.setTransform from bigemap 1.0.0 to work on 0.0.7
  111. //------------------------------------------------------------------------------
  112. _setTransform: function _setTransform(el, offset, scale) {
  113. var pos = offset || new BM.Point(0, 0);
  114. el.style[BM.DomUtil.TRANSFORM] = (BM.Browser.ie3d ? "translate(" + pos.x + "px," + pos.y + "px)" : "translate3d(" + pos.x + "px," + pos.y + "px,0)") + (scale ? " scale(" + scale + ")" : "");
  115. },
  116. //------------------------------------------------------------------------------
  117. _animateZoom: function _animateZoom(e) {
  118. var scale = this._map.getZoomScale(e.zoom);
  119. // -- different calc of offset in bigemap 1.0.0 and 0.0.7 thanks for 1.0.0-rc2 calc @jduggan1
  120. var offset = BM.Layer ? this._map._latLngToNewLayerPoint(this._map.getBounds().getNorthWest(), e.zoom, e.center) : this._map._getCenterOffset(e.center)._multiplyBy(-scale).subtract(this._map._getMapPanePos());
  121. BM.DomUtil.setTransform(this._canvas, offset, scale);
  122. }
  123. });
  124. BM.canvasLayer = function (pane) {
  125. return new BM.CanvasLayer(pane);
  126. };
  127. BM.Control.Velocity = BM.Control.extend({
  128. options: {
  129. position: "topleft",
  130. emptyString: "Unavailable",
  131. // Could be any combination of 'bearing' (angle toward which the flow goes) or 'meteo' (angle from which the flow comes)
  132. // and 'CW' (angle value increases clock-wise) or 'CCW' (angle value increases counter clock-wise)
  133. angleConvention: "bearingCCW",
  134. showCardinal: false,
  135. // Could be 'm/s' for meter per second, 'k/h' for kilometer per hour, 'mph' for miles per hour or 'kt' for knots
  136. speedUnit: "m/s",
  137. directionString: "风向",
  138. speedString: "速度",
  139. onAdd: null,
  140. onRemove: null,
  141. handMove: true,
  142. handClick: true
  143. },
  144. onAdd: function onAdd(map) {
  145. this._container = BM.DomUtil.create("div", "bigemap-control-velocity");
  146. BM.DomEvent.disableClickPropagation(this._container);
  147. if (this.options.handMove) map.on("mousemove", this._onMouseMove, this);
  148. if (this.options.handClick) map.on('click', this._onClick, this);
  149. this._container.innerHTML = this.options.emptyString;
  150. if (this.options.bigemapVelocity.options.onAdd) this.options.bigemapVelocity.options.onAdd();
  151. return this._container;
  152. },
  153. onRemove: function onRemove(map) {
  154. map.off("mousemove", this._onMouseMove, this);
  155. map.off('click', this._onClick, this);
  156. if (this.options.bigemapVelocity.options.onRemove) this.options.bigemapVelocity.options.onRemove();
  157. },
  158. vectorToSpeed: function vectorToSpeed(uMs, vMs, unit) {
  159. var velocityAbs = Math.sqrt(Math.pow(uMs, 2) + Math.pow(vMs, 2));
  160. // Default is m/s
  161. if (unit === "k/h") {
  162. return this.meterSec2kilometerHour(velocityAbs);
  163. } else if (unit === "kt") {
  164. return this.meterSec2Knots(velocityAbs);
  165. } else if (unit === "mph") {
  166. return this.meterSec2milesHour(velocityAbs);
  167. } else {
  168. return velocityAbs;
  169. }
  170. },
  171. vectorToDegrees: function vectorToDegrees(uMs, vMs, angleConvention) {
  172. // Default angle convention is CW
  173. if (angleConvention.endsWith("CCW")) {
  174. // vMs comes out upside-down..
  175. vMs = vMs > 0 ? vMs = -vMs : Math.abs(vMs);
  176. }
  177. var velocityAbs = Math.sqrt(Math.pow(uMs, 2) + Math.pow(vMs, 2));
  178. var velocityDir = Math.atan2(uMs / velocityAbs, vMs / velocityAbs);
  179. var velocityDirToDegrees = velocityDir * 180 / Math.PI + 180;
  180. if (angleConvention === "bearingCW" || angleConvention === "meteoCCW") {
  181. velocityDirToDegrees += 180;
  182. if (velocityDirToDegrees >= 360) velocityDirToDegrees -= 360;
  183. }
  184. return velocityDirToDegrees;
  185. },
  186. degreesToCardinalDirection: function degreesToCardinalDirection(deg) {
  187. var cardinalDirection = '';
  188. if (deg >= 0 && deg < 11.25 || deg >= 348.75) {
  189. cardinalDirection = 'N';
  190. } else if (deg >= 11.25 && deg < 33.75) {
  191. cardinalDirection = 'NNW';
  192. } else if (deg >= 33.75 && deg < 56.25) {
  193. cardinalDirection = 'NW';
  194. } else if (deg >= 56.25 && deg < 78.75) {
  195. cardinalDirection = 'WNW';
  196. } else if (deg >= 78.25 && deg < 101.25) {
  197. cardinalDirection = 'W';
  198. } else if (deg >= 101.25 && deg < 123.75) {
  199. cardinalDirection = 'WSW';
  200. } else if (deg >= 123.75 && deg < 146.25) {
  201. cardinalDirection = 'SW';
  202. } else if (deg >= 146.25 && deg < 168.75) {
  203. cardinalDirection = 'SSW';
  204. } else if (deg >= 168.75 && deg < 191.25) {
  205. cardinalDirection = 'S';
  206. } else if (deg >= 191.25 && deg < 213.75) {
  207. cardinalDirection = 'SSE';
  208. } else if (deg >= 213.75 && deg < 236.25) {
  209. cardinalDirection = 'SE';
  210. } else if (deg >= 236.25 && deg < 258.75) {
  211. cardinalDirection = 'ESE';
  212. } else if (deg >= 258.75 && deg < 281.25) {
  213. cardinalDirection = 'E';
  214. } else if (deg >= 281.25 && deg < 303.75) {
  215. cardinalDirection = 'ENE';
  216. } else if (deg >= 303.75 && deg < 326.25) {
  217. cardinalDirection = 'NE';
  218. } else if (deg >= 326.25 && deg < 348.75) {
  219. cardinalDirection = 'NNE';
  220. }
  221. return cardinalDirection;
  222. },
  223. meterSec2Knots: function meterSec2Knots(meters) {
  224. return meters / 0.514;
  225. },
  226. meterSec2kilometerHour: function meterSec2kilometerHour(meters) {
  227. return meters * 3.6;
  228. },
  229. meterSec2milesHour: function meterSec2milesHour(meters) {
  230. return meters * 2.23694;
  231. },
  232. _onMouseMove: function _onMouseMove(e) {
  233. var self = this;
  234. var pos = this.options.bigemapVelocity._map.containerPointToLatLng(BM.point(e.containerPoint.x, e.containerPoint.y));
  235. var gridValue = this.options.bigemapVelocity._windy.interpolatePoint(pos.lng, pos.lat);
  236. var htmlOut = "";
  237. if (gridValue && !isNaN(gridValue[0]) && !isNaN(gridValue[1]) && gridValue[2]) {
  238. var deg = self.vectorToDegrees(gridValue[0], gridValue[1], this.options.angleConvention);
  239. var cardinal = this.options.showCardinal ? " (".concat(self.degreesToCardinalDirection(deg), ") ") : '';
  240. htmlOut = "<strong> ".concat(this.options.velocityType, " ").concat(this.options.directionString, ": </strong> ").concat(deg.toFixed(2), "\xB0").concat(cardinal, ", <strong> ").concat(this.options.velocityType, " ").concat(this.options.speedString, ": </strong> ").concat(self.vectorToSpeed(gridValue[0], gridValue[1], this.options.speedUnit).toFixed(2), " ").concat(this.options.speedUnit);
  241. self._map.fire('VelocityLayerMove', {
  242. direct: "".concat(deg.toFixed(2), "\xB0").concat(cardinal),
  243. speed: "".concat(self.vectorToSpeed(gridValue[0], gridValue[1], this.options.speedUnit).toFixed(2), " ").concat(this.options.speedUnit),
  244. context: this,
  245. Event: e
  246. });
  247. } else {
  248. htmlOut = this.options.emptyString;
  249. }
  250. self._container.innerHTML = htmlOut;
  251. },
  252. _onClick: function _onClick(e) {
  253. var self = this;
  254. var pos = this.options.bigemapVelocity._map.containerPointToLatLng(BM.point(e.containerPoint.x, e.containerPoint.y));
  255. var gridValue = this.options.bigemapVelocity._windy.interpolatePoint(pos.lng, pos.lat);
  256. var htmlOut = "";
  257. if (gridValue && !isNaN(gridValue[0]) && !isNaN(gridValue[1]) && gridValue[2]) {
  258. var deg = self.vectorToDegrees(gridValue[0], gridValue[1], this.options.angleConvention);
  259. var cardinal = this.options.showCardinal ? " (".concat(self.degreesToCardinalDirection(deg), ") ") : '';
  260. htmlOut = "<strong> ".concat(this.options.velocityType, " ").concat(this.options.directionString, ": </strong> ").concat(deg.toFixed(2), "\xB0").concat(cardinal, ", <strong> ").concat(this.options.velocityType, " ").concat(this.options.speedString, ": </strong> ").concat(self.vectorToSpeed(gridValue[0], gridValue[1], this.options.speedUnit).toFixed(2), " ").concat(this.options.speedUnit);
  261. map.fire('VelocityLayerClick', {
  262. direct: "".concat(deg.toFixed(2), "\xB0").concat(cardinal),
  263. speed: "".concat(self.vectorToSpeed(gridValue[0], gridValue[1], this.options.speedUnit).toFixed(2), " ").concat(this.options.speedUnit),
  264. context: this,
  265. Event: e
  266. });
  267. } else {
  268. htmlOut = this.options.emptyString;
  269. }
  270. self._container.innerHTML = htmlOut;
  271. }
  272. });
  273. BM.Map.mergeOptions({
  274. positionControl: false
  275. });
  276. BM.Map.addInitHook(function () {
  277. if (this.options.positionControl) {
  278. this.positionControl = new BM.Control.MousePosition();
  279. this.addControl(this.positionControl);
  280. }
  281. });
  282. BM.control.velocity = function (options) {
  283. return new BM.Control.Velocity(options);
  284. };
  285. BM.VelocityLayer = (BM.Layer ? BM.Layer : BM.Class).extend({
  286. options: {
  287. displayValues: true,
  288. displayOptions: {
  289. velocityType: "",
  290. position: "topleft",
  291. emptyString: "No data"
  292. },
  293. maxVelocity: 10,
  294. // used to align color scale
  295. colorScale: null,
  296. data: null
  297. },
  298. _map: null,
  299. _canvasLayer: null,
  300. _windy: null,
  301. _context: null,
  302. _timer: 0,
  303. _mouseControl: null,
  304. initialize: function initialize(options) {
  305. BM.setOptions(this, options);
  306. },
  307. onAdd: function onAdd(map) {
  308. // determine where to add the layer
  309. this._paneName = this.options.paneName || "overlayPane";
  310. // fall back to overlayPane for bigemap < 1
  311. var pane = map._panes.overlayPane;
  312. if (map.getPane) {
  313. // attempt to get pane first to preserve parent (createPane voids this)
  314. pane = map.getPane(this._paneName);
  315. if (!pane) {
  316. pane = map.createPane(this._paneName);
  317. }
  318. }
  319. // create canvas, add to map pane
  320. this._canvasLayer = BM.canvasLayer({
  321. pane: pane
  322. }).delegate(this);
  323. this._canvasLayer.addTo(map);
  324. this._map = map;
  325. },
  326. onRemove: function onRemove(map) {
  327. this._destroyWind();
  328. },
  329. setData: function setData(data) {
  330. this.options.data = data;
  331. if (this._windy) {
  332. this._windy.setData(data);
  333. this._clearAndRestart();
  334. }
  335. this.fire("load");
  336. },
  337. setOpacity: function setOpacity(opacity) {
  338. this._canvasLayer.setOpacity(opacity);
  339. },
  340. setOptions: function setOptions(options) {
  341. this.options = Object.assign(this.options, options);
  342. if (options.hasOwnProperty("displayOptions")) {
  343. this.options.displayOptions = Object.assign(this.options.displayOptions, options.displayOptions);
  344. this._initMouseHandler(true);
  345. }
  346. if (options.hasOwnProperty("data")) this.options.data = options.data;
  347. if (this._windy) {
  348. this._windy.setOptions(options);
  349. if (options.hasOwnProperty("data")) this._windy.setData(options.data);
  350. this._clearAndRestart();
  351. }
  352. this.fire("load");
  353. },
  354. /*------------------------------------ PRIVATE ------------------------------------------*/
  355. onDrawLayer: function onDrawLayer(overlay, params) {
  356. var self = this;
  357. if (!this._windy) {
  358. this._initWindy(this);
  359. return;
  360. }
  361. if (!this.options.data) {
  362. return;
  363. }
  364. if (this._timer) clearTimeout(self._timer);
  365. this._timer = setTimeout(function () {
  366. self._startWindy();
  367. }, 750); // showing velocity is delayed
  368. },
  369. _startWindy: function _startWindy() {
  370. var bounds = this._map.getBounds();
  371. var size = this._map.getSize();
  372. // bounds, width, height, extent
  373. this._windy.start([[0, 0], [size.x, size.y]], size.x, size.y, [[bounds._southWest.lng, bounds._southWest.lat], [bounds._northEast.lng, bounds._northEast.lat]]);
  374. },
  375. _initWindy: function _initWindy(self) {
  376. // windy object, copy options
  377. var options = Object.assign({
  378. canvas: self._canvasLayer._canvas,
  379. map: this._map
  380. }, self.options);
  381. this._windy = new Windy(options);
  382. // prepare context global var, start drawing
  383. this._context = this._canvasLayer._canvas.getContext("2d");
  384. this._canvasLayer._canvas.classList.add("velocity-overlay");
  385. this.onDrawLayer();
  386. this._map.on("dragstart", self._windy.stop);
  387. this._map.on("dragend", self._clearAndRestart);
  388. this._map.on("zoomstart", self._windy.stop);
  389. this._map.on("zoomend", self._clearAndRestart);
  390. this._map.on("resize", self._clearWind);
  391. this._initMouseHandler(false);
  392. },
  393. _initMouseHandler: function _initMouseHandler(voidPrevious) {
  394. if (voidPrevious) {
  395. this._map.removeControl(this._mouseControl);
  396. this._mouseControl = false;
  397. }
  398. if (!this._mouseControl && this.options.displayValues) {
  399. var options = this.options.displayOptions || {};
  400. options["bigemapVelocity"] = this;
  401. this._mouseControl = BM.control.velocity(options).addTo(this._map);
  402. }
  403. },
  404. _clearAndRestart: function _clearAndRestart() {
  405. if (this._context) this._context.clearRect(0, 0, 3000, 3000);
  406. if (this._windy) this._startWindy();
  407. },
  408. _clearWind: function _clearWind() {
  409. if (this._windy) this._windy.stop();
  410. if (this._context) this._context.clearRect(0, 0, 3000, 3000);
  411. },
  412. _destroyWind: function _destroyWind() {
  413. if (this._timer) clearTimeout(this._timer);
  414. if (this._windy) this._windy.stop();
  415. if (this._context) this._context.clearRect(0, 0, 3000, 3000);
  416. if (this._mouseControl) this._map.removeControl(this._mouseControl);
  417. this._mouseControl = null;
  418. this._windy = null;
  419. this._map.removeLayer(this._canvasLayer);
  420. }
  421. });
  422. BM.velocityLayer = function (options) {
  423. return new BM.VelocityLayer(options);
  424. };
  425. /* Global class for simulating the movement of particle through a 1km wind grid
  426. credit: All the credit for this work goes to: https://github.com/cambecc for creating the repo:
  427. https://github.com/cambecc/earth. The majority of this code is directly take nfrom there, since its awesome.
  428. This class takes a canvas element and an array of data (1km GFS from http://www.emc.ncep.noaa.gov/index.php?branch=GFS)
  429. and then uses a mercator (forward/reverse) projection to correctly map wind vectors in "map space".
  430. The "start" method takes the bounds of the map at its current extent and starts the whole gridding,
  431. interpolation and animation process.
  432. */
  433. var Windy = function Windy(params) {
  434. var MIN_VELOCITY_INTENSITY = params.minVelocity || 0; // velocity at which particle intensity is minimum (m/s)
  435. var MAX_VELOCITY_INTENSITY = params.maxVelocity || 10; // velocity at which particle intensity is maximum (m/s)
  436. var VELOCITY_SCALE = (params.velocityScale || 0.005) * (Math.pow(window.devicePixelRatio, 1 / 3) || 1); // scale for wind velocity (completely arbitrary--this value looks nice)
  437. var MAX_PARTICLE_AGE = params.particleAge || 90; // max number of frames a particle is drawn before regeneration
  438. var PARTICLE_LINE_WIDTH = params.lineWidth || 1; // line width of a drawn particle
  439. var PARTICLE_MULTIPLIER = params.particleMultiplier || 1 / 300; // particle count scalar (completely arbitrary--this values looks nice)
  440. var PARTICLE_REDUCTION = Math.pow(window.devicePixelRatio, 1 / 3) || 1.6; // multiply particle count for mobiles by this amount
  441. var FRAME_RATE = params.frameRate || 15;
  442. var FRAME_TIME = 1000 / FRAME_RATE; // desired frames per second
  443. var OPACITY = 0.97;
  444. var defaulColorScale = ["rgb(36,104, 180)", "rgb(60,157, 194)", "rgb(128,205,193 )", "rgb(151,218,168 )", "rgb(198,231,181)", "rgb(238,247,217)", "rgb(255,238,159)", "rgb(252,217,125)", "rgb(255,182,100)", "rgb(252,150,75)", "rgb(250,112,52)", "rgb(245,64,32)", "rgb(237,45,28)", "rgb(220,24,32)", "rgb(180,0,35)"];
  445. var colorScale = params.colorScale || defaulColorScale;
  446. var NULL_WIND_VECTOR = [NaN, NaN, null]; // singleton for no wind in the form: [u, v, magnitude]
  447. var builder;
  448. var grid;
  449. var gridData = params.data;
  450. var date;
  451. var λ0, φ0, Δλ, Δφ, ni, nj;
  452. var setData = function setData(data) {
  453. gridData = data;
  454. };
  455. var setOptions = function setOptions(options) {
  456. if (options.hasOwnProperty("minVelocity")) MIN_VELOCITY_INTENSITY = options.minVelocity;
  457. if (options.hasOwnProperty("maxVelocity")) MAX_VELOCITY_INTENSITY = options.maxVelocity;
  458. if (options.hasOwnProperty("velocityScale")) VELOCITY_SCALE = (options.velocityScale || 0.005) * (Math.pow(window.devicePixelRatio, 1 / 3) || 1);
  459. if (options.hasOwnProperty("particleAge")) MAX_PARTICLE_AGE = options.particleAge;
  460. if (options.hasOwnProperty("lineWidth")) PARTICLE_LINE_WIDTH = options.lineWidth;
  461. if (options.hasOwnProperty("particleMultiplier")) PARTICLE_MULTIPLIER = options.particleMultiplier;
  462. if (options.hasOwnProperty("opacity")) OPACITY = +options.opacity;
  463. if (options.hasOwnProperty("frameRate")) FRAME_RATE = options.frameRate;
  464. FRAME_TIME = 1000 / FRAME_RATE;
  465. };
  466. // interpolation for vectors like wind (u,v,m)
  467. var bilinearInterpolateVector = function bilinearInterpolateVector(x, y, g00, g10, g01, g11) {
  468. var rx = 1 - x;
  469. var ry = 1 - y;
  470. var a = rx * ry,
  471. b = x * ry,
  472. c = rx * y,
  473. d = x * y;
  474. var u = g00[0] * a + g10[0] * b + g01[0] * c + g11[0] * d;
  475. var v = g00[1] * a + g10[1] * b + g01[1] * c + g11[1] * d;
  476. return [u, v, Math.sqrt(u * u + v * v)];
  477. };
  478. var createWindBuilder = function createWindBuilder(uComp, vComp) {
  479. var uData = uComp.data,
  480. vData = vComp.data;
  481. return {
  482. header: uComp.header,
  483. //recipe: recipeFor("wind-" + uComp.header.surface1Value),
  484. data: function data(i) {
  485. return [uData[i], vData[i]];
  486. },
  487. interpolate: bilinearInterpolateVector
  488. };
  489. };
  490. var createBuilder = function createBuilder(data) {
  491. var uComp = null,
  492. vComp = null,
  493. scalar = null;
  494. data.forEach(function (record) {
  495. switch (record.header.parameterCategory + "," + record.header.parameterNumber) {
  496. case "1,2":
  497. case "2,2":
  498. uComp = record;
  499. break;
  500. case "1,3":
  501. case "2,3":
  502. vComp = record;
  503. break;
  504. default:
  505. scalar = record;
  506. }
  507. });
  508. return createWindBuilder(uComp, vComp);
  509. };
  510. var buildGrid = function buildGrid(data, callback) {
  511. var supported = true;
  512. if (data.length < 2) supported = false;
  513. if (!supported) console.log("Windy Error: data must have at least two components (u,v)");
  514. builder = createBuilder(data);
  515. var header = builder.header;
  516. if (header.hasOwnProperty("gridDefinitionTemplate") && header.gridDefinitionTemplate != 0) supported = false;
  517. if (!supported) {
  518. console.log("Windy Error: Only data with Latitude_Longitude coordinates is supported");
  519. }
  520. supported = true; // reset for futher checks
  521. λ0 = header.lo1;
  522. φ0 = header.la1; // the grid's origin (e.g., 0.0E, 90.0N)
  523. Δλ = header.dx;
  524. Δφ = header.dy; // distance between grid points (e.g., 2.5 deg lon, 2.5 deg lat)
  525. ni = header.nx;
  526. nj = header.ny; // number of grid points W-E and N-S (e.g., 144 x 73)
  527. if (header.hasOwnProperty("scanMode")) {
  528. var scanModeMask = header.scanMode.toString(2);
  529. scanModeMask = ('0' + scanModeMask).slice(-8);
  530. var scanModeMaskArray = scanModeMask.split('').map(Number).map(Boolean);
  531. if (scanModeMaskArray[0]) Δλ = -Δλ;
  532. if (scanModeMaskArray[1]) Δφ = -Δφ;
  533. if (scanModeMaskArray[2]) supported = false;
  534. if (scanModeMaskArray[3]) supported = false;
  535. if (scanModeMaskArray[4]) supported = false;
  536. if (scanModeMaskArray[5]) supported = false;
  537. if (scanModeMaskArray[6]) supported = false;
  538. if (scanModeMaskArray[7]) supported = false;
  539. if (!supported) console.log("Windy Error: Data with scanMode: " + header.scanMode + " is not supported.");
  540. }
  541. date = new Date(header.refTime);
  542. date.setHours(date.getHours() + header.forecastTime);
  543. // Scan modes 0, 64 allowed.
  544. // http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table3-4.shtml
  545. grid = [];
  546. var p = 0;
  547. var isContinuous = Math.floor(ni * Δλ) >= 360;
  548. for (var j = 0; j < nj; j++) {
  549. var row = [];
  550. for (var i = 0; i < ni; i++, p++) {
  551. row[i] = builder.data(p);
  552. }
  553. if (isContinuous) {
  554. // For wrapped grids, duplicate first column as last column to simplify interpolation logic
  555. row.push(row[0]);
  556. }
  557. grid[j] = row;
  558. }
  559. callback({
  560. date: date,
  561. interpolate: interpolate
  562. });
  563. };
  564. /**
  565. * Get interpolated grid value from Lon/Lat position
  566. * @param λ {Float} Longitude
  567. * @param φ {Float} Latitude
  568. * @returns {Object}
  569. */
  570. var interpolate = function interpolate(λ, φ) {
  571. if (!grid) return null;
  572. var i = floorMod(λ - λ0, 360) / Δλ; // calculate longitude index in wrapped range [0, 360)
  573. var j = (φ0 - φ) / Δφ; // calculate latitude index in direction +90 to -90
  574. var fi = Math.floor(i),
  575. ci = fi + 1;
  576. var fj = Math.floor(j),
  577. cj = fj + 1;
  578. var row;
  579. if (row = grid[fj]) {
  580. var g00 = row[fi];
  581. var g10 = row[ci];
  582. if (isValue(g00) && isValue(g10) && (row = grid[cj])) {
  583. var g01 = row[fi];
  584. var g11 = row[ci];
  585. if (isValue(g01) && isValue(g11)) {
  586. // All four points found, so interpolate the value.
  587. return builder.interpolate(i - fi, j - fj, g00, g10, g01, g11);
  588. }
  589. }
  590. }
  591. return null;
  592. };
  593. /**
  594. * @returns {Boolean} true if the specified value is not null and not undefined.
  595. */
  596. var isValue = function isValue(x) {
  597. return x !== null && x !== undefined;
  598. };
  599. /**
  600. * @returns {Number} returns remainder of floored division, i.e., floor(a / n). Useful for consistent modulo
  601. * of negative numbers. See http://en.wikipedia.org/wiki/Modulo_operation.
  602. */
  603. var floorMod = function floorMod(a, n) {
  604. return a - n * Math.floor(a / n);
  605. };
  606. /**
  607. * @returns {Number} the value x clamped to the range [low, high].
  608. */
  609. var clamp = function clamp(x, range) {
  610. return Math.max(range[0], Math.min(x, range[1]));
  611. };
  612. /**
  613. * @returns {Boolean} true if agent is probably a mobile device. Don't really care if this is accurate.
  614. */
  615. var isMobile = function isMobile() {
  616. return /android|blackberry|iemobile|ipad|iphone|ipod|opera mini|webos/i.test(navigator.userAgent);
  617. };
  618. /**
  619. * Calculate distortion of the wind vector caused by the shape of the projection at point (x, y). The wind
  620. * vector is modified in place and returned by this function.
  621. */
  622. var distort = function distort(projection, λ, φ, x, y, scale, wind) {
  623. var u = wind[0] * scale;
  624. var v = wind[1] * scale;
  625. var d = distortion(projection, λ, φ, x, y);
  626. // Scale distortion vectors by u and v, then add.
  627. wind[0] = d[0] * u + d[2] * v;
  628. wind[1] = d[1] * u + d[3] * v;
  629. return wind;
  630. };
  631. var distortion = function distortion(projection, λ, φ, x, y) {
  632. var τ = 2 * Math.PI;
  633. // var H = Math.pow(10, -5.2); // 0.00000630957344480193
  634. // var H = 0.0000360; // 0.0000360°φ ~= 4m (from https://github.com/cambecc/earth/blob/master/public/libs/earth/1.0.0/micro.js#L13)
  635. var H = 5; // ToDo: Why does this work?
  636. var hλ = λ < 0 ? H : -H;
  637. var hφ = φ < 0 ? H : -H;
  638. var pλ = project(φ, λ + hλ);
  639. var pφ = project(φ + hφ, λ);
  640. // Meridian scale factor (see Snyder, equation 4-3), where R = 1. This handles issue where length of 1º λ
  641. // changes depending on φ. Without this, there is a pinching effect at the poles.
  642. var k = Math.cos(φ / 360 * τ);
  643. return [(pλ[0] - x) / hλ / k, (pλ[1] - y) / hλ / k, (pφ[0] - x) / hφ, (pφ[1] - y) / hφ];
  644. };
  645. var createField = function createField(columns, bounds, callback) {
  646. /**
  647. * @returns {Array} wind vector [u, v, magnitude] at the point (x, y), or [NaN, NaN, null] if wind
  648. * is undefined at that point.
  649. */
  650. function field(x, y) {
  651. var column = columns[Math.round(x)];
  652. return column && column[Math.round(y)] || NULL_WIND_VECTOR;
  653. }
  654. // Frees the massive "columns" array for GC. Without this, the array is leaked (in Chrome) each time a new
  655. // field is interpolated because the field closure's context is leaked, for reasons that defy explanation.
  656. field.release = function () {
  657. columns = [];
  658. };
  659. field.randomize = function (o) {
  660. // UNDONE: this method is terrible
  661. var x, y;
  662. var safetyNet = 0;
  663. do {
  664. x = Math.round(Math.floor(Math.random() * bounds.width) + bounds.x);
  665. y = Math.round(Math.floor(Math.random() * bounds.height) + bounds.y);
  666. } while (field(x, y)[2] === null && safetyNet++ < 30);
  667. o.x = x;
  668. o.y = y;
  669. return o;
  670. };
  671. callback(bounds, field);
  672. };
  673. var buildBounds = function buildBounds(bounds, width, height) {
  674. var upperLeft = bounds[0];
  675. var lowerRight = bounds[1];
  676. var x = Math.round(upperLeft[0]); //Math.max(Math.floor(upperLeft[0], 0), 0);
  677. var y = Math.max(Math.floor(upperLeft[1], 0), 0);
  678. var xMax = Math.min(Math.ceil(lowerRight[0], width), width - 1);
  679. var yMax = Math.min(Math.ceil(lowerRight[1], height), height - 1);
  680. return {
  681. x: x,
  682. y: y,
  683. xMax: width,
  684. yMax: yMax,
  685. width: width,
  686. height: height
  687. };
  688. };
  689. var deg2rad = function deg2rad(deg) {
  690. return deg / 180 * Math.PI;
  691. };
  692. var invert = function invert(x, y, windy) {
  693. var latlon = params.map.containerPointToLatLng(BM.point(x, y));
  694. return [latlon.lng, latlon.lat];
  695. };
  696. var project = function project(lat, lon, windy) {
  697. var xy = params.map.latLngToContainerPoint(BM.latLng(lat, lon));
  698. return [xy.x, xy.y];
  699. };
  700. var interpolateField = function interpolateField(grid, bounds, extent, callback) {
  701. var projection = {}; // map.crs used instead
  702. var mapArea = (extent.south - extent.north) * (extent.west - extent.east);
  703. var velocityScale = VELOCITY_SCALE * Math.pow(mapArea, 0.4);
  704. var columns = [];
  705. var x = bounds.x;
  706. function interpolateColumn(x) {
  707. var column = [];
  708. for (var y = bounds.y; y <= bounds.yMax; y += 2) {
  709. var coord = invert(x, y);
  710. if (coord) {
  711. var λ = coord[0],
  712. φ = coord[1];
  713. if (isFinite(λ)) {
  714. var wind = grid.interpolate(λ, φ);
  715. if (wind) {
  716. wind = distort(projection, λ, φ, x, y, velocityScale, wind);
  717. column[y + 1] = column[y] = wind;
  718. }
  719. }
  720. }
  721. }
  722. columns[x + 1] = columns[x] = column;
  723. }
  724. (function batchInterpolate() {
  725. var start = Date.now();
  726. while (x < bounds.width) {
  727. interpolateColumn(x);
  728. x += 2;
  729. if (Date.now() - start > 1000) {
  730. //MAX_TASK_TIME) {
  731. setTimeout(batchInterpolate, 25);
  732. return;
  733. }
  734. }
  735. createField(columns, bounds, callback);
  736. })();
  737. };
  738. var animationLoop;
  739. var animate = function animate(bounds, field) {
  740. function windIntensityColorScale(min, max) {
  741. colorScale.indexFor = function (m) {
  742. // map velocity speed to a style
  743. return Math.max(0, Math.min(colorScale.length - 1, Math.round((m - min) / (max - min) * (colorScale.length - 1))));
  744. };
  745. return colorScale;
  746. }
  747. var colorStyles = windIntensityColorScale(MIN_VELOCITY_INTENSITY, MAX_VELOCITY_INTENSITY);
  748. var buckets = colorStyles.map(function () {
  749. return [];
  750. });
  751. var particleCount = Math.round(bounds.width * bounds.height * PARTICLE_MULTIPLIER);
  752. if (isMobile()) {
  753. particleCount *= PARTICLE_REDUCTION;
  754. }
  755. var fadeFillStyle = "rgba(0, 0, 0, ".concat(OPACITY, ")");
  756. var particles = [];
  757. for (var i = 0; i < particleCount; i++) {
  758. particles.push(field.randomize({
  759. age: Math.floor(Math.random() * MAX_PARTICLE_AGE) + 0
  760. }));
  761. }
  762. function evolve() {
  763. buckets.forEach(function (bucket) {
  764. bucket.length = 0;
  765. });
  766. particles.forEach(function (particle) {
  767. if (particle.age > MAX_PARTICLE_AGE) {
  768. field.randomize(particle).age = 0;
  769. }
  770. var x = particle.x;
  771. var y = particle.y;
  772. var v = field(x, y); // vector at current position
  773. var m = v[2];
  774. if (m === null) {
  775. particle.age = MAX_PARTICLE_AGE; // particle has escaped the grid, never to return...
  776. } else {
  777. var xt = x + v[0];
  778. var yt = y + v[1];
  779. if (field(xt, yt)[2] !== null) {
  780. // Path from (x,y) to (xt,yt) is visible, so add this particle to the appropriate draw bucket.
  781. particle.xt = xt;
  782. particle.yt = yt;
  783. buckets[colorStyles.indexFor(m)].push(particle);
  784. } else {
  785. // Particle isn't visible, but it still moves through the field.
  786. particle.x = xt;
  787. particle.y = yt;
  788. }
  789. }
  790. particle.age += 1;
  791. });
  792. }
  793. var g = params.canvas.getContext("2d");
  794. g.lineWidth = PARTICLE_LINE_WIDTH;
  795. g.fillStyle = fadeFillStyle;
  796. g.globalAlpha = 0.6;
  797. function draw() {
  798. // Fade existing particle trails.
  799. var prev = "lighter";
  800. g.globalCompositeOperation = "destination-in";
  801. g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
  802. g.globalCompositeOperation = prev;
  803. g.globalAlpha = OPACITY === 0 ? 0 : OPACITY * 0.9;
  804. // Draw new particle trails.
  805. buckets.forEach(function (bucket, i) {
  806. if (bucket.length > 0) {
  807. g.beginPath();
  808. g.strokeStyle = colorStyles[i];
  809. bucket.forEach(function (particle) {
  810. g.moveTo(particle.x, particle.y);
  811. g.lineTo(particle.xt, particle.yt);
  812. particle.x = particle.xt;
  813. particle.y = particle.yt;
  814. });
  815. g.stroke();
  816. }
  817. });
  818. }
  819. var then = Date.now();
  820. (function frame() {
  821. animationLoop = requestAnimationFrame(frame);
  822. var now = Date.now();
  823. var delta = now - then;
  824. if (delta > FRAME_TIME) {
  825. then = now - delta % FRAME_TIME;
  826. evolve();
  827. draw();
  828. }
  829. })();
  830. };
  831. var start = function start(bounds, width, height, extent) {
  832. var mapBounds = {
  833. south: deg2rad(extent[0][1]),
  834. north: deg2rad(extent[1][1]),
  835. east: deg2rad(extent[1][0]),
  836. west: deg2rad(extent[0][0]),
  837. width: width,
  838. height: height
  839. };
  840. stop();
  841. // build grid
  842. buildGrid(gridData, function (grid) {
  843. // interpolateField
  844. interpolateField(grid, buildBounds(bounds, width, height), mapBounds, function (bounds, field) {
  845. // animate the canvas with random points
  846. windy.field = field;
  847. animate(bounds, field);
  848. });
  849. });
  850. };
  851. var stop = function stop() {
  852. if (windy.field) windy.field.release();
  853. if (animationLoop) cancelAnimationFrame(animationLoop);
  854. };
  855. var windy = {
  856. params: params,
  857. start: start,
  858. stop: stop,
  859. createField: createField,
  860. interpolatePoint: interpolate,
  861. setData: setData,
  862. setOptions: setOptions,
  863. colorScale: colorScale
  864. };
  865. return windy;
  866. };
  867. if (!window.cancelAnimationFrame) {
  868. window.cancelAnimationFrame = function (id) {
  869. clearTimeout(id);
  870. };
  871. }