source: src/webapp/webclient/js/GnuBoat.js@ 91626d5

0.5 debian/bullseye debian/jessie
Last change on this file since 91626d5 was b8b5e77, checked in by Joachim Langenbach <joachim.langenbach@…>, 9 years ago

Improved coloring of the leaflet hotlines and the 3D rendering

  • Property mode set to 100644
File size: 26.5 KB
Line 
1/*
2
3 Copyright (C) 2016 - 2017 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 MA 02110-1301 USA.
19
20*/
21
22/** @namespace GnuBoat JavaScript namespace */
23var GnuBoat = GnuBoat || {};
24
25/**
26 * @brief Sets the webservice base url, used by any other functions
27 */
28GnuBoat.setServer = function(baseUrl)
29{
30 if(baseUrl.slice(-1) != "/")
31 baseUrl += "/";
32 GnuBoat.private.serverBaseUrl = baseUrl;
33
34 var link = document.createElement("a");
35 link.setAttribute("href", baseUrl);
36 $("#opencpnHint").empty();
37 $("<p>To connect OpenCPN with the GPSD running on this webservice, use <b>"+ link.hostname +":2947</b> and <b>"+ link.hostname +":2597</b> for the messages recieved on NMEA2000 bus.</p>").appendTo("#opencpnHint");
38}
39
40/**
41 * @brief Used to display user messages
42 */
43GnuBoat.displayMessage = function(text)
44{
45 $("#message").empty();
46 $(text).appendTo("#message");
47 location.hash = "#messages";
48}
49
50/**
51 * @brief Fetches the data shown in the display area from the webservice
52 */
53GnuBoat.displayDataGet = function()
54{
55 if(GnuBoat.private.serverBaseUrl == null){
56 GnuBoat.displayMessage('<span class="error">No server set/found</span>');
57 return;
58 }
59 var gnuboatApi = GnuBoat.private.serverBaseUrl;
60 $.getJSON(gnuboatApi, GnuBoat.private.displayDataSet);
61};
62
63/**
64 * @brief Gets the metadata of all maps, provided by the tileserver
65 */
66GnuBoat.getMapInfos = function()
67{
68 if(GnuBoat.private.serverBaseUrl == null){
69 GnuBoat.displayMessage('<span class="error">No server set/found</span>');
70 return;
71 }
72 $.getJSON(GnuBoat.private.serverBaseUrl +"tileserver.php?/index.json", GnuBoat.private.mapInfos);
73};
74
75/**
76 * @brief Fetches the list of available logfiles and adds them to the log file download form
77 */
78GnuBoat.logfilesLoad = function()
79{
80 if(GnuBoat.private.serverBaseUrl == null){
81 GnuBoat.displayMessage('<span class="error">No server set/found</span>');
82 return;
83 }
84 $("#logfilesForm").empty();
85 $.getJSON(GnuBoat.private.serverBaseUrl +"?request=logfiles", function(data){
86 GnuBoat.private.updateMapModus(data);
87 if(!Array.isArray(data) || data.length < 1){
88 $("<p>No Logfiles found!</p>").appendTo("#logfilesForm");
89 console.log(data);
90 return;
91 }
92 if(("error" in data) && data["error"] == 1){
93 GnuBoat.displayMessage('<span class="error">Failed to get log files: '+ data["errormessage"] +'</span>');
94 $("<p>No Logfiles found!</p>").appendTo("#logfilesForm");
95 console.log(data);
96 return;
97 }
98 $("<select id=\"logfilesSelect\" name=\"logfilesSelected[]\" class=\"pure-input-1\" multiple></select>").appendTo("#logfilesForm");
99 $("<input type=\"submit\" class=\"pure-button pure-button-primary\" name=\"logfilesDownload\" value=\"Download\"/>").appendTo("#logfilesForm");
100 data.forEach(function(value, index){
101 $("<option value=\""+ value +"\">"+ value +"</option>").appendTo("#logfilesSelect");
102 });
103 });
104};
105/**
106 * @brief Sends a shutdown request to the webservice
107 */
108GnuBoat.shutdown = function()
109{
110 if(GnuBoat.private.serverBaseUrl == null){
111 GnuBoat.displayMessage('<span class="error">No server set/found</span>');
112 return;
113 }
114 $.getJSON(GnuBoat.private.serverBaseUrl +"?request=shutdown", function(data){
115 var shutdownTime = data["shutdownstart"];
116 var shutdownDate = Date.parse(shutdownTime);
117 var currentDate = new Date();
118 var shutdownHint = '<span class="info">Shutting down in '+ Math.floor((shutdownDate - currentDate)/1000) +"s at "+ shutdownTime.toLocaleString() +"</span>";
119 if(shutdownTime == -1){
120 shutdownHint = '<span class="error">Failed to initiate shutdown: '+ data["errormessage"] +"</span>";
121 }
122 GnuBoat.displayMessage(shutdownHint);
123 });
124};
125
126/**
127 * @brief Uploads a map and refreshes the maps metadata on success
128 */
129GnuBoat.uploadMap = function(form)
130{
131 if(GnuBoat.private.serverBaseUrl == null){
132 displayMessage('<span class="error">No server set/found</span>');
133 return;
134 }
135 $("#mapFileInput").hide();
136 $("#mapTileUploadProgress").show();
137 $.ajax({
138 type: 'POST',
139 url: GnuBoat.private.serverBaseUrl +'?request=map',
140 data: new FormData($("#mapTileUpload")[0]),
141 contentType: false,
142 processData: false,
143 success: function(data){
144 if(("error" in data) && data["error"] == 1){
145 GnuBoat.displayMessage('<span class="error">Failed to upload map: '+ data["errormessage"] +'</span>');
146 $("#mapTileUploadProgress").hide();
147 $("#mapFileInput").show();
148 return;
149 }
150 GnuBoat.displayMessage('<span class="error">Map upload successfully</span>');
151 $("#mapTileUploadProgress").hide();
152 $("#mapFileInput").show();
153 GnuBoat.getMapInfos();
154 },
155 error: function(jqXHR, exception, errorThrown){
156 GnuBoat.displayMessage('<span class="error">Failed to upload map (XHR): '+ exception +'</span>');
157 $("#mapTileUploadProgress").hide();
158 $("#mapFileInput").show();
159 }
160 }).progress(function(e){
161 $("#mapTileUploadProgress").attr({value: e.oloaded, max: e.total});
162 });
163};
164
165/**
166 * @brief Setups up GnuBoat to be able to start() after configured a server with setServer().
167 */
168GnuBoat.initialize = function()
169{
170 $("#mapModusSelect").change(function(){ GnuBoat.private.mapModusChanged(); });
171 $("#mapTileUploadProgress").hide();
172 $("#logfilesReload").click(GnuBoat.logfilesLoad);
173 $("#shutdownButton").click(GnuBoat.shutdown);
174
175 $("#mapTileUpload").validate({
176 rules: {
177 mapFile: {
178 required: true
179 },
180 mapName: {
181 required: true
182 }
183 },
184 submitHandler: function(form){
185 GnuBoat.uploadMap(form);
186 }
187 });
188
189 $("#logfilesForm").validate({
190 rules: {
191 logfilesSelect: {
192 required: true
193 },
194 }
195 });
196
197 $("#rendering").empty();
198 var width = $("#rendering").width();
199 var height = $("#rendering").height();
200
201 var fieldOfView = 75;
202
203 GnuBoat.private.renderScene = new THREE.Scene();
204 GnuBoat.private.renderScene.background = new THREE.Color(0xEEEEEE);
205
206 GnuBoat.private.renderCamera = new THREE.PerspectiveCamera(75, width/height, 0.1, 1000000);
207 GnuBoat.private.renderCamera.up = new THREE.Vector3(0, 0, 1);
208 GnuBoat.private.renderCamera.position.set(-0.01, -0.01, 15000);
209 GnuBoat.private.renderCamera.lookAt(GnuBoat.private.renderScene.position);
210
211 GnuBoat.private.renderRenderer = new THREE.WebGLRenderer();
212 GnuBoat.private.renderRenderer.setSize(width, height);
213 GnuBoat.private.renderRenderer.setPixelRatio( window.devicePixelRatio );
214 document.getElementById("rendering").appendChild(GnuBoat.private.renderRenderer.domElement);
215
216 GnuBoat.private.renderControls = new THREE.OrbitControls( GnuBoat.private.renderCamera, GnuBoat.private.renderRenderer.domElement );
217 GnuBoat.private.renderControls.zoomSpeed = 2;
218}
219
220/**
221 * @brief Starts querying the webservice
222 *
223 * Call initialize() and setServer() before start()
224 */
225GnuBoat.start = function()
226{
227 if(GnuBoat.private.serverBaseUrl == null){
228 GnuBoat.displayMessage('<span class="error">No server set/found</span>');
229 return;
230 }
231
232 GnuBoat.getMapInfos();
233 GnuBoat.displayDataGet();
234 if(GnuBoat.private.timerDisplay == null)
235 GnuBoat.private.timerDisplay = setInterval(GnuBoat.displayDataGet, 10000);
236 GnuBoat.logfilesLoad();
237
238 GnuBoat.private.animate();
239}
240
241/**
242 * @brief Stops querying the webservice
243 */
244GnuBoat.stop = function()
245{
246 if(GnuBoat.private.timerDisplay != null){
247 clearInterval(GnuBoat.private.timerDisplay);
248 GnuBoat.private.timerDisplay = null;
249 }
250}
251
252/**
253 * @brief Private methods and properties of GnuBoat
254 */
255GnuBoat.private = {
256 map: null,
257 mapLayerCurrent: null,
258 mapPolylines: [],
259 mapControl: null,
260 mapsMetadata: null,
261 mapBounds: null,
262 mapModusLive: true,
263 mapHotlineGradientDefault: { absolute: false, palette: { 0.0: 'green', 0.5: 'yellow', 1.0: 'red' } },
264 dataMappings: {
265 speedthroughwater: {display: true, map: true, mapActive: false, titleLong: "Speed Through Water", titleShort: "STW", unit: "kts"},
266 speedoverground: {display: true, map: true, mapActive: false, titleLong: "Speed Over Ground", titleShort: "SOG", unit: "kts"},
267 waterdepth: {
268 display: true, map: true, mapActive: true, titleLong: "Waterdepth", titleShort: "Depth", unit: "m",
269 gradient: {
270 absolute: true,
271 palette: { 0: 'DarkBlue', 2: 'DodgerBlue', 6: 'LightBlue', 10: 'AliceBlue'},
272 }
273 },
274 watertemperature: {display: true, map: true, mapActive: false, titleLong: "Watertemperature", titleShort: "Water", unit: "°C"},
275 gpsfix: {display: true, map: false, mapActive: false, titleLong: "GPS Fix", titleShort: "Fix", unit: ""},
276 },
277 serverBaseUrl: null,
278 timerDisplay: null,
279 renderScene: null,
280 renderCamera: null,
281 renderRenderer: null,
282 renderMapBounds: null,
283 renderGrid: null,
284 renderControls: null,
285 renderCloud: null,
286
287 openLink: function(target)
288 {
289 window.location=target;
290 },
291
292 displayDataSet: function(data)
293 {
294// if(!Array.isArray(data) || data.length < 1){
295// console.log("No data array returned!");
296// console.log(data);
297// return;
298// }
299 if(("error" in data) && data["error"] == 1){
300 GnuBoat.displayMessage('<span class="error">Failed to get display data and tracks: '+ data["errormessage"] +'</span>');
301 return;
302 }
303
304 var keysDisplay = [];
305 for(var key in GnuBoat.private.dataMappings){
306 if(GnuBoat.private.dataMappings[key]["display"] === true)
307 keysDisplay.push(key);
308 }
309
310 if(!("lastvalid" in data)){
311 console.log("No last valid values given!");
312 }
313 else{
314 var lastValid = data["lastvalid"];
315 for(var i = 0; i < keysDisplay.length; i++){
316 var key = keysDisplay[i];
317 var value = lastValid[key];
318 if($.isNumeric(value)){
319 var text = value.toFixed(1);
320 if(key == "watertemperature"){
321 text = value.toFixed(0);
322 }
323 $("#display #"+ key +" #value").text(text);
324 }
325 else if(key == "gpsfix"){
326 $("#display #"+ key +" #value").text(value);
327 }
328 }
329 }
330
331 // map displays logged data
332 if(!GnuBoat.private.mapModusLive)
333 return;
334 else if(!("track" in data)){
335 console.log("No track given!");
336 return;
337 }
338 GnuBoat.private.mapAddTracks(data["track"]);
339 },
340
341 mapSetup: function ()
342 {
343 var mapMetadataIndex = $("#mapSelect").val();
344 if(GnuBoat.private.mapsMetadata == null){
345 console.log("No mapsMetadata set");
346 return;
347 }
348 if(mapMetadataIndex < 0 || mapMetadataIndex >= GnuBoat.private.mapsMetadata.length){
349 console.log("Map metadata is outside of range :"+ mapMetadataIndex.toString());
350 console.log(mapsMetadata);
351 return;
352 }
353 var mapMetadata = GnuBoat.private.mapsMetadata[mapMetadataIndex];
354
355 var latitudeTop = mapMetadata["bounds"][3];
356 var latitudeBottom = mapMetadata["bounds"][1];
357 var longitudeLeft = mapMetadata["bounds"][0];
358 var longitudeRight = mapMetadata["bounds"][2];
359
360 var mapZoomMin = mapMetadata["minzoom"];
361 var mapZoomMax = mapMetadata["maxzoom"];
362
363 var latitudeCenter = (latitudeTop - latitudeBottom)/2 + latitudeBottom;
364 var longitudeCenter = (longitudeLeft - longitudeRight)/2 + longitudeRight;
365 var mapZoomStart = (mapZoomMax - mapZoomMin)/2 + mapZoomMin;
366
367 GnuBoat.private.mapBounds = new L.LatLngBounds(
368 new L.LatLng(latitudeBottom, longitudeLeft),
369 new L.LatLng(latitudeTop, longitudeRight));
370
371 if(GnuBoat.private.map == null){
372 // only initialize the map (viewport) once
373 GnuBoat.private.map = L.map('mapViewport');
374 GnuBoat.private.map.on('overlayadd', function(layerObject){ GnuBoat.private.mapOverlayLegendSwitch(layerObject.layer); });
375 GnuBoat.private.map.on('overlayremove', function(layerObject){ GnuBoat.private.mapOverlayLegendSwitch(layerObject.layer); });
376 }
377 GnuBoat.private.map.setView([latitudeCenter, longitudeCenter], mapZoomStart);
378
379 if(GnuBoat.private.mapLayerCurrent != null){
380 GnuBoat.private.map.removeLayer(GnuBoat.private.mapLayerCurrent);
381 if(GnuBoat.private.mapControl)
382 GnuBoat.private.mapControl.removeLayer(GnuBoat.private.mapLayerCurrent);
383 GnuBoat.private.mapLayerCurrent = null;
384 }
385 GnuBoat.private.mapLayerCurrent = L.tileLayer(mapMetadata["tiles"][0], {
386 minZoom: mapZoomMin, maxZoom: mapZoomMax,
387 bounds: GnuBoat.private.mapBounds,
388 attribution: mapMetadata["name"],
389 opacity: 0.85
390 }).addTo(GnuBoat.private.map);
391 if(GnuBoat.private.mapControl != null)
392 GnuBoat.private.mapControl.addBaseLayer(GnuBoat.private.mapLayerCurrent, "Map");
393 else{
394 GnuBoat.private.mapControl = L.control.layers({"Map": GnuBoat.private.mapLayerCurrent}, GnuBoat.private.mapOverlaysToList(), {hideSingleBase: true, sortLayers: true, }).addTo(GnuBoat.private.map);
395 }
396
397 // configure render scene for new map
398 GnuBoat.private.renderSetupMap();
399 },
400
401 mapInfos: function(data)
402 {
403 GnuBoat.private.mapsMetadata = data;
404
405 $("#mapSelect").empty();
406 var selected = "selected";
407 data.forEach(function(value, index){
408 $("<option value=\""+ index.toString() +"\" "+ selected +">"+ value["name"] +"</option>").appendTo("#mapSelect");
409 selected = "";
410 });
411
412 GnuBoat.private.mapSetup();
413 $("#mapSelect").change(function(){ GnuBoat.private.mapSetup(); });
414 },
415
416 mapOverlaysToList: function()
417 {
418 var overlays = {};
419 for(var key in GnuBoat.private.mapPolylines){
420 overlays[key] = GnuBoat.private.mapPolylines[key];
421 }
422 return overlays;
423 },
424
425 renderSetupMap: function()
426 {
427 if(GnuBoat.private.mapBounds == null)
428 return;
429
430 // add map bounds
431 if(GnuBoat.private.renderMapBounds != null)
432 GnuBoat.private.renderScene.remove(GnuBoat.private.renderMapBounds);
433 var m1 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getSouth(), GnuBoat.private.mapBounds.getWest());
434 var m2 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getSouth(), GnuBoat.private.mapBounds.getEast());
435 var m3 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getNorth(), GnuBoat.private.mapBounds.getEast());
436 var m4 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getNorth(), GnuBoat.private.mapBounds.getWest());
437 var geometryMapBounds = new THREE.Geometry();
438 var materialMapBounds = new THREE.LineBasicMaterial({color: 0x66BD66, linewidth: 1});
439 // z is greator 0, to draw the map boundings over the grid
440 var vertex = new THREE.Vector3(0, 0, 2);
441 geometryMapBounds.vertices.push(vertex);
442 vertex = new THREE.Vector3(m2.x - m1.x, m2.y - m1.y, 2);
443 geometryMapBounds.vertices.push(vertex);
444 vertex = new THREE.Vector3(m3.x - m1.x, m3.y - m1.y, 2);
445 geometryMapBounds.vertices.push(vertex);
446 vertex = new THREE.Vector3(m4.x - m1.x, m4.y - m1.y, 2);
447 geometryMapBounds.vertices.push(vertex);
448 GnuBoat.private.renderMapBounds = new THREE.LineLoop(geometryMapBounds, materialMapBounds);
449 GnuBoat.private.renderScene.add(GnuBoat.private.renderMapBounds);
450
451 // add 500m grid
452 if(GnuBoat.private.renderGrid != null)
453 GnuBoat.private.renderScene.remove(GnuBoat.private.renderGrid);
454 geometryMapBounds.computeBoundingBox();
455 var maxLength = Math.max(geometryMapBounds.boundingBox.getSize().x, geometryMapBounds.boundingBox.getSize().y);
456 GnuBoat.private.renderGrid = new THREE.GridHelper(maxLength, Math.round(maxLength / 500.0), 0xCCCCCC, 0xCCCCCC);
457 GnuBoat.private.renderGrid.geometry.rotateX( Math.PI / 2 );
458 GnuBoat.private.renderGrid.translateX(maxLength / 2.0);
459 GnuBoat.private.renderGrid.translateY(maxLength / 2.0);
460 GnuBoat.private.renderScene.add(GnuBoat.private.renderGrid);
461
462 var distance = 150;
463 var fieldOfView = 2 * Math.atan(maxLength / (2.0 * distance) ) * 180.0 / Math.PI;
464 GnuBoat.private.renderCamera.position.set(-10, -5, 100);
465 GnuBoat.private.renderCamera.fov = fieldOfView;
466 GnuBoat.private.renderCamera.lookAt(GnuBoat.private.renderScene.position);
467 GnuBoat.private.renderCamera.zoom = 5;
468 GnuBoat.private.renderCamera.updateProjectionMatrix();
469 },
470
471 drawDensityEstimation: function(densityPoints, gradient, maximum, minimum)
472 {
473 var colors = GnuBoat.private.gradientToRenderColors(gradient, maximum, minimum);
474 // converting all indizes into numbers to sort them correctly
475 // in descending order e.g. 10, 2, 1, 0 and not 2, 10, 1, 0
476 var colorsIndizes = Object.getOwnPropertyNames(colors);
477 colorsIndizes.sort(function(a, b){
478 a = +a;
479 b = +b;
480 return a-b;
481 });
482 var colorsCount = colorsIndizes.length;
483
484 var material = new THREE.PointsMaterial({vertexColors: THREE.VertexColors, size: 5});
485 var geometry = new THREE.Geometry();
486 var mercatorSouthWest = {x: 0, y: 0};
487 if(GnuBoat.private.mapBounds != null)
488 mercatorSouthWest = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getSouth(), GnuBoat.private.mapBounds.getWest());
489
490 for(var i = 0; i < densityPoints.length; i++){
491 var mercator = GnuBoat.private.mercator(densityPoints[i].latitude, densityPoints[i].longitude);
492 var vertex = new THREE.Vector3(mercator.x - mercatorSouthWest.x, mercator.y - mercatorSouthWest.y, (densityPoints[i].depth * -1) + maximum);
493 var step = (densityPoints[i].depth - minimum)/(maximum-minimum);
494 var color = new THREE.Color(0x000000);
495 for(var j = 0; j < colorsCount; j++){
496 if(j < colorsCount - 1)
497 color = colors[colorsIndizes[j]];
498 if(step <= colorsIndizes[j+1]){
499 color = colors[colorsIndizes[j]];
500 break;
501 }
502 }
503 geometry.vertices.push(vertex);
504 geometry.colors.push(color);
505 }
506 // point cloud
507 if(GnuBoat.private.renderCloud != null)
508 GnuBoat.private.renderScene.remove(GnuBoat.private.renderCloud);
509 GnuBoat.private.renderCloud = new THREE.Points(geometry, material);
510 GnuBoat.private.renderScene.add(GnuBoat.private.renderCloud);
511 },
512
513 animate: function()
514 {
515 requestAnimationFrame(GnuBoat.private.animate);
516 if(GnuBoat.private.renderCloud != null){
517 var scaleZ = $("#renderScaleZ").val();
518 if(GnuBoat.private.renderCloud.scale.z != scaleZ)
519 GnuBoat.private.renderCloud.scale.set(1, 1, scaleZ);
520 }
521
522 GnuBoat.private.renderControls.update();
523 GnuBoat.private.renderRenderer.render(GnuBoat.private.renderScene, GnuBoat.private.renderCamera);
524 },
525
526 mercator: function(latitude, longitude)
527 {
528 var result = {};
529
530 var earthRadius = 6378137.0;
531
532 result["x"] = longitude / 180.0 * Math.PI * earthRadius;
533 result["y"] = Math.log(Math.tan(latitude / 180.0 * Math.PI / 2.0 + Math.PI / 4.0)) * earthRadius;
534
535 return result;
536 },
537
538 updateMapModus: function(data)
539 {
540 var selected = $("#mapModusSelect").val();
541 $("#mapModusSelect").empty();
542 var selectedFound = false;
543 if(selected != null && Array.isArray(data)){
544 data.forEach(function(value, index){
545 if(value == selected)
546 selectedFound = true;
547 });
548 }
549 var selectedString = "";
550 if(!selectedFound)
551 selectedString = " selected";
552 $('<option value="live"'+ selectedString +'>Live View</option>').appendTo("#mapModusSelect");
553 if(!Array.isArray(data) || data.length < 1){
554 console.log(data);
555 return;
556 }
557 if(("error" in data) && data["error"] == 1){
558 GnuBoat.displayMessage('<span class="error">Failed to upload map: '+ data["errormessage"] +'</span>');
559 return;
560 }
561 data.forEach(function(value, index){
562 var selectedString = "";
563 if(value == selected)
564 selectedString = " selected";
565 $("<option value=\""+ value +"\""+ selected +">"+ value +"</option>").appendTo("#mapModusSelect");
566 });
567 },
568
569 mapModusChanged: function()
570 {
571 var modus = $("#mapModusSelect").val();
572 // live modus is automatically activated on displayDataSet
573 if(modus == "live"){
574 GnuBoat.private.mapModusLive = true;
575 return;
576 }
577 // remove overlays
578 if(GnuBoat.private.mapControl != null){
579 for(var key in GnuBoat.private.dataMappings){
580 if(GnuBoat.private.dataMappings[key]["map"] === true)
581 if(key in GnuBoat.private.mapPolylines){
582 GnuBoat.private.mapControl.removeLayer(GnuBoat.private.mapPolylines[key]);
583 GnuBoat.private.mapPolylines[key].remove();
584 delete GnuBoat.private.mapPolylines[key];
585 }
586 }
587 }
588 GnuBoat.private.mapModusLive = false;
589 $.post({
590 url: GnuBoat.private.serverBaseUrl +'?request=replay',
591 data: { logfile: modus },
592 success: function(data){
593// if(!Array.isArray(data) || data.length < 1){
594// console.log("No data array returned!");
595// console.log(data);
596// return;
597// }
598 if(("error" in data) && data["error"] == 1){
599 GnuBoat.displayMessage('<span class="error">Failed to get logged tracks: '+ data["errormessage"] +'</span>');
600 return;
601 }
602 if(!("track" in data)){
603 console.log("No track given!");
604 return;
605 }
606 GnuBoat.private.mapAddTracks(data["track"]);
607 }
608 });
609 },
610
611 mapAddTracks: function(track)
612 {
613 if(GnuBoat.private.map == null){
614 console.log("No map in use");
615 return;
616 }
617
618 $("#mapLegend").empty();
619 var maximas = [];
620 var minimas = [];
621 var points = [];
622 var densityPoints = [];
623
624 var keysMap = [];
625 for(var key in GnuBoat.private.dataMappings){
626 if(GnuBoat.private.dataMappings[key]["map"] === true)
627 keysMap.push(key);
628 }
629 for(var i = 0; i < keysMap.length; i++){
630 points[keysMap[i]] = [];
631 }
632
633 // getting maximas, minimums for normalization and the tracks themselves
634 for(var time in track){
635 for(var i = 0; i < keysMap.length; i++){
636 var key = keysMap[i];
637 var value = track[time][key];
638 if(!$.isNumeric(value))
639 continue;
640 if(!(key in maximas))
641 maximas[key] = value
642 else if(maximas[key] < value)
643 maximas[key] = value;
644 if(!(key in minimas))
645 minimas[key] = value
646 else if(minimas[key] > value)
647 minimas[key] = value;
648 points[key].push(new L.latLng(track[time]["latitude"], track[time]["longitude"], value));
649 if(key == "waterdepth")
650 densityPoints.push({latitude: track[time]["latitude"], longitude: track[time]["longitude"], depth: value});
651 }
652 }
653 for(var i = 0; i < keysMap.length; i++){
654 var key = keysMap[i];
655 if(points[key].length > 0){
656 var palette = GnuBoat.private.mapHotlineGradientDefault.palette;
657 var paletteLegend = GnuBoat.private.mapHotlineGradientDefault.palette;
658 if("gradient" in GnuBoat.private.dataMappings[key]){
659 palette = GnuBoat.private.gradientToPalette(GnuBoat.private.dataMappings[key]["gradient"], maximas[key], minimas[key]);
660 // use original palette, to use absolute values, if possible
661 paletteLegend = GnuBoat.private.dataMappings[key]["gradient"]["palette"];
662 }
663
664 var legendTable = $('<table id="'+ key +'" class="hidden"></table>');
665 $("<tr><th colspan=2>"+ GnuBoat.private.dataMappings[key]["titleShort"] +" in "+ GnuBoat.private.dataMappings[key]["unit"] +"</th></tr>").appendTo(legendTable);
666 $("<tr><th>Level</th><th>Color</th></tr>").appendTo(legendTable);
667 // converting all indizes into numbers to sort them correctly
668 // e.g. 0, 1, 2, 10 and not 0, 1, 10, 2
669 var indizes = Object.getOwnPropertyNames(paletteLegend);
670 indizes.sort(function(a, b){
671 a = +a;
672 b = +b;
673 return a-b;
674 });
675 for(var j=0; j < indizes.length; j++){
676 var index = indizes[j];
677 $('<tr><td class="level">'+ index.toString() +'</td><td style="background-color: '+ paletteLegend[index] +'"></td></tr>').appendTo(legendTable);
678 }
679 $('<tr><td colspan="2">Extrema: '+ maximas[key].toString() +' / '+ minimas[key].toString() +'</td></tr>').appendTo(legendTable);
680
681 var hotlineOptions = {
682 weight: 3,
683 outlineWidth: 0,
684 min: minimas[key],
685 max: maximas[key],
686 palette: palette,
687 };
688
689 legendTable.appendTo("#mapLegend");
690
691 if(key in GnuBoat.private.mapPolylines){
692 GnuBoat.private.mapPolylines[key].setStyle(hotlineOptions);
693 GnuBoat.private.mapPolylines[key].setLatLngs(points[key]);
694 if(GnuBoat.private.map.hasLayer(GnuBoat.private.mapPolylines[key]))
695 GnuBoat.private.mapOverlayLegendSwitch(GnuBoat.private.mapPolylines[key]);
696 GnuBoat.private.mapPolylines[key].unbindPopup();
697 }
698 else{
699 GnuBoat.private.mapPolylines[key] = L.hotline(points[key], hotlineOptions);
700 if(GnuBoat.private.mapControl){
701 var name = GnuBoat.private.dataMappings[key]["titleLong"] +" in "+ GnuBoat.private.dataMappings[key]["unit"] +" ("+ GnuBoat.private.dataMappings[key]["titleShort"] +")";
702 GnuBoat.private.mapControl.addOverlay(GnuBoat.private.mapPolylines[key], name);
703 }
704 if(GnuBoat.private.dataMappings[key]["mapActive"] === true)
705 GnuBoat.private.mapPolylines[key].addTo(GnuBoat.private.map);
706 }
707 GnuBoat.private.mapPolylines[key].bindPopup(legendTable[0].outerHTML);
708 }
709 }
710 var gradient = GnuBoat.private.mapHotlineGradientDefault.palette;
711 if("gradient" in GnuBoat.private.dataMappings["waterdepth"])
712 gradient = GnuBoat.private.dataMappings["waterdepth"]["gradient"];
713 GnuBoat.private.drawDensityEstimation(densityPoints, gradient, maximas["waterdepth"], minimas["waterdepth"]);
714 },
715
716 gradientToPalette: function(gradient, maximum, minimum)
717 {
718 if(!("palette" in gradient)){
719 return GnuBoat.private.mapHotlineGradientDefault.palette;
720 }
721 if(!("absolute" in gradient) || !gradient.absolute){
722 // palette is already relative
723 return gradient.palette;
724 }
725 var range = maximum - minimum;
726 if(range == 0){
727 console.log("Range is zero --> Could not make gradient relative");
728 return GnuBoat.private.mapHotlineGradientDefault.palette;
729 }
730 var palette = {};
731 var addedStop = false;
732 for(var indexAbs in gradient.palette){
733 var indexRel = (indexAbs - minimum)/range;
734 if(indexRel < 0){
735 // add the nearest minimum value (which might be configured smaller than minimum)
736 indexRel = 0;
737 palette[indexRel] = gradient.palette[indexAbs];
738 addedStop = true;
739 }
740 else if(indexRel < 1){
741 palette[indexRel] = gradient.palette[indexAbs];
742 addedStop = true;
743 }
744 else{
745 // add first index > 1 as the maximum value at 1
746 indexRel = 1;
747 palette[indexRel] = gradient.palette[indexAbs];
748 addedStop = true;
749 break;
750 }
751 }
752 if(!addedStop)
753 return GnuBoat.private.mapHotlineGradientDefault.palette;
754 return palette;
755 },
756
757 gradientToRenderColors: function(gradient, maximum, minimum)
758 {
759 var paletteRelative = GnuBoat.private.gradientToPalette(gradient, maximum, minimum);
760
761 var colors = {};
762 for(var index in paletteRelative)
763 colors[index] = new THREE.Color(paletteRelative[index].toLowerCase());
764
765 return colors;
766 },
767
768 mapOverlayLegendSwitch: function(layer)
769 {
770 var overlayKey = null;
771 for(var key in GnuBoat.private.mapPolylines){
772 if(GnuBoat.private.mapPolylines.hasOwnProperty(key)){
773 if(GnuBoat.private.mapPolylines[key] === layer){
774 overlayKey = key;
775 break;
776 }
777 }
778 }
779 // ECMAScript 6
780// var overlayKey = Object.keys(GnuBoat.private.mapPolylines).find(key => GnuBoat.private.mapPolylines[key] === overlay);
781 if(overlayKey == null)
782 return;
783 if(overlayKey){
784 $("#mapLegend #"+ overlayKey).toggleClass("hidden");
785 }
786 },
787};
Note: See TracBrowser for help on using the repository browser.