source: src/webapp/webclient/js/GnuBoat.js@ fb91143

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

Added colored track lines to leaflet map view

  • Property mode set to 100644
File size: 12.7 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").clear();
46 $(shutdownHint).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("No server set/found");
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("No server set/found");
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("No server set/found");
82 return;
83 }
84 $("#logfilesForm").empty();
85 $.getJSON(GnuBoat.private.serverBaseUrl +"?request=logfiles", function(data){
86 if(!Array.isArray(data) || data.length < 1){
87 $("<p>No Logfiles found!</p>").appendTo("#logfilesForm");
88 console.log(data);
89 return;
90 }
91 if(("error" in data) && data["error"] == 1){
92 alert("Failed to upload map: "+ data["errormessage"]);
93 $("#mapTileUploadProgress").hide();
94 $("#mapFileInput").show();
95 return;
96 }
97 $("<select id=\"logfilesSelect\" name=\"logfilesSelected[]\" class=\"pure-input-1\" multiple></select>").appendTo("#logfilesForm");
98 $("<input type=\"submit\" class=\"pure-button pure-button-primary\" name=\"logfilesDownload\" value=\"Download\"/>").appendTo("#logfilesForm");
99 data.forEach(function(value, index){
100 $("<option value=\""+ value +"\">"+ value +"</option>").appendTo("#logfilesSelect");
101 });
102 });
103};
104/**
105 * @brief Sends a shutdown request to the webservice
106 */
107GnuBoat.shutdown = function()
108{
109 if(GnuBoat.private.serverBaseUrl == null){
110 GnuBoat.displayMessage("No server set/found");
111 return;
112 }
113 $.getJSON(GnuBoat.private.serverBaseUrl +"?request=shutdown", function(data){
114 var shutdownTime = data["shutdownstart"];
115 var shutdownDate = Date.parse(shutdownTime);
116 var currentDate = new Date();
117 var shutdownHint = "Shutting down in "+ Math.floor((shutdownDate - currentDate)/1000) +"s at "+ shutdownTime.toLocaleString();
118 if(shutdownTime == -1){
119 shutdownHint = "Failed to initiate shutdown: "+ data["errormessage"];
120 }
121 GnuBoat.displayMessage(shutdownHint);
122 });
123};
124
125/**
126 * @brief Uploads a map and refreshes the maps metadata on success
127 */
128GnuBoat.uploadMap = function(form)
129{
130 if(GnuBoat.private.serverBaseUrl == null){
131 displayMessage("No server set/found");
132 return;
133 }
134 $("#mapFileInput").hide();
135 $("#mapTileUploadProgress").show();
136 $.ajax({
137 type: 'POST',
138 url: GnuBoat.private.serverBaseUrl +'?request=map',
139 data: new FormData($("#mapTileUpload")[0]),
140 contentType: false,
141 processData: false,
142 success: function(data){
143 if(("error" in data) && data["error"] == 1){
144 alert("Failed to upload map: "+ data["errormessage"]);
145 $("#mapTileUploadProgress").hide();
146 $("#mapFileInput").show();
147 return;
148 }
149 alert("Map upload successfully");
150 $("#mapTileUploadProgress").hide();
151 $("#mapFileInput").show();
152 GnuBoat.getMapInfos();
153 },
154 error: function(jqXHR, exception, errorThrown){
155 alert("Failed to upload map (XHR): "+ exception);
156 $("#mapTileUploadProgress").hide();
157 $("#mapFileInput").show();
158 }
159 }).progress(function(e){
160 $("#mapTileUploadProgress").attr({value: e.oloaded, max: e.total});
161 });
162};
163
164/**
165 * @brief Setups up GnuBoat to be able to start() after configured a server with setServer().
166 */
167GnuBoat.initialize = function()
168{
169 $("#mapTileUploadProgress").hide();
170 $("#logfilesReload").click(GnuBoat.logfilesLoad);
171 $("#shutdownButton").click(GnuBoat.shutdown);
172
173 $("#mapTileUpload").validate({
174 rules: {
175 mapFile: {
176 required: true
177 },
178 mapName: {
179 required: true
180 }
181 },
182 submitHandler: function(form){
183 GnuBoat.uploadMap(form);
184 }
185 });
186
187 $("#logfilesForm").validate({
188 rules: {
189 logfilesSelect: {
190 required: true
191 },
192 }
193 });
194}
195
196/**
197 * @brief Starts querying the webservice
198 *
199 * Call initialize() and setServer() before start()
200 */
201GnuBoat.start = function()
202{
203 if(GnuBoat.private.serverBaseUrl == null){
204 GnuBoat.displayMessage("No server set/found");
205 return;
206 }
207
208 GnuBoat.getMapInfos();
209 GnuBoat.displayDataGet();
210 if(GnuBoat.private.timerDisplay == null)
211 GnuBoat.private.timerDisplay = setInterval(GnuBoat.displayDataGet, 10000);
212 GnuBoat.logfilesLoad();
213}
214
215/**
216 * @brief Stops querying the webservice
217 */
218GnuBoat.stop = function()
219{
220 if(GnuBoat.private.timerDisplay != null){
221 clearInterval(GnuBoat.private.timerDisplay);
222 GnuBoat.private.timerDisplay = null;
223 }
224}
225
226/**
227 * @brief Private methods and properties of GnuBoat
228 */
229GnuBoat.private = {
230 map: null,
231 mapLayerCurrent: null,
232 mapPolylines: [],
233 mapControl: null,
234 mapsMetadata: null,
235 dataMappings: {
236 speedthroughwater: {display: true, map: true, mapActive: false, titleLong: "Speed Through Water", titleShort: "STW", unit: "kts"},
237 speedoverground: {display: true, map: true, mapActive: false, titleLong: "Speed Over Ground", titleShort: "SOG", unit: "kts"},
238 waterdepth: {display: true, map: true, mapActive: true, titleLong: "Waterdepth", titleShort: "Depth", unit: "m"},
239 watertemperature: {display: true, map: true, mapActive: false, titleLong: "Watertemperature", titleShort: "Water", unit: "°C"},
240 gpsfix: {display: true, map: false, mapActive: false, titleLong: "GPS Fix", titleShort: "Fix", unit: ""},
241 },
242 serverBaseUrl: null,
243 timerDisplay: null,
244
245 openLink: function(target)
246 {
247 window.location=target;
248 },
249
250 displayDataSet: function(data)
251 {
252 var keysDisplay = [];
253 for(var key in GnuBoat.private.dataMappings){
254 if(GnuBoat.private.dataMappings[key]["display"] === true)
255 keysDisplay.push(key);
256 }
257 if(!Array.isArray(data) && !(data instanceof Object)){
258 console.log("No data array returned!");
259 console.log(data);
260 return;
261 }
262 if(!("lastvalid" in data)){
263 console.log("No last valid values given!");
264 }
265 else{
266 var lastValid = data["lastvalid"];
267 for(var i = 0; i < keysDisplay.length; i++){
268 var key = keysDisplay[i];
269 var value = lastValid[key];
270 if($.isNumeric(value)){
271 var text = value.toFixed(1);
272 if(key == "watertemperature"){
273 text = value.toFixed(0);
274 }
275 $("#display #"+ key +" #value").text(text);
276 }
277 else if(key == "gpsfix"){
278 $("#display #"+ key +" #value").text(value);
279 }
280 }
281 }
282
283 if(!("track" in data)){
284 console.log("No track given!");
285 }
286 else{
287 if(GnuBoat.private.map == null){
288 console.log("No map in use");
289 }
290 else{
291 var track = data["track"];
292 var maximas = [];
293 var minimas = [];
294 var points = [];
295
296 var keysMap = [];
297 for(var key in GnuBoat.private.dataMappings){
298 if(GnuBoat.private.dataMappings[key]["map"] === true)
299 keysMap.push(key);
300 }
301 for(var i = 0; i < keysMap.length; i++){
302 if(keysMap[i] == "gpsfix")
303 continue;
304 points[keysMap[i]] = [];
305 }
306
307 // getting maximas, minimums for normalization and the tracks themselves
308 for(var time in track){
309 for(var i = 0; i < keysMap.length; i++){
310 var key = keysMap[i];
311 if(key == "gpsfix")
312 continue;
313 if(!(key in maximas))
314 maximas[key] = track[time][key]
315 else if(maximas[key] < track[time][key])
316 maximas[key] = track[time][key];
317 if(!(key in minimas))
318 minimas[key] = track[time][key]
319 else if(minimas[key] > track[time][key])
320 minimas[key] = track[time][key];
321 points[key].push(new L.latLng(track[time]["latitude"], track[time]["longitude"], track[time][key]));
322 }
323 }
324 for(var i = 0; i < keysMap.length; i++){
325 var key = keysMap[i];
326 if(key == "gpsfix")
327 continue;
328 if(points[key].length > 0){
329 if(key in GnuBoat.private.mapPolylines){
330 GnuBoat.private.mapPolylines[key].setLatLngs(points[key]);
331 }
332 else{
333 GnuBoat.private.mapPolylines[key] = L.hotline(points[key], {weight: 3, outlineWidth: 0, min: minimas[key], max: maximas[key]});
334 if(GnuBoat.private.mapControl){
335 var name = GnuBoat.private.dataMappings[key]["titleLong"] +" in "+ GnuBoat.private.dataMappings[key]["unit"] +" ("+ GnuBoat.private.dataMappings[key]["titleShort"] +")";
336 GnuBoat.private.mapControl.addOverlay(GnuBoat.private.mapPolylines[key], name);
337 }
338 if(GnuBoat.private.dataMappings[key]["mapActive"] === true)
339 GnuBoat.private.mapPolylines[key].addTo(GnuBoat.private.map);
340 }
341 }
342 }
343 }
344 }
345 },
346
347 mapSetup: function ()
348 {
349 var mapMetadataIndex = $("#mapSelect").val();
350 if(GnuBoat.private.mapsMetadata == null){
351 console.log("No mapsMetadata set");
352 return;
353 }
354 if(mapMetadataIndex < 0 || mapMetadataIndex >= GnuBoat.private.mapsMetadata.length){
355 console.log("Map metadata is outside of range :"+ mapMetadataIndex.toString());
356 console.log(mapsMetadata);
357 return;
358 }
359 var mapMetadata = GnuBoat.private.mapsMetadata[mapMetadataIndex];
360
361 var latitudeTop = mapMetadata["bounds"][3];
362 var latitudeBottom = mapMetadata["bounds"][1];
363 var longitudeLeft = mapMetadata["bounds"][0];
364 var longitudeRight = mapMetadata["bounds"][2];
365
366 var mapZoomMin = mapMetadata["minzoom"];
367 var mapZoomMax = mapMetadata["maxzoom"];
368
369 var latitudeCenter = (latitudeTop - latitudeBottom)/2 + latitudeBottom;
370 var longitudeCenter = (longitudeLeft - longitudeRight)/2 + longitudeRight;
371 var mapZoomStart = (mapZoomMax - mapZoomMin)/2 + mapZoomMin;
372
373 var mapBounds = new L.LatLngBounds(
374 new L.LatLng(latitudeBottom, longitudeLeft),
375 new L.LatLng(latitudeTop, longitudeRight));
376
377 if(GnuBoat.private.map == null){
378 // only initialize the map (viewport) once
379 GnuBoat.private.map = L.map('mapViewport');
380 }
381 GnuBoat.private.map.setView([latitudeCenter, longitudeCenter], mapZoomStart);
382
383 if(GnuBoat.private.mapLayerCurrent != null){
384 GnuBoat.private.map.removeLayer(GnuBoat.private.mapLayerCurrent);
385 if(GnuBoat.private.mapControl)
386 GnuBoat.private.mapControl.removeLayer(GnuBoat.private.mapLayerCurrent);
387 GnuBoat.private.mapLayerCurrent = null;
388 }
389 GnuBoat.private.mapLayerCurrent = L.tileLayer(mapMetadata["tiles"][0], {
390 minZoom: mapZoomMin, maxZoom: mapZoomMax,
391 bounds: mapBounds,
392 attribution: mapMetadata["name"],
393 opacity: 0.85
394 }).addTo(GnuBoat.private.map);
395 if(GnuBoat.private.mapControl)
396 GnuBoat.private.mapControl.addBaseLayer(GnuBoat.private.mapLayerCurrent, "Map");
397 else{
398 GnuBoat.private.mapControl = L.control.layers({"Map": GnuBoat.private.mapLayerCurrent}, GnuBoat.private.mapOverlaysToList(), {hideSingleBase: true, sortLayers: true, }).addTo(GnuBoat.private.map);
399 }
400 },
401
402 mapInfos: function(data)
403 {
404 GnuBoat.private.mapsMetadata = data;
405
406 $("#mapSelect").empty();
407 var selected = "selected";
408 data.forEach(function(value, index){
409 $("<option value=\""+ index.toString() +"\" "+ selected +">"+ value["name"] +"</option>").appendTo("#mapSelect");
410 selected = "";
411 });
412
413 GnuBoat.private.mapSetup();
414 $("#mapSelect").change(function(){ mapSetup(); });
415 },
416
417 mapOverlaysToList: function()
418 {
419 var overlays = {};
420 for(var key in GnuBoat.private.mapPolylines){
421 overlays[key] = GnuBoat.private.mapPolylines[key];
422 }
423 return overlays;
424 },
425};
Note: See TracBrowser for help on using the repository browser.