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 gAction, gActionLabel;
14 var gOSMAPIURL = "http://api.openstreetmap.org/";
16 window.onload = function() {
17 gAction = document.getElementById("action");
18 gActionLabel = document.getElementById("actionlabel");
20 var mSel = document.getElementById("mapSelector");
21 for (var mapStyle in gMapStyles) {
22 var opt = document.createElement("option");
24 opt.text = gMapStyles[mapStyle].name;
28 var areas = document.getElementsByClassName("overlayArea");
29 for (var i = 0; i <= areas.length - 1; i++) {
30 areas[i].addEventListener("mouseup", uiEvHandler, false);
31 areas[i].addEventListener("mousemove", uiEvHandler, false);
32 areas[i].addEventListener("mousedown", uiEvHandler, false);
33 areas[i].addEventListener("mouseout", uiEvHandler, false);
35 areas[i].addEventListener("touchstart", uiEvHandler, false);
36 areas[i].addEventListener("touchmove", uiEvHandler, false);
37 areas[i].addEventListener("touchend", uiEvHandler, false);
38 areas[i].addEventListener("touchcancel", uiEvHandler, false);
39 areas[i].addEventListener("touchleave", uiEvHandler, false);
42 document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
44 if (navigator.platform.length == "") {
45 // For Firefox OS, don't display the "save" button.
46 // Do this by setting the debugHide class for testing in debug mode.
47 document.getElementById("saveTrackButton").classList.add("debugHide");
50 // Without OAuth, the login data is useless
51 //document.getElementById("uploadSettingsArea").classList.remove("debugHide");
52 // As login data is useless for now, always enable upload button
53 document.getElementById("uploadTrackButton").disabled = false;
56 // Note that GPX upload returns an error 500 on the dev API right now.
57 gOSMAPIURL = "http://api06.dev.openstreetmap.org/";
60 gAction.addEventListener("dbinit-done", initMap, false);
61 gAction.addEventListener("mapinit-done", postInit, false);
62 console.log("starting DB init...");
66 function postInit(aEvent) {
67 gAction.removeEventListener(aEvent.type, postInit, false);
68 console.log("init done, draw map.");
69 gMapPrefsLoaded = true;
71 //gMap.resizeAndDraw(); <-- HACK: This triggers bug 1001853, work around with a delay.
72 window.setTimeout(gMap.resizeAndDraw, 100);
73 gActionLabel.textContent = "";
74 gAction.style.display = "none";
75 setTracking(document.getElementById("trackCheckbox"));
76 gPrefs.get(gDebug ? "osm_dev_user" : "osm_user", function(aValue) {
78 document.getElementById("uploadUser").value = aValue;
79 document.getElementById("uploadTrackButton").disabled = false;
82 gPrefs.get(gDebug ? "osm_dev_pwd" : "osm_pwd", function(aValue) {
83 var upwd = document.getElementById("uploadPwd");
85 document.getElementById("uploadPwd").value = aValue;
89 window.onresize = function() {
93 function initDB(aEvent) {
96 gAction.removeEventListener(aEvent.type, initDB, false);
97 var request = window.indexedDB.open("MainDB-lantea", 2);
98 request.onerror = function(event) {
99 // Errors can be handled here. Error codes explain in:
100 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
102 console.log("error opening mainDB: " + event.target.errorCode);
104 request.onsuccess = function(event) {
105 mainDB = request.result;
106 var throwEv = new CustomEvent("dbinit-done");
107 gAction.dispatchEvent(throwEv);
109 request.onupgradeneeded = function(event) {
110 mainDB = request.result;
111 var ver = mainDB.version || 0; // version is empty string for a new DB
113 console.log("mainDB has version " + ver + ", upgrade needed.");
114 if (!mainDB.objectStoreNames.contains("prefs")) {
115 // Create a "prefs" objectStore.
116 var prefsStore = mainDB.createObjectStore("prefs");
118 if (!mainDB.objectStoreNames.contains("track")) {
119 // Create a "track" objectStore.
120 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
122 if (!mainDB.objectStoreNames.contains("tilecache")) {
123 // Create a "tilecache" objectStore.
124 var tilecacheStore = mainDB.createObjectStore("tilecache");
126 mainDB.onversionchange = function(event) {
135 if (gUIHideCountdown <= 0) {
136 var areas = document.getElementsByClassName('overlayArea');
137 for (var i = 0; i <= areas.length - 1; i++) {
138 areas[i].classList.remove("hidden");
140 setTimeout(maybeHideUI, 1000);
142 gUIHideCountdown = 5;
145 function maybeHideUI() {
147 if (gUIHideCountdown <= 0) {
148 var areas = document.getElementsByClassName('overlayArea');
149 for (var i = 0; i <= areas.length - 1; i++) {
150 areas[i].classList.add("hidden");
154 setTimeout(maybeHideUI, 1000);
158 function toggleTrackArea() {
159 var fs = document.getElementById("trackArea");
160 if (fs.style.display != "block") {
161 fs.style.display = "block";
165 fs.style.display = "none";
169 function toggleSettings() {
170 var fs = document.getElementById("settingsArea");
171 if (fs.style.display != "block") {
172 fs.style.display = "block";
176 fs.style.display = "none";
180 function toggleFullscreen() {
181 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
182 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
183 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
184 if (document.cancelFullScreen) {
185 document.cancelFullScreen();
186 } else if (document.mozCancelFullScreen) {
187 document.mozCancelFullScreen();
188 } else if (document.webkitCancelFullScreen) {
189 document.webkitCancelFullScreen();
193 var elem = document.getElementById("body");
194 if (elem.requestFullScreen) {
195 elem.requestFullScreen();
196 } else if (elem.mozRequestFullScreen) {
197 elem.mozRequestFullScreen();
198 } else if (elem.webkitRequestFullScreen) {
199 elem.webkitRequestFullScreen();
204 function showUploadDialog() {
205 var dia = document.getElementById("dialogArea");
206 var areas = dia.children;
207 for (var i = 0; i <= areas.length - 1; i++) {
208 areas[i].style.display = "none";
210 document.getElementById("uploadDialog").style.display = "block";
211 document.getElementById("uploadTrackButton").disabled = true;
212 dia.classList.remove("hidden");
215 function showGLWarningDialog() {
216 var dia = document.getElementById("dialogArea");
217 var areas = dia.children;
218 for (var i = 0; i <= areas.length - 1; i++) {
219 areas[i].style.display = "none";
221 document.getElementById("noGLwarning").style.display = "block";
222 dia.classList.remove("hidden");
225 function cancelDialog() {
226 document.getElementById("dialogArea").classList.add("hidden");
227 document.getElementById("uploadTrackButton").disabled = false;
231 handleEvent: function(aEvent) {
232 var touchEvent = aEvent.type.indexOf('touch') != -1;
234 switch (aEvent.type) {
248 function setUploadField(aField) {
251 gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
252 document.getElementById("uploadTrackButton").disabled = !aField.value.length;
255 gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
260 function makeISOString(aTimestamp) {
261 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
262 var tsDate = new Date(aTimestamp);
263 // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
264 return tsDate.getUTCFullYear() + "-" +
265 (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
266 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
267 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
268 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
269 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
272 function convertTrack(aTargetFormat) {
274 switch (aTargetFormat) {
276 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
277 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
279 out += ' <trk>' + "\n";
280 out += ' <trkseg>' + "\n";
281 for (var i = 0; i < gTrack.length; i++) {
282 if (gTrack[i].beginSegment && i > 0) {
283 out += ' </trkseg>' + "\n";
284 out += ' <trkseg>' + "\n";
286 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
287 gTrack[i].coords.longitude + '">' + "\n";
288 if (gTrack[i].coords.altitude) {
289 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
291 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
292 out += ' </trkpt>' + "\n";
294 out += ' </trkseg>' + "\n";
295 out += ' </trk>' + "\n";
297 out += '</gpx>' + "\n";
300 out = JSON.stringify(gTrack);
308 function saveTrack() {
310 var outDataURI = "data:application/gpx+xml," +
311 encodeURIComponent(convertTrack("gpx"));
312 window.open(outDataURI, 'GPX Track');
316 function saveTrackDump() {
318 var outDataURI = "data:application/json," +
319 encodeURIComponent(convertTrack("json"));
320 window.open(outDataURI, 'JSON dump');
324 function uploadTrack() {
325 // Hide all areas in the dialog.
326 var dia = document.getElementById("dialogArea");
327 var areas = dia.children;
328 for (var i = 0; i <= areas.length - 1; i++) {
329 areas[i].style.display = "none";
331 // Reset all the fields in the status area.
332 document.getElementById("uploadStatusCloseButton").disabled = true;
333 document.getElementById("uploadInProgress").style.display = "block";
334 document.getElementById("uploadSuccess").style.display = "none";
335 document.getElementById("uploadFailed").style.display = "none";
336 document.getElementById("uploadError").style.display = "none";
337 document.getElementById("uploadErrorMsg").textContent = "";
338 // Now show the status area.
339 document.getElementById("uploadStatus").style.display = "block";
341 // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
342 var trackBlob = new Blob([convertTrack("gpx")],
343 { "type" : "application/gpx+xml" });
344 var formData = new FormData();
345 formData.append("file", trackBlob);
346 var desc = document.getElementById("uploadDesc").value;
347 formData.append("description",
348 desc.length ? desc : "Track recorded via Lantea Maps");
349 //formData.append("tags", "");
350 formData.append("visibility",
351 document.getElementById("uploadVisibility").value);
352 // Do an empty POST request first, so that we don't send everything,
353 // then ask for credentials, and then send again.
354 var hXHR = new XMLHttpRequest();
355 hXHR.onreadystatechange = function() {
356 if (hXHR.readyState == 4 && (hXHR.status == 200 || hXHR.status == 400)) {
357 // 400 is Bad Request, but that's expected as this was empty.
358 // So far so good, init actual upload.
359 var XHR = new XMLHttpRequest();
360 XHR.onreadystatechange = function() {
361 if (XHR.readyState == 4 && XHR.status == 200) {
362 // Everthing looks fine.
363 reportUploadStatus(true);
364 } else if (XHR.readyState == 4 && XHR.status != 200) {
365 // Fetched the wrong page or network error...
366 reportUploadStatus(false);
369 XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
370 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
371 // So, we'll ask the user for entering credentials with rather ugly UI.
372 XHR.withCredentials = true;
374 XHR.send(formData); // Send actual form data.
377 reportUploadStatus(false, e);
379 } else if (hXHR.readyState == 4 && hXHR.status != 200) {
380 // Fetched the wrong page or network error...
381 reportUploadStatus(false);
384 hXHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
385 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
386 // So, we'll ask the user for entering credentials with rather ugly UI.
387 hXHR.withCredentials = true;
389 hXHR.send(); // Empty request, see above.
392 reportUploadStatus(false, e);
396 function reportUploadStatus(aSuccess, aMessage) {
397 document.getElementById("uploadStatusCloseButton").disabled = false;
398 document.getElementById("uploadInProgress").style.display = "none";
400 document.getElementById("uploadSuccess").style.display = "block";
403 document.getElementById("uploadErrorMsg").textContent = aMessage;
404 document.getElementById("uploadError").style.display = "block";
407 document.getElementById("uploadFailed").style.display = "block";
414 get: function(aKey, aCallback) {
417 var transaction = mainDB.transaction([this.objStore]);
418 var request = transaction.objectStore(this.objStore).get(aKey);
419 request.onsuccess = function(event) {
420 aCallback(request.result, event);
422 request.onerror = function(event) {
423 // Errors can be handled here.
424 aCallback(undefined, event);
428 set: function(aKey, aValue, aCallback) {
432 var transaction = mainDB.transaction([this.objStore], "readwrite");
433 var objStore = transaction.objectStore(this.objStore);
434 var request = objStore.put(aValue, aKey);
435 request.onsuccess = function(event) {
438 aCallback(success, event);
440 request.onerror = function(event) {
441 // Errors can be handled here.
443 aCallback(success, event);
447 unset: function(aKey, aCallback) {
451 var transaction = mainDB.transaction([this.objStore], "readwrite");
452 var request = transaction.objectStore(this.objStore).delete(aKey);
453 request.onsuccess = function(event) {
456 aCallback(success, event);
458 request.onerror = function(event) {
459 // Errors can be handled here.
461 aCallback(success, event);
469 getList: function(aCallback) {
472 var transaction = mainDB.transaction([this.objStore]);
473 var objStore = transaction.objectStore(this.objStore);
474 if (objStore.getAll) { // currently Mozilla-specific
475 objStore.getAll().onsuccess = function(event) {
476 aCallback(event.target.result);
479 else { // Use cursor (standard method).
481 objStore.openCursor().onsuccess = function(event) {
482 var cursor = event.target.result;
484 tPoints.push(cursor.value);
494 getListStepped: function(aCallback) {
497 var transaction = mainDB.transaction([this.objStore]);
498 var objStore = transaction.objectStore(this.objStore);
499 // Use cursor in reverse direction (so we get the most recent position first)
500 objStore.openCursor(null, "prev").onsuccess = function(event) {
501 var cursor = event.target.result;
503 aCallback(cursor.value);
512 push: function(aValue, aCallback) {
515 var transaction = mainDB.transaction([this.objStore], "readwrite");
516 var objStore = transaction.objectStore(this.objStore);
517 var request = objStore.add(aValue);
518 request.onsuccess = function(event) {
520 aCallback(request.result, event);
522 request.onerror = function(event) {
523 // Errors can be handled here.
525 aCallback(false, event);
529 clear: function(aCallback) {
533 var transaction = mainDB.transaction([this.objStore], "readwrite");
534 var request = transaction.objectStore(this.objStore).clear();
535 request.onsuccess = function(event) {
538 aCallback(success, event);
540 request.onerror = function(event) {
541 // Errors can be handled here.
543 aCallback(success, event);