source: src/webapp/webclient/js/GnuBoat.Webclient.js@ b240fb0

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