1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
5 // Get the best-available objects for indexedDB and requestAnimationFrame.
6 window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
7 window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
10 var gAppInitDone = false;
11 var gUIHideCountdown = 0;
13 var gTrackUpdateInterval;
14 var gAction, gActionLabel;
15 var gOSMAPIURL = "http://api.openstreetmap.org/";
17 window.onload = function() {
18 gAction = document.getElementById("action");
19 gActionLabel = document.getElementById("actionlabel");
21 var mSel = document.getElementById("mapSelector");
22 for (var mapStyle in gMapStyles) {
23 var opt = document.createElement("option");
25 opt.text = gMapStyles[mapStyle].name;
29 var areas = document.getElementsByClassName("overlayArea");
30 for (var i = 0; i <= areas.length - 1; i++) {
31 areas[i].addEventListener("mouseup", uiEvHandler, false);
32 areas[i].addEventListener("mousemove", uiEvHandler, false);
33 areas[i].addEventListener("mousedown", uiEvHandler, false);
34 areas[i].addEventListener("mouseout", uiEvHandler, false);
36 areas[i].addEventListener("touchstart", uiEvHandler, false);
37 areas[i].addEventListener("touchmove", uiEvHandler, false);
38 areas[i].addEventListener("touchend", uiEvHandler, false);
39 areas[i].addEventListener("touchcancel", uiEvHandler, false);
40 areas[i].addEventListener("touchleave", uiEvHandler, false);
43 document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
45 if (navigator.platform.length == "") {
46 // For Firefox OS, don't display the "save" button.
47 // Do this by setting the debugHide class for testing in debug mode.
48 document.getElementById("saveTrackButton").classList.add("debugHide");
51 // Without OAuth, the login data is useless
52 //document.getElementById("uploadSettingsArea").classList.remove("debugHide");
53 // As login data is useless for now, always enable upload button
54 document.getElementById("uploadTrackButton").disabled = false;
57 // Note that GPX upload returns an error 500 on the dev API right now.
58 gOSMAPIURL = "http://api06.dev.openstreetmap.org/";
61 gAction.addEventListener("dbinit-done", initMap, false);
62 gAction.addEventListener("mapinit-done", postInit, false);
63 console.log("starting DB init...");
67 function postInit(aEvent) {
68 gAction.removeEventListener(aEvent.type, postInit, false);
69 console.log("init done, draw map.");
70 gMapPrefsLoaded = true;
72 //gMap.resizeAndDraw(); <-- HACK: This triggers bug 1001853, work around with a delay.
73 window.setTimeout(gMap.resizeAndDraw, 100);
74 gActionLabel.textContent = "";
75 gAction.style.display = "none";
76 setTracking(document.getElementById("trackCheckbox"));
77 gPrefs.get(gDebug ? "osm_dev_user" : "osm_user", function(aValue) {
79 document.getElementById("uploadUser").value = aValue;
80 document.getElementById("uploadTrackButton").disabled = false;
83 gPrefs.get(gDebug ? "osm_dev_pwd" : "osm_pwd", function(aValue) {
84 var upwd = document.getElementById("uploadPwd");
86 document.getElementById("uploadPwd").value = aValue;
90 window.onresize = function() {
94 function initDB(aEvent) {
97 gAction.removeEventListener(aEvent.type, initDB, false);
98 var request = window.indexedDB.open("MainDB-lantea", 2);
99 request.onerror = function(event) {
100 // Errors can be handled here. Error codes explain in:
101 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
103 console.log("error opening mainDB: " + event.target.errorCode);
105 request.onsuccess = function(event) {
106 mainDB = request.result;
107 var throwEv = new CustomEvent("dbinit-done");
108 gAction.dispatchEvent(throwEv);
110 request.onupgradeneeded = function(event) {
111 mainDB = request.result;
112 var ver = mainDB.version || 0; // version is empty string for a new DB
114 console.log("mainDB has version " + ver + ", upgrade needed.");
115 if (!mainDB.objectStoreNames.contains("prefs")) {
116 // Create a "prefs" objectStore.
117 var prefsStore = mainDB.createObjectStore("prefs");
119 if (!mainDB.objectStoreNames.contains("track")) {
120 // Create a "track" objectStore.
121 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
123 if (!mainDB.objectStoreNames.contains("tilecache")) {
124 // Create a "tilecache" objectStore.
125 var tilecacheStore = mainDB.createObjectStore("tilecache");
127 mainDB.onversionchange = function(event) {
136 if (gUIHideCountdown <= 0) {
137 var areas = document.getElementsByClassName('overlayArea');
138 for (var i = 0; i <= areas.length - 1; i++) {
139 areas[i].classList.remove("hidden");
141 setTimeout(maybeHideUI, 1000);
143 gUIHideCountdown = 5;
146 function maybeHideUI() {
148 if (gUIHideCountdown <= 0) {
149 var areas = document.getElementsByClassName('overlayArea');
150 for (var i = 0; i <= areas.length - 1; i++) {
151 areas[i].classList.add("hidden");
155 setTimeout(maybeHideUI, 1000);
159 function updateTrackInfo() {
160 document.getElementById("trackLengthNum").textContent = calcTrackLength().toFixed(1);
161 var duration = calcTrackDuration();
162 var durationM = Math.round(duration/60);
163 var durationH = Math.floor(durationM/60); durationM = durationM - durationH * 60;
164 document.getElementById("trackDurationH").style.display = durationH ? "inline" : "none";
165 document.getElementById("trackDurationHNum").textContent = durationH;
166 document.getElementById("trackDurationMNum").textContent = durationM;
169 function toggleTrackArea() {
170 var fs = document.getElementById("trackArea");
171 if (fs.classList.contains("hidden")) {
172 fs.classList.remove("hidden");
174 gTrackUpdateInterval = setInterval(updateTrackInfo, 1000);
177 clearInterval(gTrackUpdateInterval);
178 fs.classList.add("hidden");
182 function toggleSettings() {
183 var fs = document.getElementById("settingsArea");
184 if (fs.classList.contains("hidden")) {
185 fs.classList.remove("hidden");
189 fs.classList.add("hidden");
193 function toggleFullscreen() {
194 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
195 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
196 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
197 if (document.cancelFullScreen) {
198 document.cancelFullScreen();
199 } else if (document.mozCancelFullScreen) {
200 document.mozCancelFullScreen();
201 } else if (document.webkitCancelFullScreen) {
202 document.webkitCancelFullScreen();
206 var elem = document.getElementById("body");
207 if (elem.requestFullScreen) {
208 elem.requestFullScreen();
209 } else if (elem.mozRequestFullScreen) {
210 elem.mozRequestFullScreen();
211 } else if (elem.webkitRequestFullScreen) {
212 elem.webkitRequestFullScreen();
217 function showUploadDialog() {
218 var dia = document.getElementById("dialogArea");
219 var areas = dia.children;
220 for (var i = 0; i <= areas.length - 1; i++) {
221 areas[i].style.display = "none";
223 document.getElementById("uploadDialog").style.display = "block";
224 document.getElementById("uploadTrackButton").disabled = true;
225 dia.classList.remove("hidden");
228 function showGLWarningDialog() {
229 var dia = document.getElementById("dialogArea");
230 var areas = dia.children;
231 for (var i = 0; i <= areas.length - 1; i++) {
232 areas[i].style.display = "none";
234 document.getElementById("noGLwarning").style.display = "block";
235 dia.classList.remove("hidden");
238 function cancelDialog() {
239 document.getElementById("dialogArea").classList.add("hidden");
240 document.getElementById("uploadTrackButton").disabled = false;
244 handleEvent: function(aEvent) {
245 var touchEvent = aEvent.type.indexOf('touch') != -1;
247 switch (aEvent.type) {
261 function setUploadField(aField) {
264 gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
265 document.getElementById("uploadTrackButton").disabled = !aField.value.length;
268 gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
273 function makeISOString(aTimestamp) {
274 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
275 var tsDate = new Date(aTimestamp);
276 // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
277 return tsDate.getUTCFullYear() + "-" +
278 (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
279 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
280 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
281 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
282 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
285 function convertTrack(aTargetFormat) {
287 switch (aTargetFormat) {
289 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
290 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
292 out += ' <trk>' + "\n";
293 out += ' <trkseg>' + "\n";
294 for (var i = 0; i < gTrack.length; i++) {
295 if (gTrack[i].beginSegment && i > 0) {
296 out += ' </trkseg>' + "\n";
297 out += ' <trkseg>' + "\n";
299 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
300 gTrack[i].coords.longitude + '">' + "\n";
301 if (gTrack[i].coords.altitude) {
302 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
304 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
305 out += ' </trkpt>' + "\n";
307 out += ' </trkseg>' + "\n";
308 out += ' </trk>' + "\n";
310 out += '</gpx>' + "\n";
313 out = JSON.stringify(gTrack);
321 function saveTrack() {
323 var outDataURI = "data:application/gpx+xml," +
324 encodeURIComponent(convertTrack("gpx"));
325 window.open(outDataURI, 'GPX Track');
329 function saveTrackDump() {
331 var outDataURI = "data:application/json," +
332 encodeURIComponent(convertTrack("json"));
333 window.open(outDataURI, 'JSON dump');
337 function uploadTrack() {
338 // Hide all areas in the dialog.
339 var dia = document.getElementById("dialogArea");
340 var areas = dia.children;
341 for (var i = 0; i <= areas.length - 1; i++) {
342 areas[i].style.display = "none";
344 // Reset all the fields in the status area.
345 document.getElementById("uploadStatusCloseButton").disabled = true;
346 document.getElementById("uploadInProgress").style.display = "block";
347 document.getElementById("uploadSuccess").style.display = "none";
348 document.getElementById("uploadFailed").style.display = "none";
349 document.getElementById("uploadError").style.display = "none";
350 document.getElementById("uploadErrorMsg").textContent = "";
351 // Now show the status area.
352 document.getElementById("uploadStatus").style.display = "block";
354 // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
355 var trackBlob = new Blob([convertTrack("gpx")],
356 { "type" : "application/gpx+xml" });
357 var formData = new FormData();
358 formData.append("file", trackBlob);
359 var desc = document.getElementById("uploadDesc").value;
360 formData.append("description",
361 desc.length ? desc : "Track recorded via Lantea Maps");
362 //formData.append("tags", "");
363 formData.append("visibility",
364 document.getElementById("uploadVisibility").value);
365 // Do an empty POST request first, so that we don't send everything,
366 // then ask for credentials, and then send again.
367 var hXHR = new XMLHttpRequest();
368 hXHR.onreadystatechange = function() {
369 if (hXHR.readyState == 4 && (hXHR.status == 200 || hXHR.status == 400)) {
370 // 400 is Bad Request, but that's expected as this was empty.
371 // So far so good, init actual upload.
372 var XHR = new XMLHttpRequest();
373 XHR.onreadystatechange = function() {
374 if (XHR.readyState == 4 && XHR.status == 200) {
375 // Everthing looks fine.
376 reportUploadStatus(true);
377 } else if (XHR.readyState == 4 && XHR.status != 200) {
378 // Fetched the wrong page or network error...
379 reportUploadStatus(false);
382 XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
383 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
384 // So, we'll ask the user for entering credentials with rather ugly UI.
385 XHR.withCredentials = true;
387 XHR.send(formData); // Send actual form data.
390 reportUploadStatus(false, e);
392 } else if (hXHR.readyState == 4 && hXHR.status != 200) {
393 // Fetched the wrong page or network error...
394 reportUploadStatus(false);
397 hXHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
398 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
399 // So, we'll ask the user for entering credentials with rather ugly UI.
400 hXHR.withCredentials = true;
402 hXHR.send(); // Empty request, see above.
405 reportUploadStatus(false, e);
409 function reportUploadStatus(aSuccess, aMessage) {
410 document.getElementById("uploadStatusCloseButton").disabled = false;
411 document.getElementById("uploadInProgress").style.display = "none";
413 document.getElementById("uploadSuccess").style.display = "block";
416 document.getElementById("uploadErrorMsg").textContent = aMessage;
417 document.getElementById("uploadError").style.display = "block";
420 document.getElementById("uploadFailed").style.display = "block";
427 get: function(aKey, aCallback) {
430 var transaction = mainDB.transaction([this.objStore]);
431 var request = transaction.objectStore(this.objStore).get(aKey);
432 request.onsuccess = function(event) {
433 aCallback(request.result, event);
435 request.onerror = function(event) {
436 // Errors can be handled here.
437 aCallback(undefined, event);
441 set: function(aKey, aValue, aCallback) {
445 var transaction = mainDB.transaction([this.objStore], "readwrite");
446 var objStore = transaction.objectStore(this.objStore);
447 var request = objStore.put(aValue, aKey);
448 request.onsuccess = function(event) {
451 aCallback(success, event);
453 request.onerror = function(event) {
454 // Errors can be handled here.
456 aCallback(success, event);
460 unset: function(aKey, aCallback) {
464 var transaction = mainDB.transaction([this.objStore], "readwrite");
465 var request = transaction.objectStore(this.objStore).delete(aKey);
466 request.onsuccess = function(event) {
469 aCallback(success, event);
471 request.onerror = function(event) {
472 // Errors can be handled here.
474 aCallback(success, event);
482 getList: function(aCallback) {
485 var transaction = mainDB.transaction([this.objStore]);
486 var objStore = transaction.objectStore(this.objStore);
487 if (objStore.getAll) { // currently Mozilla-specific
488 objStore.getAll().onsuccess = function(event) {
489 aCallback(event.target.result);
492 else { // Use cursor (standard method).
494 objStore.openCursor().onsuccess = function(event) {
495 var cursor = event.target.result;
497 tPoints.push(cursor.value);
507 getListStepped: function(aCallback) {
510 var transaction = mainDB.transaction([this.objStore]);
511 var objStore = transaction.objectStore(this.objStore);
512 // Use cursor in reverse direction (so we get the most recent position first)
513 objStore.openCursor(null, "prev").onsuccess = function(event) {
514 var cursor = event.target.result;
516 aCallback(cursor.value);
525 push: function(aValue, aCallback) {
528 var transaction = mainDB.transaction([this.objStore], "readwrite");
529 var objStore = transaction.objectStore(this.objStore);
530 var request = objStore.add(aValue);
531 request.onsuccess = function(event) {
533 aCallback(request.result, event);
535 request.onerror = function(event) {
536 // Errors can be handled here.
538 aCallback(false, event);
542 clear: function(aCallback) {
546 var transaction = mainDB.transaction([this.objStore], "readwrite");
547 var request = transaction.objectStore(this.objStore).clear();
548 request.onsuccess = function(event) {
551 aCallback(success, event);
553 request.onerror = function(event) {
554 // Errors can be handled here.
556 aCallback(success, event);