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 gUIHideCountdown = 0;
12 var gAction, gActionLabel;
13 var gOSMAPIURL = "http://api.openstreetmap.org/";
15 window.onload = function() {
16 gAction = document.getElementById("action");
17 gActionLabel = document.getElementById("actionlabel");
19 var mSel = document.getElementById("mapSelector");
20 for (var mapStyle in gMapStyles) {
21 var opt = document.createElement("option");
23 opt.text = gMapStyles[mapStyle].name;
27 var areas = document.getElementsByClassName("overlayArea");
28 for (var i = 0; i <= areas.length - 1; i++) {
29 areas[i].addEventListener("mouseup", uiEvHandler, false);
30 areas[i].addEventListener("mousemove", uiEvHandler, false);
31 areas[i].addEventListener("mousedown", uiEvHandler, false);
32 areas[i].addEventListener("mouseout", uiEvHandler, false);
34 areas[i].addEventListener("touchstart", uiEvHandler, false);
35 areas[i].addEventListener("touchmove", uiEvHandler, false);
36 areas[i].addEventListener("touchend", uiEvHandler, false);
37 areas[i].addEventListener("touchcancel", uiEvHandler, false);
38 areas[i].addEventListener("touchleave", uiEvHandler, false);
41 document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
43 if (navigator.platform.length == "") {
44 // For Firefox OS, don't display the "save" button.
45 // Do this by setting the debugHide class for testing in debug mode.
46 document.getElementById("saveTrackButton").classList.add("debugHide");
49 // Without OAuth, the login data is useless
50 //document.getElementById("uploadSettingsArea").classList.remove("debugHide");
51 // As login data is useless for now, always enable upload button
52 document.getElementById("uploadTrackButton").disabled = false;
55 // Note that GPX upload returns an error 500 on the dev API right now.
56 gOSMAPIURL = "http://api06.dev.openstreetmap.org/";
59 gAction.addEventListener("dbinit-done", initMap, false);
60 gAction.addEventListener("mapinit-done", postInit, false);
61 console.log("starting DB init...");
65 function postInit(aEvent) {
66 gAction.removeEventListener(aEvent.type, postInit, false);
67 console.log("init done, draw map.");
68 gMapPrefsLoaded = true;
69 //gMap.resizeAndDraw(); <-- HACK: This triggers bug 1001853, work around with a delay.
70 window.setTimeout(gMap.resizeAndDraw, 100);
71 gActionLabel.textContent = "";
72 gAction.style.display = "none";
73 setTracking(document.getElementById("trackCheckbox"));
74 gPrefs.get(gDebug ? "osm_dev_user" : "osm_user", function(aValue) {
76 document.getElementById("uploadUser").value = aValue;
77 document.getElementById("uploadTrackButton").disabled = false;
80 gPrefs.get(gDebug ? "osm_dev_pwd" : "osm_pwd", function(aValue) {
81 var upwd = document.getElementById("uploadPwd");
83 document.getElementById("uploadPwd").value = aValue;
87 window.onresize = function() {
91 function initDB(aEvent) {
94 gAction.removeEventListener(aEvent.type, initDB, false);
95 var request = window.indexedDB.open("MainDB-lantea", 2);
96 request.onerror = function(event) {
97 // Errors can be handled here. Error codes explain in:
98 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
100 console.log("error opening mainDB: " + event.target.errorCode);
102 request.onsuccess = function(event) {
103 mainDB = request.result;
104 var throwEv = new CustomEvent("dbinit-done");
105 gAction.dispatchEvent(throwEv);
107 request.onupgradeneeded = function(event) {
108 mainDB = request.result;
109 var ver = mainDB.version || 0; // version is empty string for a new DB
111 console.log("mainDB has version " + ver + ", upgrade needed.");
112 if (!mainDB.objectStoreNames.contains("prefs")) {
113 // Create a "prefs" objectStore.
114 var prefsStore = mainDB.createObjectStore("prefs");
116 if (!mainDB.objectStoreNames.contains("track")) {
117 // Create a "track" objectStore.
118 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
120 if (!mainDB.objectStoreNames.contains("tilecache")) {
121 // Create a "tilecache" objectStore.
122 var tilecacheStore = mainDB.createObjectStore("tilecache");
124 mainDB.onversionchange = function(event) {
133 if (gUIHideCountdown <= 0) {
134 var areas = document.getElementsByClassName('overlayArea');
135 for (var i = 0; i <= areas.length - 1; i++) {
136 areas[i].classList.remove("hidden");
138 setTimeout(maybeHideUI, 1000);
140 gUIHideCountdown = 5;
143 function maybeHideUI() {
145 if (gUIHideCountdown <= 0) {
146 var areas = document.getElementsByClassName('overlayArea');
147 for (var i = 0; i <= areas.length - 1; i++) {
148 areas[i].classList.add("hidden");
152 setTimeout(maybeHideUI, 1000);
156 function toggleTrackArea() {
157 var fs = document.getElementById("trackArea");
158 if (fs.style.display != "block") {
159 fs.style.display = "block";
163 fs.style.display = "none";
167 function toggleSettings() {
168 var fs = document.getElementById("settingsArea");
169 if (fs.style.display != "block") {
170 fs.style.display = "block";
174 fs.style.display = "none";
178 function toggleFullscreen() {
179 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
180 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
181 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
182 if (document.cancelFullScreen) {
183 document.cancelFullScreen();
184 } else if (document.mozCancelFullScreen) {
185 document.mozCancelFullScreen();
186 } else if (document.webkitCancelFullScreen) {
187 document.webkitCancelFullScreen();
191 var elem = document.getElementById("body");
192 if (elem.requestFullScreen) {
193 elem.requestFullScreen();
194 } else if (elem.mozRequestFullScreen) {
195 elem.mozRequestFullScreen();
196 } else if (elem.webkitRequestFullScreen) {
197 elem.webkitRequestFullScreen();
202 function showUploadDialog() {
203 var dia = document.getElementById("dialogArea");
204 var areas = dia.children;
205 for (var i = 0; i <= areas.length - 1; i++) {
206 areas[i].style.display = "none";
208 document.getElementById("uploadDialog").style.display = "block";
209 document.getElementById("uploadTrackButton").disabled = true;
210 dia.classList.remove("hidden");
213 function showGLWarningDialog() {
214 var dia = document.getElementById("dialogArea");
215 var areas = dia.children;
216 for (var i = 0; i <= areas.length - 1; i++) {
217 areas[i].style.display = "none";
219 document.getElementById("noGLwarning").style.display = "block";
220 dia.classList.remove("hidden");
223 function cancelDialog() {
224 document.getElementById("dialogArea").classList.add("hidden");
225 document.getElementById("uploadTrackButton").disabled = false;
229 handleEvent: function(aEvent) {
230 var touchEvent = aEvent.type.indexOf('touch') != -1;
232 switch (aEvent.type) {
246 function setUploadField(aField) {
249 gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
250 document.getElementById("uploadTrackButton").disabled = !aField.value.length;
253 gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
258 function makeISOString(aTimestamp) {
259 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
260 var tsDate = new Date(aTimestamp);
261 // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
262 return tsDate.getUTCFullYear() + "-" +
263 (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
264 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
265 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
266 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
267 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
270 function convertTrack(aTargetFormat) {
272 switch (aTargetFormat) {
274 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
275 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
277 out += ' <trk>' + "\n";
278 out += ' <trkseg>' + "\n";
279 for (var i = 0; i < gTrack.length; i++) {
280 if (gTrack[i].beginSegment && i > 0) {
281 out += ' </trkseg>' + "\n";
282 out += ' <trkseg>' + "\n";
284 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
285 gTrack[i].coords.longitude + '">' + "\n";
286 if (gTrack[i].coords.altitude) {
287 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
289 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
290 out += ' </trkpt>' + "\n";
292 out += ' </trkseg>' + "\n";
293 out += ' </trk>' + "\n";
295 out += '</gpx>' + "\n";
298 out = JSON.stringify(gTrack);
306 function saveTrack() {
308 var outDataURI = "data:application/gpx+xml," +
309 encodeURIComponent(convertTrack("gpx"));
310 window.open(outDataURI, 'GPX Track');
314 function saveTrackDump() {
316 var outDataURI = "data:application/json," +
317 encodeURIComponent(convertTrack("json"));
318 window.open(outDataURI, 'JSON dump');
322 function uploadTrack() {
323 // Hide all areas in the dialog.
324 var dia = document.getElementById("dialogArea");
325 var areas = dia.children;
326 for (var i = 0; i <= areas.length - 1; i++) {
327 areas[i].style.display = "none";
329 // Reset all the fields in the status area.
330 document.getElementById("uploadStatusCloseButton").disabled = true;
331 document.getElementById("uploadInProgress").style.display = "block";
332 document.getElementById("uploadSuccess").style.display = "none";
333 document.getElementById("uploadFailed").style.display = "none";
334 document.getElementById("uploadError").style.display = "none";
335 document.getElementById("uploadErrorMsg").textContent = "";
336 // Now show the status area.
337 document.getElementById("uploadStatus").style.display = "block";
339 // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
340 var trackBlob = new Blob([convertTrack("gpx")],
341 { "type" : "application/gpx+xml" });
342 var formData = new FormData();
343 formData.append("file", trackBlob);
344 var desc = document.getElementById("uploadDesc").value;
345 formData.append("description",
346 desc.length ? desc : "Track recorded via Lantea Maps");
347 //formData.append("tags", "");
348 formData.append("visibility",
349 document.getElementById("uploadVisibility").value);
350 // Do an empty POST request first, so that we don't send everything,
351 // then ask for credentials, and then send again.
352 var hXHR = new XMLHttpRequest();
353 hXHR.onreadystatechange = function() {
354 if (hXHR.readyState == 4 && (hXHR.status == 200 || hXHR.status == 400)) {
355 // 400 is Bad Request, but that's expected as this was empty.
356 // So far so good, init actual upload.
357 var XHR = new XMLHttpRequest();
358 XHR.onreadystatechange = function() {
359 if (XHR.readyState == 4 && XHR.status == 200) {
360 // Everthing looks fine.
361 reportUploadStatus(true);
362 } else if (XHR.readyState == 4 && XHR.status != 200) {
363 // Fetched the wrong page or network error...
364 reportUploadStatus(false);
367 XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
368 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
369 // So, we'll ask the user for entering credentials with rather ugly UI.
370 XHR.withCredentials = true;
372 XHR.send(formData); // Send actual form data.
375 reportUploadStatus(false, e);
377 } else if (hXHR.readyState == 4 && hXHR.status != 200) {
378 // Fetched the wrong page or network error...
379 reportUploadStatus(false);
382 hXHR.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 hXHR.withCredentials = true;
387 hXHR.send(); // Empty request, see above.
390 reportUploadStatus(false, e);
394 function reportUploadStatus(aSuccess, aMessage) {
395 document.getElementById("uploadStatusCloseButton").disabled = false;
396 document.getElementById("uploadInProgress").style.display = "none";
398 document.getElementById("uploadSuccess").style.display = "block";
401 document.getElementById("uploadErrorMsg").textContent = aMessage;
402 document.getElementById("uploadError").style.display = "block";
405 document.getElementById("uploadFailed").style.display = "block";
412 get: function(aKey, aCallback) {
415 var transaction = mainDB.transaction([this.objStore]);
416 var request = transaction.objectStore(this.objStore).get(aKey);
417 request.onsuccess = function(event) {
418 aCallback(request.result, event);
420 request.onerror = function(event) {
421 // Errors can be handled here.
422 aCallback(undefined, event);
426 set: function(aKey, aValue, aCallback) {
430 var transaction = mainDB.transaction([this.objStore], "readwrite");
431 var objStore = transaction.objectStore(this.objStore);
432 var request = objStore.put(aValue, aKey);
433 request.onsuccess = function(event) {
436 aCallback(success, event);
438 request.onerror = function(event) {
439 // Errors can be handled here.
441 aCallback(success, event);
445 unset: function(aKey, aCallback) {
449 var transaction = mainDB.transaction([this.objStore], "readwrite");
450 var request = transaction.objectStore(this.objStore).delete(aKey);
451 request.onsuccess = function(event) {
454 aCallback(success, event);
456 request.onerror = function(event) {
457 // Errors can be handled here.
459 aCallback(success, event);
467 getList: function(aCallback) {
470 var transaction = mainDB.transaction([this.objStore]);
471 var objStore = transaction.objectStore(this.objStore);
472 if (objStore.getAll) { // currently Mozilla-specific
473 objStore.getAll().onsuccess = function(event) {
474 aCallback(event.target.result);
477 else { // Use cursor (standard method).
479 objStore.openCursor().onsuccess = function(event) {
480 var cursor = event.target.result;
482 tPoints.push(cursor.value);
492 getListStepped: function(aCallback) {
495 var transaction = mainDB.transaction([this.objStore]);
496 var objStore = transaction.objectStore(this.objStore);
497 // Use cursor in reverse direction (so we get the most recent position first)
498 objStore.openCursor(null, "prev").onsuccess = function(event) {
499 var cursor = event.target.result;
501 aCallback(cursor.value);
510 push: function(aValue, aCallback) {
513 var transaction = mainDB.transaction([this.objStore], "readwrite");
514 var objStore = transaction.objectStore(this.objStore);
515 var request = objStore.add(aValue);
516 request.onsuccess = function(event) {
518 aCallback(request.result, event);
520 request.onerror = function(event) {
521 // Errors can be handled here.
523 aCallback(false, event);
527 clear: function(aCallback) {
531 var transaction = mainDB.transaction([this.objStore], "readwrite");
532 var request = transaction.objectStore(this.objStore).clear();
533 request.onsuccess = function(event) {
536 aCallback(success, event);
538 request.onerror = function(event) {
539 // Errors can be handled here.
541 aCallback(success, event);