lib.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522
  1. /*
  2. Copyright (c) 2013 Mapo developers and contributors <mapo.tizen@gmail.com>
  3. This file is part of Mapo.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. /*
  16. * Application Global variables
  17. */
  18. var web = "http://notabug.org/tizen/mapo";
  19. web = "http://rzr.github.io/";
  20. var gEmail = "mapo.tizen@gmail.com";
  21. // The map of the application
  22. var map = null;
  23. // The boolean which provide the connection state of the application
  24. var isReady = true;
  25. var isAdvanced = false;
  26. var isOnline = navigator.onLine;
  27. var isLoaded = false;
  28. var isDownloaded = false;
  29. var gLocationDate = null;
  30. /*
  31. * Recording Global Variable
  32. */
  33. // Directory where the recording document is placed
  34. var docDir;
  35. // Name of the recording document
  36. var doc;
  37. // The file where the records are placed
  38. var file;
  39. // Boolean which provide the information if a file has been recorded
  40. var fileRecorded = false;
  41. var url_openlayers = "http://openlayers.org/api/OpenLayers.js";
  42. // var url_gmaps = "http://maps.google.com/maps/api/js?v=3.2&sensor=false";
  43. var url_gmaps = 'http://maps.googleapis.com/maps/api/js?v=3.2&signed_in=true&callback=handleLoadedGmaps';
  44. /*
  45. * General Manager
  46. */
  47. /**
  48. * Quit the application
  49. */
  50. function exit() {
  51. if ('undefined' !== typeof (tizen)) {
  52. tizen.application.getCurrentApplication().exit();
  53. } else {
  54. log("exit:");
  55. }
  56. }
  57. /**
  58. * Show a message
  59. *
  60. * @param message
  61. */
  62. function log(message) {
  63. var text = "# ";
  64. try {
  65. var json = JSON.stringify(message);
  66. text += json;
  67. } catch (e) {
  68. text += "not json: " + message;
  69. }
  70. if (isAdvanced) {
  71. console.log(text);
  72. var element = document.getElementById("console");
  73. element.innerHTML += "<pre>" + text + "</pre>";
  74. }
  75. }
  76. function logMap(data) {
  77. for (i = 0; i < data.length; i++) {
  78. log("#" + i + " key:" + data[i].key);
  79. for (j = 0; j < data[i].value.length; j++) {
  80. log(" value#" + j + ":" + data[i].value[j]);
  81. }
  82. }
  83. }
  84. // upstream: https://gist.github.com/kamranzafar/3136584#comment-1244934
  85. function toast(message, delay) {
  86. if (typeof (b) === 'undefined') {
  87. delay = 2000;
  88. }
  89. var $toast = $('<div class="ui-loader ui-overlay-shadow ui-body-e ui-corner-all"><h3>'
  90. + message + '</h3></div>');
  91. $toast.css({
  92. display : 'block',
  93. background : '#fff',
  94. opacity : 0.90,
  95. position : 'fixed',
  96. padding : '7px',
  97. 'text-align' : 'center',
  98. width : '270px',
  99. left : ($(window).width() - 284) / 2,
  100. top : $(window).height() / 2 - 20
  101. });
  102. var removeToast = function() {
  103. $(this).remove();
  104. };
  105. $toast.click(removeToast);
  106. $toast.appendTo($.mobile.pageContainer).delay(delay);
  107. $toast.fadeOut(400, removeToast);
  108. }
  109. function handleError(message) {
  110. message = "error: " + message;
  111. log(message);
  112. toast(message);
  113. return message;
  114. }
  115. function handleException(e) {
  116. return handleError(e.name);
  117. }
  118. function handleSuccess() {
  119. return log("success: ");
  120. }
  121. function handleFailure() {
  122. return log("failure: ");
  123. }
  124. /*
  125. * Storage Manager
  126. */
  127. /**
  128. * Store the coordinates values in the local storage
  129. */
  130. function storeData() {
  131. localStorage.setItem('lat', $('#lat').val());
  132. localStorage.setItem('lon', $('#lon').val());
  133. localStorage.setItem('dms', $('#dms').val());
  134. }
  135. /**
  136. * Store the settings values in the local storage
  137. */
  138. function storeSettings() {
  139. log("#{ storeSettings: " + isOnline);
  140. localStorage.setItem('connection', $('#switchOnline').val());
  141. localStorage.setItem('energySaving', $('#switchEnergy').val());
  142. localStorage.setItem('timeout', $('#selectorTimeout').val());
  143. localStorage.setItem('downloaded', isDownloaded);
  144. isAdvanced = $('#switchDeveloper').val();
  145. localStorage.setItem('develmode', isAdvanced );
  146. log("#} storeSettings: " + isOnline);
  147. }
  148. function store() {
  149. var i = 0;
  150. var r = $.Deferred();
  151. storeData();
  152. storeSettings();
  153. for (i = 0; i < localStorage.length; i++) {
  154. log(i + " -- " + localStorage.key(i) + " : "
  155. + localStorage.getItem(localStorage.key(i)));
  156. }
  157. r.resolve();
  158. return r;
  159. }
  160. /**
  161. * Store the data before quitting the application
  162. */
  163. function quit() {
  164. log("#{ exit");
  165. store().done(exit);
  166. log("#} exit");
  167. }
  168. /*
  169. * Set Manager
  170. */
  171. /**
  172. * Modify the latitude value
  173. *
  174. * @param lat :
  175. * new latitude value
  176. */
  177. function setLat(lat) {
  178. if (document.getElementById("lat").value !== lat) {
  179. document.getElementById("lat").value = lat;
  180. }
  181. }
  182. /**
  183. * Modify the longitude value
  184. *
  185. * @param lon :
  186. * new longitude value
  187. */
  188. function setLon(lon) {
  189. if (document.getElementById("lon").value !== lon) {
  190. document.getElementById("lon").value = lon;
  191. }
  192. }
  193. function makeMessageShort() {
  194. var tag = fromLatLonToTag($("#lat").val(), $("#lon").val());
  195. var message = web + "#" + tag + " I am at " + "#" + tag;
  196. return message;
  197. }
  198. function makeTwitterUrl() {
  199. var tag = fromLatLonToTag($("#lat").val(), $("#lon").val());
  200. var url = web + "%23" + tag;
  201. var message = " I am at " + "#" + tag;
  202. var baseurl = 'https://twitter.com/intent/tweet?&via=TizenHelper&url=${web}&text=${message}';
  203. url = baseurl.replace("${web}", url);
  204. message = encodeURIComponent(message);
  205. url = url.replace("${message}", message);
  206. return url;
  207. }
  208. /*
  209. * Link Manager
  210. */
  211. /**
  212. * Get the OpenStreetMap link with the corresponding latitude and longitude
  213. *
  214. * @returns url
  215. */
  216. function getLink(provider) {
  217. var lat = $("#lat").val();
  218. var lon = $("#lon").val();
  219. var url = web;
  220. var message = null;
  221. var tag = null;
  222. switch (provider) {
  223. case 'OSM':
  224. url = "http://www.openstreetmap.org/?&zoom=10&layers=mapnik&lat=${lat}&lon=${lon}";
  225. break;
  226. case 'GM':
  227. url = "http://maps.google.com/maps?&z=10&ll=${lat},${lon}";
  228. break;
  229. case 'HERE':
  230. url = "http://maps.nokia.com/${lat},${lon},16,0,0,normal.day";
  231. break;
  232. case 'bing':
  233. url = "http://www.bing.com/maps/?v=2&style=r&lvl=13&cp=48.11~${lat}~${lon}&style=r&lvl=4";
  234. break;
  235. case 'twitter':
  236. url = makeTwitterUrl();
  237. break;
  238. default:
  239. tag = fromLatLonToTag(lat, lon);
  240. url = provider;
  241. break;
  242. }
  243. url = url.replace("${lon}", lon);
  244. url = url.replace("${lat}", lat);
  245. url = url.replace("${tag}", tag);
  246. url = url.replace("${url}", web);
  247. url = url.replace("${web}", web);
  248. return url;
  249. }
  250. /**
  251. * Use the Internet Application Control to go to OSM link with the browser
  252. */
  253. function goToURL(provider) {
  254. var i = 0;
  255. var j = 0;
  256. var url = getLink(provider);
  257. log(url);
  258. if ('undefined' !== typeof (tizen)) {
  259. if (isOnline) {
  260. var appControl = new tizen.ApplicationControl(
  261. "http://tizen.org/appcontrol/operation/view", url, null);
  262. var appControlReplyCallback = {
  263. onsuccess : logMap,
  264. onfailure : handleFailure
  265. }
  266. tizen.application.launchAppControl(appControl, null, function() {
  267. log("launch internet application control succeed");
  268. }, function(e) {
  269. log("launch internet application control failed. reason: "
  270. + e.message);
  271. }, appControlReplyCallback);
  272. } else {
  273. handleError("Please connect your application online in the settings"
  274. + " if you want to open a browser")
  275. }
  276. } else {
  277. window.open(url);
  278. }
  279. }
  280. /**
  281. * update links TODO: check if needed ?
  282. */
  283. function updateLinks() {
  284. $('#OSMLink').attr('href', getOSMLink());
  285. }
  286. /*
  287. * Map Manager
  288. */
  289. /**
  290. * get the size of the map (width, height) according to the dimension of the
  291. * screen
  292. *
  293. * @returns [ width, height ]
  294. */
  295. function getMapSize() {
  296. var viewHeight = $(window).height();
  297. var viewWidth = $(window).width();
  298. var header = $("div[data-role='header']:visible:visible");
  299. var footer = $("div[data-role='footer']:visible:visible");
  300. var navbar = $("div[data-role='navbar']:visible:visible");
  301. var content = $("div[data-role='content']:visible:visible");
  302. var contentHeight = viewHeight - header.outerHeight()
  303. - navbar.outerHeight() - footer.outerHeight();
  304. var contentWidth = viewWidth - 30;
  305. return [ contentWidth, contentHeight ];
  306. }
  307. /**
  308. * Modify the dimension of the map according to getMapSize()
  309. */
  310. function setMapSize(size) {
  311. size = getMapSize();
  312. $('#myMap').css("width", size[0]);
  313. $('#myMap').css("height", size[1]);
  314. }
  315. function initIcon() {
  316. var size = new OpenLayers.Size(21, 25);
  317. var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
  318. return new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',
  319. size, offset);
  320. }
  321. function loadTrace(data) {
  322. var i = 0;
  323. log("loadTrace data : " + data['dates'][0]);
  324. var icon = initIcon();
  325. log("tab lons = " + data['lons']);
  326. log("tab lats = " + data['lats']);
  327. log("tab dates = " + data['dates']);
  328. for (i = 0; i < data['dates'].length; i++) {
  329. var lon = parseFloat(data['lons'][i]);
  330. var lat = parseFloat(data['lats'][i]);
  331. var date = data['dates'][i];
  332. log("data['dates'][" + i + "] = " + date);
  333. log("data['lons'][" + i + "] = " + lon);
  334. log("data['lat'][" + i + "] = " + lat);
  335. log("lat before : " + lat);
  336. log("lon before : " + lon);
  337. var lonlat = new OpenLayers.LonLat(lon, lat).transform('EPSG:4326',
  338. 'EPSG:3857');
  339. var mark = new OpenLayers.Marker(lonlat, icon);
  340. trace.addMarker(mark);
  341. }
  342. map.addLayer(trace);
  343. }
  344. /**
  345. * Load the OpenLayers map with different OpenStreetMap and Google maps' layers
  346. * TODO: check if needed ?
  347. */
  348. function loadMap() {
  349. log("#{ loadMap: " + OpenLayers);
  350. if (OpenLayers === null) {
  351. log("error: OpenLayers " + isDownloaded);
  352. return;
  353. }
  354. var latCenter = $("#lat").val();
  355. var lonCenter = $("#lon").val();
  356. var zoom = $("#zoom").val();
  357. var layers = [ new OpenLayers.Layer.OSM("OpenStreetMap") ];
  358. log("# is gmaps available ? " + gmaps + "/" + gmaps);
  359. if (gmaps !== null) {
  360. var array = [ new OpenLayers.Layer.Google("Google Satellite", {
  361. type : google.maps.MapTypeId.SATELLITE,
  362. numZoomLevels : 22,
  363. })
  364. , new OpenLayers.Layer.Google("Google Physical", {
  365. type : google.maps.MapTypeId.TERRAIN
  366. }), new OpenLayers.Layer.Google("Google Hybrid", {
  367. type : google.maps.MapTypeId.HYBRID,
  368. numZoomLevels : 20
  369. }),
  370. new OpenLayers.Layer.Google("Google Streets", {
  371. numZoomLevels : 20
  372. }) ];
  373. // layers = array.concat(layers);
  374. layers = layers.concat(array);
  375. }
  376. log("# add ui " + layers);
  377. map = new OpenLayers.Map('myMap', {
  378. projection : 'EPSG:3857',
  379. layers : layers,
  380. center : new OpenLayers.LonLat(lonCenter, latCenter).transform(
  381. 'EPSG:4326', 'EPSG:3857'),
  382. zoom : zoom,
  383. controls : [ new OpenLayers.Control.TouchNavigation(),
  384. new OpenLayers.Control.PanZoom(),
  385. new OpenLayers.Control.ArgParser() ]
  386. });
  387. if (isAdvanced)
  388. map.addControl(new OpenLayers.Control.LayerSwitcher());
  389. if (fileRecorded) { // TODO : Data vide : data([0])?.length!=0 or
  390. // fileRecorded
  391. // var trace = new OpenLayers.Layer.Markers( "Latest recorded trace"
  392. // );
  393. // map.removeLayer(trace);
  394. var markers = map.getLayersByName("Last recorded trace");
  395. if (markers.length != 0) {
  396. var previousTrace = markers[0];
  397. log("trace = " + previousTrace.name);
  398. previousTrace.destroy();
  399. }
  400. trace = new OpenLayers.Layer.Markers("Last recorded trace");
  401. // readFile().done(loadTrace);
  402. readFile();
  403. // setTimeout(
  404. // // log("result 0 : "+result[0]);
  405. // // log("result 1 : "+result[1]);
  406. // loadTrace
  407. // , 5000);
  408. }
  409. log("#} loadMap: " + OpenLayers);
  410. }
  411. /*
  412. * Refresh Manager
  413. */
  414. /**
  415. * Refresh all the application according to the coordinates and the settings
  416. */
  417. function refresh() {
  418. log("#{ refresh: " + OpenLayers);
  419. if (isOnline) {
  420. isReady = (OpenLayers !== null);
  421. } else {
  422. isReady = false;
  423. }
  424. log("isReady=" + isReady);
  425. if (isReady) {
  426. $('#myMap').empty();
  427. setMapSize();
  428. loadMap();
  429. } else {
  430. // isOnline = navigator.onLine;
  431. // $('#switchOnline').val(isOnline ? 'online' : 'offline');
  432. $('#myMap').empty();
  433. $('#myMap')
  434. .html(
  435. "<p align='center'>"
  436. + "Please connect your application online in the settings"
  437. + " if you want to load the map</p>");
  438. }
  439. // isOffline $('#switchOffline').val() // TODO
  440. updateDMS();
  441. if (gLocationDate != null) {
  442. var lat = $("#lat").val();
  443. var lon = $("#lon").val();
  444. var text = "Last update:<br/>" //
  445. + gLocationDate.toString() //
  446. + "<br/>" + "#" + fromLatLonToTag(lat, lon) //
  447. ;
  448. $('#locationInfo').html(text);
  449. }
  450. // var locationInfo = document.getElementById("locationInfo");
  451. // locationInfo.innerHTML = fromLatLonToDMS(lat, lon);
  452. log("#} refresh: " + isReady);
  453. }
  454. /*
  455. * Initialization Manager
  456. */
  457. /**
  458. * Recover in the local storage the coordinates values from the preceding use
  459. */
  460. function initData() {
  461. log("#{ initData");
  462. if (localStorage.getItem('lat') !== null) {
  463. $('#lat').val(localStorage.getItem('lat'));
  464. }
  465. if (localStorage.getItem('lon') !== null) {
  466. $('#lon').val(localStorage.getItem('lon'));
  467. }
  468. if (localStorage.getItem('dms') !== null) {
  469. $('#dms').val(localStorage.getItem('dms'));
  470. } // not needed
  471. storeData();
  472. log("#} initData");
  473. }
  474. /**
  475. * Recover in the local storage the setting values from the preceding use
  476. */
  477. function initSettings() {
  478. log("#{ initSettings: " + isOnline);
  479. if (null !== localStorage.getItem('connection')) {
  480. isOnline = (localStorage.getItem('connection') == 'online');
  481. }
  482. $('#switchOnline').val(isOnline ? 'online' : 'offline');
  483. if (localStorage.getItem('energySaving') !== null) {
  484. $('#switchEnergy').val(localStorage.getItem('energySaving'));
  485. }
  486. if (localStorage.getItem('timeout') !== null) {
  487. $('#selectorTimeout').attr('value', localStorage.getItem('timeout'));
  488. }
  489. if (localStorage.getItem('downloaded') !== null) {
  490. isDownloaded = localStorage.getItem('downloaded');
  491. }
  492. if (localStorage.getItem('develmode') !== null) {
  493. isAdvanced = localStorage.getItem('develmode');
  494. }
  495. $('#switchDeveloper').val(isAdvanced ? 'on' : 'off');
  496. storeSettings();
  497. log("#} initSettings: " + isReady);
  498. }
  499. /*
  500. * Coordinates transformation Manager
  501. */
  502. /**
  503. * Transform the latitude/longitude into DMS coordinate
  504. *
  505. * @param lat :
  506. * latitude
  507. * @param lon :
  508. * longitude
  509. * @returns dms : DMS coordinate
  510. */
  511. function fromLatLonToDMS(lat, lon) {
  512. var latitude = lat;
  513. var longitude = lon;
  514. var dms = "";
  515. var NS = "";
  516. if (latitude >= 0) {
  517. NS += "N";
  518. } else {
  519. latitude = -latitude;
  520. NS += "S";
  521. }
  522. var dLat = parseInt(latitude, 10);
  523. var mLat = parseInt((latitude - dLat) * 60, 10);
  524. var sLat = parseInt((latitude - dLat) * 60 * 60 - 60 * mLat, 10);
  525. dms += NS + " " + dLat + "° " + mLat + "' " + sLat + "\" ";
  526. var EW = "";
  527. if (longitude >= 0) {
  528. EW += "E";
  529. } else {
  530. EW += "W";
  531. longitude = -longitude;
  532. }
  533. var dLon = parseInt(longitude, 10);
  534. var mLon = parseInt((longitude - dLon) * 60, 10);
  535. var sLon = parseInt((longitude - dLon) * 60 * 60 - 60 * mLon, 10);
  536. dms += EW + " " + dLon + "° " + mLon + "' " + sLon + "\"";
  537. // text = NS+" "+d+"° "+m+"' "+s+"\" "+EW+" "+d+"° "+m+"' "+s+"\"";
  538. return dms;
  539. }
  540. /** @return string in this form : N26d21m28sE127d47m1s **/
  541. function fromLatLonToTag(lat, lon) {
  542. var result = "";
  543. var latitude = lat;
  544. var longitude = lon;
  545. var NS = "";
  546. if (latitude >= 0) {
  547. NS += "N";
  548. } else {
  549. latitude = -latitude;
  550. NS += "S";
  551. }
  552. var dLat = parseInt(latitude, 10);
  553. var mLat = parseInt((latitude - dLat) * 60, 10);
  554. var sLat = parseInt((latitude - dLat) * 60 * 60 - 60 * mLat, 10);
  555. result += NS + dLat + "d" + mLat + "m" + sLat + "s";
  556. var EW = "";
  557. if (longitude >= 0) {
  558. EW += "E";
  559. } else {
  560. EW += "W";
  561. longitude = -longitude;
  562. }
  563. var dLon = parseInt(longitude, 10);
  564. var mLon = parseInt((longitude - dLon) * 60, 10);
  565. var sLon = parseInt((longitude - dLon) * 60 * 60 - 60 * mLon, 10);
  566. result += EW + dLon + "d" + mLon + "m" + sLon + "s";
  567. return result;
  568. }
  569. /**
  570. * Transform the DMS into latitude/longitude coordinates
  571. *
  572. * @param dms :
  573. * DMS coordinate
  574. */
  575. function setDMS(input) {
  576. input = input.replace('°', 'd').replace('\'', 'm'), replace('"', s);
  577. setTag(input);
  578. }
  579. function setTag(input) {
  580. var re = /^#([NS])([0-9.\-]+)d([0-9.\-]+)m([0-9.\-]+)s([EW])([0-9.\-]+)d([0-9.\-]+)m([0-9.\-]+)s$/;
  581. if (re.test(input)) {
  582. var lat = (parseFloat(RegExp.$2) + parseFloat(RegExp.$3) / 60 + parseFloat(RegExp.$4)
  583. / (60 * 60)).toFixed(6);
  584. if (RegExp.$1 == 'S') {
  585. lat = -lat;
  586. }
  587. lat = lat.toString();
  588. setLat(lat);
  589. var lon = (parseFloat(RegExp.$6) + parseFloat(RegExp.$7) / 60 + parseFloat(RegExp.$8)
  590. / (60 * 60)).toFixed(6);
  591. if (RegExp.$5 == 'W') {
  592. lon = -lon;
  593. }
  594. lon = lon.toString();
  595. setLon(lon);
  596. refresh();
  597. }
  598. }
  599. /*
  600. * Coordinates Manager
  601. */
  602. /**
  603. * Modify the DMS value using the transformation's function fromLatLonToDMS
  604. */
  605. function updateDMS() {
  606. var lat = $("#lat").val();
  607. var lon = $("#lon").val();
  608. var text = fromLatLonToDMS(lat, lon);
  609. $('#dms').val(text);
  610. }
  611. function setLatLon() {
  612. setDMS($('#dms').val());
  613. }
  614. /**
  615. * Validate or not the DMS coordinate according to the form of the regular
  616. * expression
  617. *
  618. * @param dms :
  619. * DMS coordinates
  620. * @returns Validation
  621. */
  622. function validateDMS(dms) {
  623. var re = /^([NS])\s*([0-9.\-]+)\s*°\s*([0-9.\-]+)\s*\'\s*([0-9.\-]+)\s*\"\s*([EW])\s*([0-9.\-]+)\s*°\s*([0-9.\-]+)\s*\'\s*([0-9.\-]+)\s*\"\s*$/;
  624. if (re.test(dms)) {
  625. return true;
  626. } else {
  627. return false;
  628. }
  629. }
  630. /**
  631. * Validate or not the latitudes and longitudes coordinates according to the
  632. * form of the regular expression
  633. *
  634. * @param latOrLon
  635. * @returns Validation
  636. */
  637. function validateLatOrLon(latOrLon) {
  638. if (/^[0-9.\-]+$/.test(latOrLon)) {
  639. return true;
  640. } else {
  641. return false;
  642. }
  643. }
  644. /**
  645. * Function called when the latitude value changes Calculate the new DMS
  646. * coordinate
  647. */
  648. function changeLat() {
  649. var lat = $('#lat').val();
  650. if (validateLatOrLon(lat)) {
  651. $('#lat').val(parseFloat($('#lat').val()).toFixed(6).toString());
  652. refresh();
  653. storeData();
  654. } else {
  655. handleError("Latitude coordinate invalid : " + lat);
  656. initData();
  657. }
  658. }
  659. /**
  660. * Function called when the longitude value changes Calculate the new DMS
  661. * coordinate
  662. */
  663. function changeLon() {
  664. var lon = $('#lon').val();
  665. if (validateLatOrLon(lon)) {
  666. $('#lon').val(parseFloat($('#lon').val()).toFixed(6).toString());
  667. refresh();
  668. storeData();
  669. } else {
  670. handleError("Lontitude coordinate invalid : " + lon);
  671. initData();
  672. }
  673. }
  674. /**
  675. * Function called when the DMS value changes Calculate the new latitude and
  676. * longitude coordinates
  677. */
  678. function changeDMS() {
  679. var dms = $('#dms').val();
  680. if (validateDMS(dms)) {
  681. setLatLon();
  682. storeData();
  683. } else {
  684. alert("DMS coordinate invalid : " + dms);
  685. initData();
  686. }
  687. }
  688. /*
  689. * Location Manager
  690. */
  691. /**
  692. * Function called when the getCurrentPosition succeded Refresh the application
  693. */
  694. function handleShowLocation(position) {
  695. var lat = position.coords.latitude.toFixed(6).toString();
  696. var lon = position.coords.longitude.toFixed(6).toString();
  697. gLocationDate = new Date(position.timestamp);
  698. setLat(lat);
  699. setLon(lon);
  700. refresh();
  701. isLocated = true;
  702. }
  703. /**
  704. * Function called when the getCurrentPosition failed Show the error
  705. *
  706. * @param error
  707. */
  708. function handleErrorLocation(error) {
  709. var locationInfo = document.getElementById("locationInfo");
  710. switch (error.code) {
  711. case error.PERMISSION_DENIED:
  712. locationInfo.innerHTML = "error: User denied the request for Geolocation.";
  713. break;
  714. case error.POSITION_UNAVAILABLE:
  715. locationInfo.innerHTML = "error: Location information is unavailable.";
  716. break;
  717. case error.TIMEOUT:
  718. locationInfo.innerHTML = "error: The request to get user location timed out.";
  719. break;
  720. case error.UNKNOWN_ERROR:
  721. default:
  722. locationInfo.innerHTML = "error: An unknown error occurred.";
  723. break;
  724. }
  725. toast("Check settings and press update to track position", 4000);
  726. isLocated = false;
  727. }
  728. /**
  729. * Get the current position according to the GPS' device
  730. */
  731. function getLocation(isUpdate) {
  732. if (navigator.geolocation) {
  733. if (isUpdate) {
  734. navigator.geolocation.getCurrentPosition(handleShowLocation,
  735. handleErrorLocation, {
  736. enableHighAccuracy : $('#switchEnergy').val() == 'off'
  737. });
  738. } else {
  739. navigator.geolocation.watchPosition(updateMapCenter,
  740. handleErrorLocation, {
  741. enableHighAccuracy : $('#switchEnergy').val() == 'off'
  742. });
  743. }
  744. } else {
  745. document.getElementById("locationInfo").innerHTML = "Geolocation is not supported by this browser.";
  746. }
  747. }
  748. function updateMapCenter(position) {
  749. var latCenter = position.coords.latitude.toFixed(6).toString();
  750. var lonCenter = position.coords.longitude.toFixed(6).toString();
  751. map.setCenter(new OpenLayers.LonLat(lonCenter, latCenter).transform('EPSG:4326', 'EPSG:3857'));
  752. }
  753. /*
  754. * Recording manager
  755. */
  756. /**
  757. * Function called when the file resolution succeded Create the recording file
  758. * in the corresponding directory
  759. *
  760. * @param dir :
  761. * directory where the file is placed
  762. */
  763. function handleResolveSuccess(dir) {
  764. docDir = dir;
  765. var date = new Date();
  766. var dateFile = "" + date.getFullYear().toString() + "-"
  767. + date.getMonth().toString() + "-" + date.getDate().toString()
  768. + "-" + date.getHours().toString() + "-"
  769. + date.getMinutes().toString() + "-" + date.getSeconds().toString();
  770. dateFile = (new Date).getTime();
  771. // log(dateFile);
  772. doc = 'mapo-' + dateFile + ".csv.txt";
  773. docDir.createFile(doc);
  774. $('#locationInfo').html("Track recording in file:<br/>" + doc);
  775. }
  776. /**
  777. * Function called when the file resolution failed Show the error
  778. *
  779. * @param e :
  780. * error
  781. */
  782. function handleResolveError(e) {
  783. handleError('resolve: ' + e.message);
  784. }
  785. /**
  786. * Resolve the file
  787. */
  788. function resolveFile() {
  789. try {
  790. file = docDir.resolve(doc);
  791. } catch (exc) {
  792. log('Could not resolve file: ' + exc.message);
  793. // Stop in case of any errors
  794. return;
  795. }
  796. }
  797. /**
  798. * Function called when the record failed, writing or reading Show the error
  799. *
  800. * @param e :
  801. * error
  802. */
  803. function handleErrorStream(e) {
  804. var msg = '';
  805. switch (e.code) {
  806. case FileError.QUOTA_EXCEEDED_ERR:
  807. msg = 'QUOTA_EXCEEDED_ERR';
  808. break;
  809. case FileError.NOT_FOUND_ERR:
  810. msg = 'NOT_FOUND_ERR';
  811. break;
  812. case FileError.SECURITY_ERR:
  813. msg = 'SECURITY_ERR';
  814. break;
  815. case FileError.INVALID_MODIFICATION_ERR:
  816. msg = 'INVALID_MODIFICATION_ERR';
  817. break;
  818. case FileError.INVALID_STATE_ERR:
  819. msg = 'INVALID_STATE_ERR';
  820. break;
  821. default:
  822. msg = 'Unknown Error';
  823. break;
  824. }
  825. handleError(msg);
  826. }
  827. /**
  828. * Function called when the writing succeeded Add the position at the end of the
  829. * file
  830. *
  831. * @param fileStream :
  832. * Stream to write
  833. */
  834. function handleStreamWrite(stream) {
  835. try {
  836. var date = (new Date).getTime();
  837. var lat = $("#lat").val();
  838. var lon = $("#lon").val();
  839. var line = "" + date + ";" + lat + ";" + lon + "\n";
  840. stream.write(line);
  841. stream.close();
  842. } catch (exc) {
  843. handleError('io: could not write to file: ' + exc.message);
  844. }
  845. }
  846. /**
  847. * Try to write the record into the file
  848. */
  849. function writeRecord() {
  850. try {
  851. file.openStream('a', handleStreamWrite, handleErrorStream);
  852. } catch (exc) {
  853. handleError('io: could not write to file: ' + exc.message);
  854. }
  855. }
  856. /**
  857. * Function called when the reading succeded
  858. *
  859. * @param fileStream :
  860. * Stream to read
  861. */
  862. function handleStreamRead(fileStream) {
  863. try {
  864. log('File size: ' + file.fileSize);
  865. var contents = fileStream.read(fileStream.bytesAvailable);
  866. fileStream.close();
  867. log('file contents: ' + contents);
  868. } catch (exc) {
  869. handleError('io: Could not read from file: ' + exc.message);
  870. }
  871. }
  872. /**
  873. * Try to read the file
  874. */
  875. function readRecord() {
  876. try {
  877. file.openStream('r', handleStreamRead, handleRecordError);
  878. } catch (exc) {
  879. handleError('io: Could not write to file: ' + exc.message);
  880. }
  881. }
  882. /**
  883. * Function called when getPosition got successfully the position Resolve the
  884. * file, write and read the records
  885. *
  886. * @param position
  887. */
  888. function handleRecordPosition(position) {
  889. if ($('#switchRecord').val() == "start") {
  890. handleShowLocation(position);
  891. resolveFile();
  892. writeRecord();
  893. readRecord();
  894. }
  895. }
  896. /**
  897. * Function called when getPosition failed to get the position Show the error
  898. *
  899. * @param error
  900. */
  901. function handleErrorPosition(error) {
  902. $('#switchRecord').val('stop').slider('refresh');
  903. var errorInfo = document.getElementById("locationInfo");
  904. switch (error.code) {
  905. case error.PERMISSION_DENIED:
  906. errorInfo.innerHTML = "User denied the request for Geolocation.";
  907. break;
  908. case error.POSITION_UNAVAILABLE:
  909. errorInfo.innerHTML = "Location information is unavailable.";
  910. break;
  911. case error.TIMEOUT:
  912. errorInfo.innerHTML = "The request to get user location timed out.";
  913. break;
  914. case error.UNKNOWN_ERROR:
  915. errorInfo.innerHTML = "An unknown error occurred.";
  916. break;
  917. }
  918. }
  919. /**
  920. * Get the recording position
  921. */
  922. function getPosition() {
  923. navigator.geolocation.getCurrentPosition(handleRecordPosition, log, {
  924. enableHighAccuracy : false,
  925. timeout : 2000,
  926. maximumAge : Ininity
  927. });
  928. navigator.geolocation.getCurrentPosition(handleRecordPosition,
  929. handleErrorPosition, {
  930. enableHighAccuracy : $('#switchEnergy').val() == 'off'
  931. });
  932. }
  933. /**
  934. * Function called when the record of a trace has been launched Record the
  935. * position whith a timeout predefined in the settings
  936. */
  937. function record() {
  938. if (navigator.geolocation) {
  939. var intervalID;
  940. if ($('#switchRecord').val() == "start") {
  941. tizen.filesystem.resolve('documents', handleResolveSuccess,
  942. handleResolveError, 'rw');
  943. getPosition();
  944. intervalID = setInterval(getPosition,
  945. $('#selectorTimeout').val() * 1000);
  946. } else {
  947. clearInterval(intervalID);
  948. $('#locationInfo').html("Trace recorded in the file:<br/>" + doc);
  949. fileRecorded = true;
  950. }
  951. } else {
  952. document.getElementById("locationInfo").innerHTML = "Geolocation is not supported.";
  953. }
  954. }
  955. /**
  956. * Extract from a file composed by the last recorded trace all the dates,
  957. * latitudes and lontitudes and place its in data TODO: test if parse CSV as
  958. * "date,la,lo\n"
  959. */
  960. function readFile() {
  961. // var deferred = $.Deferred();
  962. try {
  963. file = docDir.resolve(doc);
  964. log('File size: ' + file.fileSize);
  965. } catch (exceptionResolve) {
  966. log('error: Could not resolve file: ' + exceptionResolve.message);
  967. // Stop in case of any errors
  968. return;
  969. }
  970. try {
  971. file.readAsText(
  972. // success callback - display the contents of the file
  973. function(contents) {
  974. // log('File contents:' + contents);
  975. var lines = contents.split("\n");
  976. var re = /^([0-9.:\-]+),([0-9.\-]+),([0-9.\-]+)$/;
  977. var data = [];
  978. var dates = [];
  979. var lats = [];
  980. var lons = [];
  981. var iData = 0;
  982. for (var iLines = 0; iLines < lines.length; iLines++) {
  983. if (re.test(lines[iLines])) {
  984. log("line " + iLines + ": " + lines[iLines]);
  985. var parts = lines[iLines].split(";");
  986. for (var iParts = 0; iParts < parts.length; iParts++) {
  987. log(" part " + iParts + ": " + parts[iParts]);
  988. if ((iParts % 3) == 0) {
  989. dates[iData] = parts[iParts];
  990. log(" date " + iData + ": " + dates[iData]);
  991. } else if ((iParts % 3) == 1) {
  992. lats[iData] = parts[iParts];
  993. log(" lat " + iData + ": " + lats[iData]);
  994. } else {
  995. lons[iData] = parts[iParts];
  996. log(" lon " + iData + ": " + lons[iData]);
  997. }
  998. }
  999. iData++;
  1000. }
  1001. }
  1002. data['dates'] = dates;
  1003. data['lats'] = lats;
  1004. data['lons'] = lons;
  1005. log("readfile data" + data['dates'][0]);
  1006. loadTrace(data);
  1007. },
  1008. // error callback
  1009. handleRecordError);
  1010. } catch (exceptionRead) {
  1011. handleError("io: readAsText() exception:" + exceptionRead.message);
  1012. }
  1013. // deferred.resolve();
  1014. // return deferred; // [data, referred]
  1015. }
  1016. /*
  1017. * Social Manager
  1018. */
  1019. function makeMessage() {
  1020. var message = "I am at this place:\n" //
  1021. + "#" + fromLatLonToTag($("#lat").val(), $("#lon").val()) + " \n" //
  1022. + "Latitude=" + $("#lat").val() + " \n" //
  1023. + "Longitude = " + $("#lon").val() + " \n" //
  1024. + "( " + $('#dms').val() + ")\n " + " \n" //
  1025. + getLink('OSM') + " \n" + web + " \n";
  1026. return message;
  1027. }
  1028. /**
  1029. * Use the Email Application Control to share a position by Email
  1030. */
  1031. function sendEmail() {
  1032. var email = gEmail;
  1033. var message = makeMessage();
  1034. var subject = "Mapo current position is ...";
  1035. if ('undefined' !== typeof (tizen)) {
  1036. if (isOnline) {
  1037. var appControl = new tizen.ApplicationControl(
  1038. "http://tizen.org/appcontrol/operation/compose", //
  1039. null, null, null, [
  1040. new tizen.ApplicationControlData(
  1041. "http://tizen.org/appcontrol/data/subject",
  1042. [ subject ]),
  1043. new tizen.ApplicationControlData(
  1044. "http://tizen.org/appcontrol/data/to",
  1045. [ email ]),
  1046. new tizen.ApplicationControlData(
  1047. "http://tizen.org/appcontrol/data/text",
  1048. [ message ]) ]);
  1049. tizen.application.launchAppControl(appControl, "tizen.email", //
  1050. handleSuccess, handleException);
  1051. } else {
  1052. alert("Please connect your application online in the settings"
  1053. + " if you want to send an email");
  1054. }
  1055. } else {
  1056. var url = "mailto:" + email + "?subject=" + subject + "&body="
  1057. + message;
  1058. window.open(url);
  1059. }
  1060. }
  1061. function sendMessage() {
  1062. var message = makeMessage();
  1063. var appControl = new tizen.ApplicationControl(
  1064. "http://tizen.org/appcontrol/operation/compose", null, null, null,
  1065. [
  1066. new tizen.ApplicationControlData(
  1067. "http://tizen.org/appcontrol/data/messagetype",
  1068. [ "sms" ]),
  1069. new tizen.ApplicationControlData(
  1070. "http://tizen.org/appcontrol/data/text",
  1071. [ message ]) ]);
  1072. tizen.application.launchAppControl(appControl, "tizen.messages", //
  1073. handleSuccess, handleException);
  1074. }
  1075. /*
  1076. * Settings Manager
  1077. */
  1078. function settings() {
  1079. var url = "http://tizen.org/appcontrol/operation/setting";
  1080. var id = "com.samsung.setting";
  1081. var appControl = new tizen.ApplicationControl(url);
  1082. tizen.application.launchAppControl(appControl, id, handleSuccess,
  1083. handleException);
  1084. }
  1085. function settingsLocation() {
  1086. var url = "http://tizen.org/appcontrol/operation/setting/location";
  1087. var id = "org.tizen.setting-location";
  1088. var appControl = new tizen.ApplicationControl(url);
  1089. tizen.application.launchAppControl(appControl, id, handleSuccess,
  1090. handleException);
  1091. }
  1092. function handleCapture(input) {
  1093. log($('#capture').val()); // fakepath
  1094. log("TODO: save to file using tag filename");
  1095. }
  1096. /*
  1097. * Caller Manager : may not be needed
  1098. */
  1099. function call() {
  1100. log("TODO");
  1101. exit();
  1102. var appControl = new tizen.ApplicationControl(
  1103. "http://tizen.org/appcontrol/operation/dial", null, null);
  1104. tizen.application.launchAppControl(appControl, "tizen.phone",
  1105. handleSuccess, handleException, null);
  1106. }
  1107. function caller() {
  1108. log("TODO");
  1109. exit();
  1110. var appControl = new tizen.ApplicationControl(
  1111. "http://tizen.org/appcontrol/operation/call",
  1112. null,
  1113. null,
  1114. null,
  1115. [ new tizen.ApplicationControlData(
  1116. "http://tizen.org/appcontrol/data/call/type", [ "voice" ]) ]);
  1117. tizen.application.launchAppControl(appControl, "tizen.call", //
  1118. handleSuccess, handleException);
  1119. }
  1120. /*
  1121. * Contact Manager
  1122. */
  1123. /**
  1124. * Use the Contact Application Control to add a contact with the corresponding
  1125. * position
  1126. */
  1127. function createContact() {
  1128. log("#{ createContact");
  1129. var addressbook = tizen.contact.getDefaultAddressBook();
  1130. var groups = addressbook.getGroups();
  1131. var idMapo = "-1";
  1132. for (var i = 0; i < groups.length; i++) {
  1133. log(groups[i].name);
  1134. if (groups[i].name == 'Mapo') {
  1135. idMapo = groups[i].id;
  1136. }
  1137. }
  1138. var group;
  1139. if (idMapo != "-1") {
  1140. group = addressbook.getGroup(idMapo);
  1141. log('Group already exists ' + group.id);
  1142. } else {
  1143. group = new tizen.ContactGroup('Mapo');
  1144. addressbook.addGroup(group);
  1145. log('Group added with id ' + group.id);
  1146. }
  1147. // TODO: edit contact is present
  1148. var contact = new tizen.Contact({
  1149. emails : [ new tizen.ContactEmailAddress(gEmail) ],
  1150. urls : [ new tizen.ContactWebSite(getLink('OSM'), 'HOMEPAGE') ],
  1151. notes : [ 'Position: lat=' + $("#lat").val() + ' lon='
  1152. + $("#lon").val() ],
  1153. organizations : [ new tizen.ContactOrganization({
  1154. name : "Mapo"
  1155. }) ],
  1156. groupIds : [ group.id ]
  1157. });
  1158. addressbook.add(contact);
  1159. var appControl = new tizen.ApplicationControl(
  1160. "http://tizen.org/appcontrol/operation/social/edit",
  1161. null,
  1162. "vnd.tizen.item.type/vnd.tizen.contact",
  1163. null,
  1164. [
  1165. new tizen.ApplicationControlData(
  1166. "http://tizen.org/appcontrol/data/social/item_type",
  1167. [ "person" ]),
  1168. new tizen.ApplicationControlData(
  1169. "http://tizen.org/appcontrol/data/social/item_id",
  1170. [ contact.personId ]) ]);
  1171. tizen.application.launchAppControl(appControl, null, function() {
  1172. log("contact: launch service succeeded");
  1173. }, function(e) {
  1174. handleError("contact: launch service failed. Reason: " + e);
  1175. });
  1176. log("#} createContact");
  1177. }
  1178. /*
  1179. * Calendar Manager
  1180. */
  1181. /**
  1182. * Use the Contact Application Control to add an event in the calendar with the
  1183. * corresponding date
  1184. */
  1185. function createCalendarEvent() {
  1186. var calendar = tizen.calendar.getDefaultCalendar("EVENT");
  1187. var date = new Date();
  1188. var event = new tizen.CalendarEvent({
  1189. description : "Mapo Event",
  1190. summary : "Mapo",
  1191. startDate : new tizen.TZDate(date.getFullYear().toString(), date
  1192. .getMonth().toString(), date.getDate().toString(), date
  1193. .getHours().toString(), date.getSeconds().toString()),
  1194. duration : new tizen.TimeDuration(1, "HOURS"),
  1195. location : 'Position: lat=' + $("#lat").val() + ' lon='
  1196. + $("#lon").val()
  1197. });
  1198. calendar.add(event);
  1199. var url = "http://tizen.org/appcontrol/operation/social/edit";
  1200. var appControl = new tizen.ApplicationControl(url, null, null, null, [
  1201. new tizen.ApplicationControlData(
  1202. "http://tizen.org/appcontrol/data/social/item_type",
  1203. [ "event" ]),
  1204. new tizen.ApplicationControlData(
  1205. "http://tizen.org/appcontrol/data/social/item_id",
  1206. [ event.id.uid ]) ]);
  1207. tizen.application.launchAppControl(appControl, "tizen.calendar",
  1208. function() {
  1209. log("success: " + url);
  1210. }, function(e) {
  1211. handleError("launch service failed. Reason: " + e);
  1212. });
  1213. }
  1214. /*
  1215. * Settings Manager
  1216. */
  1217. /**
  1218. * Function called when the online swith is activated or desactived Verify if
  1219. * the the device has a connection before connecting the application
  1220. */
  1221. function switchOnline() {
  1222. log("#{ switchOnline: " + isOnline);
  1223. log($('#switchOnline').val());
  1224. isOnline = ("online" === $('#switchOnline').val());
  1225. if (isOnline && !navigator.onLine)
  1226. log("connect system's wifi before");
  1227. if (isOnline) {
  1228. isReady = (null === OpenLayers);
  1229. if (!isReady || (null === gmaps)) {
  1230. download();
  1231. }
  1232. } else {
  1233. isReady = false;
  1234. }
  1235. refresh();
  1236. log("#} switchOnline: " + isOnline);
  1237. }
  1238. function switchDeveloper() {
  1239. isAdvanced = ("on" === $('#switchDeveloper').val());
  1240. var attribute = (isAdvanced) ? "visible" : "hidden";
  1241. $("#logView").css("visibility", attribute);
  1242. $("#recordView").css("visibility", attribute);
  1243. log("logging...");
  1244. }
  1245. /**
  1246. * Use the tactil swipe to change between every pages TODO : blink ?
  1247. */
  1248. function swipePage() {
  1249. $('div.ui-page').live("swipeleft", function() {
  1250. var nextpage = $(this).next('div[data-role="page"]');
  1251. // swipe using id of next page if exists
  1252. if (nextpage.length > 0) {
  1253. $.mobile.changePage(nextpage, {
  1254. transition : "slide",
  1255. reverse : false
  1256. });
  1257. }
  1258. });
  1259. $('div.ui-page').live("swiperight", function() {
  1260. var prevpage = $(this).prev('div[data-role="page"]');
  1261. // swipe using id of next page if exists
  1262. if (prevpage.length > 0) {
  1263. $.mobile.changePage(prevpage, {
  1264. transition : "slide",
  1265. reverse : true
  1266. });
  1267. }
  1268. });
  1269. }
  1270. function handleLoadedGmaps() {
  1271. log("#{ handleLoadedGmaps: + " + google);
  1272. gmaps = google;
  1273. isDownloaded = true;
  1274. refresh();
  1275. log("#} handleLoadedGmaps: + " + isDownloaded);
  1276. }
  1277. function downloadScriptsBody() {
  1278. log("#{ downloadScriptsBody: " + OpenLayers);
  1279. {
  1280. var element = document.createElement("script");
  1281. element.type = 'text/javascript';
  1282. element.src = url_openlayers;
  1283. document.body.appendChild(element);
  1284. }
  1285. {
  1286. var element = document.createElement("script");
  1287. element.type = 'text/javascript';
  1288. element.src = url_gmaps;
  1289. document.body.appendChild(element);
  1290. }
  1291. log("#} downloadScriptsBody: " + OpenLayers);
  1292. }
  1293. function download() {
  1294. log("#{ download: " + OpenLayers);
  1295. if (null == OpenLayers) {
  1296. $.getScript(url_openlayers, function() {
  1297. log("download:" + OpenLayers);
  1298. refresh();
  1299. $.getScript(url_gmaps, function() {
  1300. handleLoadedGmaps();
  1301. });
  1302. });
  1303. } else if (null == google) {
  1304. $.getScript(url_gmaps, function() {
  1305. handleLoadedGmaps();
  1306. });
  1307. } else {
  1308. handleLoadedGmaps();
  1309. }
  1310. // isLoaded = true; // TODO?
  1311. log("#} download: " + OpenLayers);
  1312. }
  1313. function initScripts() {
  1314. log("#{ initScripts: " + OpenLayers);
  1315. log("# isDownloaded=" + isDownloaded);
  1316. if (false === isDownloaded) {
  1317. download();
  1318. } else {
  1319. download();
  1320. refresh();
  1321. }
  1322. log("#} initScripts: " + OpenLayers);
  1323. }
  1324. /**
  1325. * Initialize the data from the preceding use
  1326. */
  1327. function start() {
  1328. log("#{ start: " + OpenLayers);
  1329. $("#picture").hide()
  1330. $("#capture").change(handleCapture);
  1331. initData();
  1332. initSettings();
  1333. initScripts();
  1334. switchDeveloper();
  1335. changeLat();
  1336. changeLon();
  1337. log(window.location.hash);
  1338. if (window.location.hash) {
  1339. setTag(window.location.hash);
  1340. } else {
  1341. setTimeout(getLocation, 4000);
  1342. }
  1343. // refresh();
  1344. if (false) { // TODO: buggy flash screen
  1345. swipePage();
  1346. }
  1347. // refresh();
  1348. log("#} start: " + OpenLayers);
  1349. }