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 indexedDB object.
6 window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
9 var gUIHideCountdown = 0;
11 var gAction, gActionLabel;
12 var gOSMAPIURL = "http://api.openstreetmap.org/";
14 window.onload = function() {
15 gAction = document.getElementById("action");
16 gActionLabel = document.getElementById("actionlabel");
18 var mSel = document.getElementById("mapSelector");
19 for (var mapStyle in gMapStyles) {
20 var opt = document.createElement("option");
22 opt.text = gMapStyles[mapStyle].name;
26 var areas = document.getElementsByClassName('overlayArea');
27 for (var i = 0; i <= areas.length - 1; i++) {
28 areas[i].addEventListener("mouseup", uiEvHandler, false);
29 areas[i].addEventListener("mousemove", uiEvHandler, false);
30 areas[i].addEventListener("mousedown", uiEvHandler, false);
31 areas[i].addEventListener("mouseout", uiEvHandler, false);
33 areas[i].addEventListener("touchstart", uiEvHandler, false);
34 areas[i].addEventListener("touchmove", uiEvHandler, false);
35 areas[i].addEventListener("touchend", uiEvHandler, false);
36 areas[i].addEventListener("touchcancel", uiEvHandler, false);
37 areas[i].addEventListener("touchleave", uiEvHandler, false);
40 document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
42 if (navigator.platform.length == "") {
43 // For Firefox OS, don't display the "save" button.
44 // Do this by setting the debugHide class for testing in debug mode.
45 document.getElementById("saveTrackButton").classList.add("debugHide");
48 // Without OAuth, the login data is useless
49 //document.getElementById("uploadSettingsArea").classList.remove("debugHide");
50 // As login data is useless for now, always enable upload button
51 document.getElementById("uploadTrackButton").disabled = false;
54 // Note that GPX upload returns an error 500 on the dev API right now.
55 gOSMAPIURL = "http://api06.dev.openstreetmap.org/";
58 gAction.addEventListener("dbinit-done", initMap, false);
59 gAction.addEventListener("mapinit-done", postInit, false);
60 console.log("starting DB init...");
64 function postInit(aEvent) {
65 gAction.removeEventListener(aEvent.type, postInit, false);
66 console.log("init done, draw map.");
67 gMapPrefsLoaded = true;
69 gActionLabel.textContent = "";
70 gAction.style.display = "none";
71 setTracking(document.getElementById("trackCheckbox"));
72 gPrefs.get(gDebug ? "osm_dev_user" : "osm_user", function(aValue) {
74 document.getElementById("uploadUser").value = aValue;
75 document.getElementById("uploadTrackButton").disabled = false;
78 gPrefs.get(gDebug ? "osm_dev_pwd" : "osm_pwd", function(aValue) {
79 var upwd = document.getElementById("uploadPwd");
81 document.getElementById("uploadPwd").value = aValue;
85 window.onresize = function() {
89 function initDB(aEvent) {
92 gAction.removeEventListener(aEvent.type, initDB, false);
93 var request = window.indexedDB.open("MainDB-lantea", 2);
94 request.onerror = function(event) {
95 // Errors can be handled here. Error codes explain in:
96 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
98 console.log("error opening mainDB: " + event.target.errorCode);
100 request.onsuccess = function(event) {
101 mainDB = request.result;
102 var throwEv = new CustomEvent("dbinit-done");
103 gAction.dispatchEvent(throwEv);
105 request.onupgradeneeded = function(event) {
106 mainDB = request.result;
107 var ver = mainDB.version || 0; // version is empty string for a new DB
109 console.log("mainDB has version " + ver + ", upgrade needed.");
110 if (!mainDB.objectStoreNames.contains("prefs")) {
111 // Create a "prefs" objectStore.
112 var prefsStore = mainDB.createObjectStore("prefs");
114 if (!mainDB.objectStoreNames.contains("track")) {
115 // Create a "track" objectStore.
116 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
118 if (!mainDB.objectStoreNames.contains("tilecache")) {
119 // Create a "tilecache" objectStore.
120 var tilecacheStore = mainDB.createObjectStore("tilecache");
122 mainDB.onversionchange = function(event) {
131 if (gUIHideCountdown <= 0) {
132 var areas = document.getElementsByClassName('overlayArea');
133 for (var i = 0; i <= areas.length - 1; i++) {
134 areas[i].classList.remove("hidden");
136 setTimeout(maybeHideUI, 1000);
138 gUIHideCountdown = 5;
141 function maybeHideUI() {
143 if (gUIHideCountdown <= 0) {
144 var areas = document.getElementsByClassName('overlayArea');
145 for (var i = 0; i <= areas.length - 1; i++) {
146 areas[i].classList.add("hidden");
150 setTimeout(maybeHideUI, 1000);
154 function toggleTrackArea() {
155 var fs = document.getElementById("trackArea");
156 if (fs.style.display != "block") {
157 fs.style.display = "block";
161 fs.style.display = "none";
165 function toggleSettings() {
166 var fs = document.getElementById("settingsArea");
167 if (fs.style.display != "block") {
168 fs.style.display = "block";
172 fs.style.display = "none";
176 function toggleFullscreen() {
177 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
178 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
179 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
180 if (document.cancelFullScreen) {
181 document.cancelFullScreen();
182 } else if (document.mozCancelFullScreen) {
183 document.mozCancelFullScreen();
184 } else if (document.webkitCancelFullScreen) {
185 document.webkitCancelFullScreen();
189 var elem = document.getElementById("body");
190 if (elem.requestFullScreen) {
191 elem.requestFullScreen();
192 } else if (elem.mozRequestFullScreen) {
193 elem.mozRequestFullScreen();
194 } else if (elem.webkitRequestFullScreen) {
195 elem.webkitRequestFullScreen();
200 function showUploadDialog() {
201 var dia = document.getElementById("dialogArea");
202 var areas = dia.children;
203 for (var i = 0; i <= areas.length - 1; i++) {
204 areas[i].style.display = "none";
206 document.getElementById("uploadDialog").style.display = "block";
207 document.getElementById("uploadTrackButton").disabled = true;
208 dia.classList.remove("hidden");
211 function cancelDialog() {
212 document.getElementById("dialogArea").classList.add("hidden");
213 document.getElementById("uploadTrackButton").disabled = false;
217 handleEvent: function(aEvent) {
218 var touchEvent = aEvent.type.indexOf('touch') != -1;
220 switch (aEvent.type) {
234 function setUploadField(aField) {
237 gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
238 document.getElementById("uploadTrackButton").disabled = !aField.value.length;
241 gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
246 function makeISOString(aTimestamp) {
247 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
248 var tsDate = new Date(aTimestamp);
249 // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
250 return tsDate.getUTCFullYear() + "-" +
251 (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
252 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
253 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
254 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
255 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
258 function convertTrack(aTargetFormat) {
260 switch (aTargetFormat) {
262 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
263 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
265 out += ' <trk>' + "\n";
266 out += ' <trkseg>' + "\n";
267 for (var i = 0; i < gTrack.length; i++) {
268 if (gTrack[i].beginSegment && i > 0) {
269 out += ' </trkseg>' + "\n";
270 out += ' <trkseg>' + "\n";
272 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
273 gTrack[i].coords.longitude + '">' + "\n";
274 if (gTrack[i].coords.altitude) {
275 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
277 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
278 out += ' </trkpt>' + "\n";
280 out += ' </trkseg>' + "\n";
281 out += ' </trk>' + "\n";
283 out += '</gpx>' + "\n";
286 out = JSON.stringify(gTrack);
294 function saveTrack() {
296 var outDataURI = "data:application/gpx+xml," +
297 encodeURIComponent(convertTrack("gpx"));
298 window.open(outDataURI, 'GPX Track');
302 function saveTrackDump() {
304 var outDataURI = "data:application/json," +
305 encodeURIComponent(convertTrack("json"));
306 window.open(outDataURI, 'JSON dump');
310 function uploadTrack() {
311 // Hide all areas in the dialog.
312 var dia = document.getElementById("dialogArea");
313 var areas = dia.children;
314 for (var i = 0; i <= areas.length - 1; i++) {
315 areas[i].style.display = "none";
317 // Reset all the fields in the status area.
318 document.getElementById("uploadStatusCloseButton").disabled = true;
319 document.getElementById("uploadInProgress").style.display = "block";
320 document.getElementById("uploadSuccess").style.display = "none";
321 document.getElementById("uploadErrorMsg").textContent = "";
322 document.getElementById("uploadError").style.display = "none";
323 // Now show the status area.
324 document.getElementById("uploadStatus").style.display = "block";
326 // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
327 var trackBlob = new Blob([convertTrack("gpx")],
328 { "type" : "application/gpx+xml" });
329 var formData = new FormData();
330 formData.append("file", trackBlob);
331 var desc = document.getElementById("uploadDesc").value;
332 formData.append("description",
333 desc.length ? desc : "Track recorded via Lantea Maps");
334 //formData.append("tags", "");
335 formData.append("visibility",
336 document.getElementById("uploadVisibility").value);
337 // Do an empty POST request first, so that we don't send everything,
338 // then ask for credentials, and then send again.
339 var hXHR = new XMLHttpRequest();
340 hXHR.onreadystatechange = function() {
341 if (hXHR.readyState == 4 && (hXHR.status == 200 || hXHR.status == 400)) {
342 // 400 is Bad Request, but that's expected as this was empty.
343 // So far so good, init actual upload.
344 var XHR = new XMLHttpRequest();
345 XHR.onreadystatechange = function() {
346 if (XHR.readyState == 4 && XHR.status == 200) {
347 // Everthing looks fine.
348 reportUploadStatus(true);
349 } else if (XHR.readyState == 4 && XHR.status != 200) {
350 // Fetched the wrong page or network error...
351 reportUploadStatus(false);
354 XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
355 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
356 // So, we'll ask the user for entering credentials with rather ugly UI.
357 XHR.withCredentials = true;
359 XHR.send(formData); // Send actual form data.
362 reportUploadStatus(false, e);
364 } else if (hXHR.readyState == 4 && hXHR.status != 200) {
365 // Fetched the wrong page or network error...
366 reportUploadStatus(false);
369 hXHR.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 hXHR.withCredentials = true;
374 hXHR.send(); // Empty request, see above.
377 reportUploadStatus(false, e);
381 function reportUploadStatus(aSuccess, aMessage) {
382 document.getElementById("uploadStatusCloseButton").disabled = false;
383 document.getElementById("uploadInProgress").style.display = "none";
385 document.getElementById("uploadSuccess").style.display = "block";
388 document.getElementById("uploadErrorMsg").textContent = aMessage;
389 document.getElementById("uploadError").style.display = "block";
392 document.getElementById("uploadFailed").style.display = "block";
399 get: function(aKey, aCallback) {
402 var transaction = mainDB.transaction([this.objStore]);
403 var request = transaction.objectStore(this.objStore).get(aKey);
404 request.onsuccess = function(event) {
405 aCallback(request.result, event);
407 request.onerror = function(event) {
408 // Errors can be handled here.
409 aCallback(undefined, event);
413 set: function(aKey, aValue, aCallback) {
417 var transaction = mainDB.transaction([this.objStore], "readwrite");
418 var objStore = transaction.objectStore(this.objStore);
419 var request = objStore.put(aValue, aKey);
420 request.onsuccess = function(event) {
423 aCallback(success, event);
425 request.onerror = function(event) {
426 // Errors can be handled here.
428 aCallback(success, event);
432 unset: function(aKey, aCallback) {
436 var transaction = mainDB.transaction([this.objStore], "readwrite");
437 var request = transaction.objectStore(this.objStore).delete(aKey);
438 request.onsuccess = function(event) {
441 aCallback(success, event);
443 request.onerror = function(event) {
444 // Errors can be handled here.
446 aCallback(success, event);
454 getList: function(aCallback) {
457 var transaction = mainDB.transaction([this.objStore]);
458 var objStore = transaction.objectStore(this.objStore);
459 if (objStore.getAll) { // currently Mozilla-specific
460 objStore.getAll().onsuccess = function(event) {
461 aCallback(event.target.result);
464 else { // Use cursor (standard method).
466 objStore.openCursor().onsuccess = function(event) {
467 var cursor = event.target.result;
469 tPoints.push(cursor.value);
479 getListStepped: function(aCallback) {
482 var transaction = mainDB.transaction([this.objStore]);
483 var objStore = transaction.objectStore(this.objStore);
484 // Use cursor in reverse direction (so we get the most recent position first)
485 objStore.openCursor(null, "prev").onsuccess = function(event) {
486 var cursor = event.target.result;
488 aCallback(cursor.value);
497 push: function(aValue, aCallback) {
500 var transaction = mainDB.transaction([this.objStore], "readwrite");
501 var objStore = transaction.objectStore(this.objStore);
502 var request = objStore.add(aValue);
503 request.onsuccess = function(event) {
505 aCallback(request.result, event);
507 request.onerror = function(event) {
508 // Errors can be handled here.
510 aCallback(false, event);
514 clear: function(aCallback) {
518 var transaction = mainDB.transaction([this.objStore], "readwrite");
519 var request = transaction.objectStore(this.objStore).clear();
520 request.onsuccess = function(event) {
523 aCallback(success, event);
525 request.onerror = function(event) {
526 // Errors can be handled here.
528 aCallback(success, event);