lib.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  1. /*
  2. Copyright (c) 2013 Mapo developpers 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. // The map of the application
  19. var map;
  20. // The boolean which provide the connection state of the application
  21. var isOnline = false;
  22. /*
  23. * Recording Global Variable
  24. */
  25. // Directory where the recording document is placed
  26. var docDir;
  27. // Name of the recording document
  28. var doc;
  29. // The file where the records are placed
  30. var file;
  31. // Boolean which provide the information if a file has been recorded
  32. var fileRecorded = false;
  33. /*
  34. * Set Manager
  35. */
  36. /**
  37. * Modify the latitude value
  38. * @param lat : new latitude value
  39. */
  40. function setLat(lat) {
  41. if (document.getElementById("lat").value != lat) {
  42. document.getElementById("lat").value = lat;
  43. }
  44. }
  45. /**
  46. * Modify the longitude value
  47. * @param lon : new longitude value
  48. */
  49. function setLon(lon) {
  50. if (document.getElementById("lon").value != lon) {
  51. document.getElementById("lon").value = lon;
  52. }
  53. }
  54. /*
  55. * Link Manager
  56. */
  57. /**
  58. * Get the OpenStreetMap link with the corresponding latitude and longitude
  59. * @returns url
  60. */
  61. function getLink(provider) {
  62. var lat = $("#lat").val();
  63. var lon = $("#lon").val();
  64. var url;
  65. switch(provider)
  66. {
  67. case 'OSM' :
  68. url =
  69. "http://www.openstreetmap.org/?&zoom=10&layers=mapnik&lat=${lat}&lon=${lon}";
  70. break;
  71. case 'GM' :
  72. url = "http://maps.google.com/maps?&z=10&ll=${lat},${lon}";
  73. break;
  74. case 'NOKIA' :
  75. url = "http://maps.nokia.com/${lat},${lon},16,0,0,normal.day";
  76. break;
  77. default :
  78. url = "http://www.openstreetmap.org/?&zoom=10&layers=mapnik&lat=${lat}&lon=${lon}";
  79. break;
  80. }
  81. url = url.replace("${lon}", lon);
  82. url = url.replace("${lat}", lat);
  83. return url;
  84. }
  85. /**
  86. * Use the Internet Application Control to go to OSM link with the browser
  87. */
  88. function goToURL(provider) {
  89. if (isOnline) {
  90. var appControl = new tizen.ApplicationControl(
  91. "http://tizen.org/appcontrol/operation/view",
  92. getLink(provider), null);
  93. var appControlReplyCallback = {
  94. onsuccess : function(data) {
  95. for ( var i = 0; i < data.length; i++) {
  96. console.log("#" + i + " key:" + data[i].key);
  97. for ( var j = 0; j < data[i].value.length; j++) {
  98. console.log(" value#" + j + ":" + data[i].value[j]);
  99. }
  100. }
  101. },
  102. onfailure : function() {
  103. console.log('The launch application control failed');
  104. }
  105. }
  106. tizen.application.launchAppControl(appControl, null, function() {
  107. console.log("launch internet application control succeed");
  108. }, function(e) {
  109. console.log("launch internet application control failed. reason: "
  110. + e.message);
  111. }, appControlReplyCallback);
  112. } else {
  113. alert("Please connect your application online in the settings"
  114. + " if you want to open a browser")
  115. }
  116. }
  117. /**
  118. * update links
  119. */
  120. //function updateLinks() {
  121. // $('#OSMLink').attr('href', getOSMLink());
  122. //}
  123. /*
  124. * Map Manager
  125. */
  126. /**
  127. * get the size of the map (width, height) according to the dimension of the screen
  128. * @returns [ width, height ]
  129. */
  130. function getMapSize() {
  131. var viewHeight = $(window).height();
  132. var viewWidth = $(window).width();
  133. var header = $("div[data-role='header']:visible:visible");
  134. var footer = $("div[data-role='footer']:visible:visible");
  135. var navbar = $("div[data-role='navbar']:visible:visible");
  136. var content = $("div[data-role='content']:visible:visible");
  137. var contentHeight = viewHeight - header.outerHeight()
  138. - navbar.outerHeight() - footer.outerHeight();
  139. var contentWidth = viewWidth - 30;
  140. return [ contentWidth, contentHeight ];
  141. }
  142. /**
  143. * Modify the dimension of the map according to getMapSize()
  144. */
  145. function setMapSize() {
  146. var mapSize = getMapSize();
  147. $('#myMap').css("width", mapSize[0]);
  148. $('#myMap').css("height", mapSize[1]);
  149. }
  150. function initIcon(){
  151. var size = new OpenLayers.Size(21,25);
  152. var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
  153. return new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png', size, offset);
  154. }
  155. function chargeCourse(data){
  156. log("chargeCourse data : "+data['dates'][0]);
  157. var icon = initIcon();
  158. log("tab lons = "+data['lons']);
  159. log("tab lats = "+data['lats']);
  160. log("tab dates = "+data['dates']);
  161. for(var i= 0; i<data['dates'].length; i++){
  162. var lon = parseFloat(data['lons'][i]);
  163. var lat = parseFloat(data['lats'][i]);
  164. var date = data['dates'][i];
  165. log("data['dates']["+i+"] = "+date);
  166. log("data['lons']["+i+"] = "+lon);
  167. log("data['lat']["+i+"] = "+lat);
  168. log("lat before : "+lat);
  169. log("lon before : "+lon);
  170. var lonlat = new OpenLayers.LonLat(lon,lat).transform('EPSG:4326', 'EPSG:3857');
  171. var mark = new OpenLayers.Marker(lonlat,icon);
  172. course.addMarker(mark);
  173. }
  174. map.addLayer(course);
  175. log("finito");
  176. }
  177. /**
  178. * Charge the OpenLayers map with different OpenStreetMap and Google maps' layers
  179. */
  180. function chargeMap() {
  181. var latCenter = $("#lat").val();
  182. var lonCenter = $("#lon").val();
  183. map = new OpenLayers.Map('myMap', {
  184. projection : 'EPSG:3857',
  185. layers : [ new OpenLayers.Layer.OSM("OpenStreetMap"),
  186. new OpenLayers.Layer.Google("Google Streets",
  187. {numZoomLevels:20}),
  188. new OpenLayers.Layer.Google("Google Physical",
  189. {type : google.maps.MapTypeId.TERRAIN}),
  190. new OpenLayers.Layer.Google("Google Hybrid",
  191. {type : google.maps.MapTypeId.HYBRID,numZoomLevels : 20}),
  192. new OpenLayers.Layer.Google("Google Satellite",
  193. {type : google.maps.MapTypeId.SATELLITE,numZoomLevels : 22})
  194. ],
  195. center : new OpenLayers.LonLat(lonCenter, latCenter).transform('EPSG:4326', 'EPSG:3857'),
  196. zoom : 7
  197. });
  198. map.addControl(new OpenLayers.Control.LayerSwitcher());
  199. if(fileRecorded){ // TODO : Data vide : data([0])?.length!=0 or fileRecorded
  200. //var course = new OpenLayers.Layer.Markers( "Latest recorded course" );
  201. //map.removeLayer(course);
  202. var markers = map.getLayersByName("Last recorded course");
  203. if(markers.length!=0){
  204. var previousCourse = markers[0];
  205. log("course = "+previousCourse.name);
  206. previousCourse.destroy();
  207. }
  208. course = new OpenLayers.Layer.Markers("Last recorded course");
  209. //readFile().done(chargeCourse);
  210. readFile();
  211. // setTimeout(
  212. //// log("result 0 : "+result[0]);
  213. //// log("result 1 : "+result[1]);
  214. // chargeCourse
  215. // , 5000);
  216. }
  217. }
  218. /*
  219. * Coordinates transformation Manager
  220. */
  221. /**
  222. * Transform the latitude/longitude into DMS coordinate
  223. * @param lat : latitude
  224. * @param lon : longitude
  225. * @returns dms : DMS coordinate
  226. */
  227. function fromLatLonToDMS(lat, lon) {
  228. var latitude = lat;
  229. var longitude = lon;
  230. var dms="";
  231. var NS="";
  232. if (latitude >= 0) {
  233. NS += "N";
  234. } else {
  235. latitude = -latitude;
  236. NS += "S";
  237. }
  238. var dLat = parseInt(latitude, 10);
  239. var mLat = parseInt((latitude - dLat) * 60, 10);
  240. var sLat = parseInt((latitude-dLat)*60*60 - 60*mLat, 10);
  241. dms += NS+" "+dLat+"° "+mLat+"' "+sLat+"\" ";
  242. var EW="";
  243. if (longitude >= 0) {
  244. EW += "E";
  245. } else {
  246. EW += "W";
  247. longitude = -longitude;
  248. }
  249. var dLon = parseInt(longitude, 10);
  250. var mLon = parseInt((longitude - dLon) * 60, 10);
  251. var sLon = parseInt((longitude-dLon)*60*60 - 60*mLon, 10);
  252. dms += EW+" "+dLon+"° "+mLon+"' "+sLon+"\"";
  253. // text = NS+" "+d+"° "+m+"' "+s+"\" "+EW+" "+d+"° "+m+"' "+s+"\"";
  254. return dms;
  255. }
  256. /**
  257. * Transform the DMS into latitude/longitude coordinates
  258. * @param dms : DMS coordinate
  259. * @returns [ lat, lon ] : latitude and longitude coordinates
  260. */
  261. function fromDMSToLatLon(dms){
  262. var re =
  263. /^([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*$/;
  264. if(re.test(dms)){
  265. var lat = (parseFloat(RegExp.$2)+parseFloat(RegExp.$3)/60+parseFloat(RegExp.$4)/(60*60)).toFixed(6);
  266. if(RegExp.$1=='S'){
  267. lat=-lat;
  268. }
  269. lat = lat.toString();
  270. setLat(lat);
  271. var lon = (parseFloat(RegExp.$6)+parseFloat(RegExp.$7)/60+parseFloat(RegExp.$8)/(60*60)).toFixed(6);
  272. if(RegExp.$5=='W'){
  273. lon=-lon;
  274. }
  275. lon = lon.toString();
  276. setLon(lon);
  277. }
  278. }
  279. /*
  280. * Coordinates Manager
  281. */
  282. /**
  283. * Modify the DMS value using the transformation's function fromLatLonToDMS
  284. */
  285. function setDMS() {
  286. $('#dms').val(fromLatLonToDMS($("#lat").val(), $("#lon").val()));
  287. }
  288. /**
  289. * Modify the latitude and longitude values using the transformation's function fromDMSToLatLon
  290. */
  291. function setLatLon(){
  292. var coordinates = fromDMSToLatLon($('#dms').val());
  293. }
  294. /**
  295. * Validate or not the DMS coordinate according to the form of the regular expression
  296. * @param dms : DMS coordinates
  297. * @returns Validation
  298. */
  299. function validateDMS(dms){
  300. var re =
  301. /^([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*$/;
  302. if (re.test(dms)) {
  303. return true;
  304. } else {
  305. return false;
  306. }
  307. }
  308. /**
  309. * Validate or not the latitudes and longitudes coordinates according to the form of the regular expression
  310. * @param latOrLon
  311. * @returns Validation
  312. */
  313. function validateLatOrLon(latOrLon){
  314. if(/^[0-9.\-]+$/.test(latOrLon)){
  315. return true;
  316. } else {
  317. return false;
  318. }
  319. }
  320. /**
  321. * Function called when the latitude value changes
  322. * Calculate the new DMS coordinate
  323. */
  324. function changeLat(){
  325. var lat = $('#lat').val();
  326. if(validateLatOrLon(lat)){
  327. $('#lat').val(parseFloat($('#lat').val()).toFixed(6).toString());
  328. setDMS();
  329. storeData();
  330. } else {
  331. alert("Latitude coordinate invalid : "+lat);
  332. initData();
  333. }
  334. }
  335. /**
  336. * Function called when the longitude value changes
  337. * Calculate the new DMS coordinate
  338. */
  339. function changeLon(){
  340. var lon = $('#lon').val();
  341. if(validateLatOrLon(lon)){
  342. $('#lon').val(parseFloat($('#lon').val()).toFixed(6).toString());
  343. setDMS();
  344. storeData();
  345. } else {
  346. alert("Lontitude coordinate invalid : "+lon);
  347. initData();
  348. }
  349. }
  350. /**
  351. * Function called when the DMS value changes
  352. * Calculate the new latitude and longitude coordinates
  353. */
  354. function changeDMS(){
  355. var dms = $('#dms').val();
  356. if(validateDMS(dms)){
  357. setLatLon();
  358. storeData();
  359. } else {
  360. alert("DMS coordinate invalid : "+dms);
  361. initData();
  362. }
  363. }
  364. /*
  365. * Location Manager
  366. */
  367. /**
  368. * Function called when the getCurrentPosition succeded
  369. * Refresh the application
  370. */
  371. function handleShowLocation(position) {
  372. var lat = position.coords.latitude.toFixed(6).toString();
  373. var lon = position.coords.longitude.toFixed(6).toString();
  374. setLat(lat);
  375. setLon(lon);
  376. refresh();
  377. }
  378. /**
  379. * Function called when the getCurrentPosition failed
  380. * Show the error
  381. * @param error
  382. */
  383. function handleErrorLocation(error) {
  384. var errorInfo = document.getElementById("locationInfo");
  385. switch (error.code) {
  386. case error.PERMISSION_DENIED:
  387. errorInfo.innerHTML = "User denied the request for Geolocation.";
  388. break;
  389. case error.POSITION_UNAVAILABLE:
  390. errorInfo.innerHTML = "Location information is unavailable.";
  391. break;
  392. case error.TIMEOUT:
  393. errorInfo.innerHTML = "The request to get user location timed out.";
  394. break;
  395. case error.UNKNOWN_ERROR:
  396. errorInfo.innerHTML = "An unknown error occurred.";
  397. break;
  398. }
  399. }
  400. /**
  401. * Get the current position according to the GPS' device
  402. */
  403. function getLocation() {
  404. if (navigator.geolocation ) {
  405. navigator.geolocation.getCurrentPosition(handleShowLocation, handleErrorLocation,
  406. {enableHighAccuracy : $('#switchEnergy').val() == 'off'});
  407. } else {
  408. document.getElementById("locationInfo").innerHTML =
  409. "Geolocation is not supported by this browser.";
  410. }
  411. }
  412. /*
  413. * Recording manager
  414. */
  415. /**
  416. * Function called when the file resolution succeded
  417. * Create the recording file in the corresponding directory
  418. * @param dir : directory where the file is placed
  419. */
  420. function handleResolveSuccess(dir) {
  421. docDir = dir;
  422. var date = new Date();
  423. var dateFile = date.getDate().toString()+"."+date.getMonth().toString()+"."+date.getFullYear().toString()
  424. +"-"+date.getHours().toString()+":"+date.getMinutes().toString()+":"+date.getSeconds().toString();
  425. //log(dateFile);
  426. doc = 'MAPO_' + dateFile + ".txt";
  427. docDir.createFile(doc);
  428. $('#locationInfo').html("Course recording in the file:<br/>" + doc);
  429. }
  430. /**
  431. * Function called when the file resolution failed
  432. * Show the error
  433. * @param e : error
  434. */
  435. function handleResolveError(e) {
  436. console.log('message: ' + e.message);
  437. }
  438. /**
  439. * Resolve the file
  440. */
  441. function resolveFile() {
  442. try {
  443. file = docDir.resolve(doc);
  444. } catch (exc) {
  445. console.log('Could not resolve file: '+exc.message);
  446. // Stop in case of any errors
  447. return;
  448. }
  449. }
  450. /**
  451. * Function called when the record failed, writing or reading
  452. * Show the error
  453. * @param e : error
  454. */
  455. function handleRecordError(e) {
  456. var msg = '';
  457. switch (e.code) {
  458. case FileError.QUOTA_EXCEEDED_ERR:
  459. msg = 'QUOTA_EXCEEDED_ERR';
  460. break;
  461. case FileError.NOT_FOUND_ERR:
  462. msg = 'NOT_FOUND_ERR';
  463. break;
  464. case FileError.SECURITY_ERR:
  465. msg = 'SECURITY_ERR';
  466. break;
  467. case FileError.INVALID_MODIFICATION_ERR:
  468. msg = 'INVALID_MODIFICATION_ERR';
  469. break;
  470. case FileError.INVALID_STATE_ERR:
  471. msg = 'INVALID_STATE_ERR';
  472. break;
  473. default:
  474. msg = 'Unknown Error';
  475. break;
  476. }
  477. console.log('Error: ' + msg);
  478. }
  479. /**
  480. * Function called when the writing succeeded
  481. * Add the position at the end of the file
  482. * @param fileStream : Stream to write
  483. */
  484. function writeToStream(fileStream) {
  485. try {
  486. var date = new Date();
  487. var dateRecord = date.getDate().toString()+"."+date.getMonth().toString()+"."+date.getFullYear().toString()
  488. +"-"+date.getHours().toString()+":"+date.getMinutes().toString()+":"+date.getSeconds().toString();
  489. // var dateRecord = date.getDate().toString()+"."+date.getMonth().toString()+"."+date.getFullYear().toString()
  490. // +"-"+date.getHours().toString()+":"+date.getMinutes().toString()+":"+date.getSeconds().toString();
  491. var lat = $("#lat").val();
  492. var lon = $("#lon").val();
  493. //fileStream.write(dateRecord + ";lat:" + lat + ";lon:" + lon + "\r");
  494. fileStream.write("\r"+dateRecord+";"+lat+";"+lon);
  495. fileStream.close();
  496. } catch (exc) {
  497. console.log('Could not write to file: ' + exc.message);
  498. }
  499. }
  500. /**
  501. * Try to write the record into the file
  502. */
  503. function writeRecord() {
  504. try {
  505. file.openStream(
  506. // open for appending
  507. 'a',
  508. // success callback - add textarea's contents
  509. writeToStream,
  510. // error callback
  511. handleRecordError);
  512. } catch (exc) {
  513. console.log('Could not write to file: ' + exc.message);
  514. }
  515. }
  516. /**
  517. * Function called when the reading succeded
  518. * @param fileStream : Stream to read
  519. */
  520. function readFromStream(fileStream) {
  521. try {
  522. console.log('File size: ' + file.fileSize);
  523. var contents = fileStream.read(fileStream.bytesAvailable);
  524. fileStream.close();
  525. console.log('file contents: ' + contents);
  526. } catch (exc) {
  527. console.log('Could not read from file: ' + exc.message);
  528. }
  529. }
  530. /**
  531. * Try to read the file
  532. */
  533. function readRecord() {
  534. try {
  535. file.openStream(
  536. // open for reading
  537. 'r',
  538. // success callback - add textarea's contents
  539. readFromStream,
  540. // error callback
  541. handleRecordError);
  542. } catch (exc) {
  543. console.log('Could not write to file: ' + exc.message);
  544. }
  545. }
  546. /**
  547. * Function called when getPosition got successfully the position
  548. * Resolve the file, write and read the records
  549. * @param position
  550. */
  551. function handleRecordPosition(position) {
  552. if ($('#switchRecord').val() == "start") {
  553. handleShowLocation(position);
  554. resolveFile();
  555. writeRecord();
  556. readRecord();
  557. }
  558. }
  559. /**
  560. * Function called when getPosition failed to get the position
  561. * Show the error
  562. * @param error
  563. */
  564. function handleErrorPosition(error) {
  565. $('#switchRecord').val('stop').slider('refresh');
  566. var errorInfo = document.getElementById("locationInfo");
  567. switch (error.code) {
  568. case error.PERMISSION_DENIED:
  569. errorInfo.innerHTML = "User denied the request for Geolocation.";
  570. break;
  571. case error.POSITION_UNAVAILABLE:
  572. errorInfo.innerHTML = "Location information is unavailable.";
  573. break;
  574. case error.TIMEOUT:
  575. errorInfo.innerHTML = "The request to get user location timed out.";
  576. break;
  577. case error.UNKNOWN_ERROR:
  578. errorInfo.innerHTML = "An unknown error occurred.";
  579. break;
  580. }
  581. }
  582. /**
  583. * Get the recording position
  584. */
  585. function getPosition() {
  586. navigator.geolocation.getCurrentPosition(handleRecordPosition, handleErrorPosition,
  587. {enableHighAccuracy : $('#switchEnergy').val() == 'off'});
  588. }
  589. /**
  590. * Function called when the record of a course has been launched
  591. * Record the position whith a timeout predefined in the settings
  592. */
  593. function record() {
  594. if (navigator.geolocation) {
  595. var intervalID;
  596. if ($('#switchRecord').val() == "start") {
  597. tizen.filesystem.resolve('documents', handleResolveSuccess,
  598. handleResolveError, 'rw');
  599. getPosition();
  600. intervalID = setInterval(getPosition, $('#selectorTimeout').val() * 1000);
  601. } else {
  602. clearInterval(intervalID);
  603. $('#locationInfo').html("Course recorded in the file:<br/>" + doc);
  604. fileRecorded=true;
  605. }
  606. } else {
  607. document.getElementById("locationInfo").innerHTML =
  608. "Geolocation is not supported.";
  609. }
  610. }
  611. /**
  612. * Extract from a file composed by the last recorded course all the dates, latitudes and lontitudes
  613. * and place its in data
  614. */
  615. function readFile() {
  616. //var deferred = $.Deferred();
  617. try {
  618. file = docDir.resolve(doc);
  619. console.log('File size: ' + file.fileSize);
  620. } catch (exceptionResolve) {
  621. console.log('Could not resolve file: ' + exceptionResolve.message);
  622. // Stop in case of any errors
  623. return;
  624. }
  625. try {
  626. file.readAsText(
  627. // success callback - display the contents of the file
  628. function(contents) {
  629. //console.log('File contents:' + contents);
  630. var lines = contents.split("\r");
  631. var re = /^([0-9.:\-]+);([0-9.\-]+);([0-9.\-]+)$/;
  632. var data = [];
  633. var dates = [];
  634. var lats = [];
  635. var lons = [];
  636. var iData = 0;
  637. for(var iLines=0; iLines<lines.length; iLines++){
  638. if(re.test(lines[iLines])) {
  639. log("line "+iLines+": "+lines[iLines]);
  640. var parts = lines[iLines].split(";");
  641. for(var iParts=0; iParts<parts.length; iParts++){
  642. log(" part "+iParts+": "+parts[iParts]);
  643. if((iParts%3)==0){
  644. dates[iData]=parts[iParts];
  645. log(" date "+iData+": "+dates[iData]);
  646. } else if((iParts%3)==1) {
  647. lats[iData]=parts[iParts];
  648. log(" lat "+iData+": "+lats[iData]);
  649. } else {
  650. lons[iData]=parts[iParts];
  651. log(" lon "+iData+": "+lons[iData]);
  652. }
  653. }
  654. iData++;
  655. }
  656. }
  657. data['dates'] = dates;
  658. data['lats'] = lats;
  659. data['lons'] = lons;
  660. log("readfile data"+data['dates'][0]);
  661. chargeCourse(data);
  662. },
  663. // error callback
  664. handleRecordError
  665. );
  666. } catch (exceptionRead) {
  667. console.log("readAsText() exception:" + exceptionRead.message);
  668. }
  669. //deferred.resolve();
  670. //return deferred; // [data, referred]
  671. }
  672. /*
  673. * Social Manager
  674. */
  675. /**
  676. * Use the Email Application Control to share a position by Email
  677. */
  678. function sendEmail() {
  679. if (isOnline) {
  680. var message =
  681. "This is the position I want to show you from Mapo:" +
  682. "\nLatitute="+$("#lat").val()+
  683. "\nLongitude = "+$("#lon").val()+
  684. "\nIf you prefer in DMS, here it is: "+$('#dms').val()+
  685. "\nYou can see this position on OpenStreetMap: "+getLink('OSM')+
  686. "\nConnect you on Mapo for more details!";
  687. var appControl = new tizen.ApplicationControl(
  688. "http://tizen.org/appcontrol/operation/send", // compose or send
  689. "mailto:", null, null,
  690. [
  691. new tizen.ApplicationControlData(
  692. "http://tizen.org/appcontrol/data/subject", [ "Mapo" ]),
  693. new tizen.ApplicationControlData(
  694. "http://tizen.org/appcontrol/data/text", [ message ]),
  695. new tizen.ApplicationControlData(
  696. "http://tizen.org/appcontrol/data/to",
  697. [ "mapo.tizen@gmail.com" ])
  698. // TODO tizen.mapo@spamgourmet.com
  699. // new tizen.ApplicationControlData(
  700. // "http://tizen.org/appcontrol/data/path",
  701. // ["images/image1.jpg"])
  702. ]);
  703. tizen.application.launchAppControl(appControl, null,
  704. function() {console.log("launch service succeeded");},
  705. function(e) {
  706. console.log("launch service failed. Reason: " + e.name);});
  707. } else {
  708. alert("Please connect your application online in the settings"
  709. + " if you want to send an email");
  710. }
  711. }
  712. //function sendBluetooth(){
  713. // var appControl = new tizen.ApplicationControl(
  714. // "http://tizen.org/appcontrol/operation/pick",
  715. // null,
  716. // "image/jpeg",
  717. // null);
  718. //
  719. // tizen.application.launchAppControl(appControl, null,
  720. // function() {console.log("launch service succeeded");},
  721. // function(e) {
  722. // console.log("launch service failed. Reason: " + e.name);});
  723. // var appControlReplyCallback = {
  724. // // callee sent a reply
  725. // onsuccess: function(data) {
  726. // for (var i = 0; i < data.length; i++) {
  727. // if (data[i].key == "http://tizen.org/appcontrol/data/selected") {
  728. // console.log('Selected image is ' + data[i].value[0]);
  729. // }
  730. // }
  731. // },
  732. // // callee returned failure
  733. // onfailure: function() {
  734. // console.log('The launch application control failed');
  735. // }
  736. // }
  737. //
  738. // tizen.application.launchAppControl(
  739. // appControl,
  740. // null,
  741. // function() {console.log("launch application control succeed"); },
  742. // function(e) {console.log("launch application control failed. reason: "+e.message); },
  743. // appControlReplyCallback );
  744. // tizen.application.launch("tizen.bluetooth",
  745. // function(){console.log("launch service succeeded");},
  746. // function(e){console.log("launch service failed. Reason: " + e.name);});
  747. // var appControl = new
  748. // tizen.ApplicationControl("http://tizen.org/appcontrol/operation/bluetooth/pick",
  749. // "Phone/Images/image16.jpg");
  750. // tizen.application.launchAppControl(appControl, null,
  751. // function(){console.log("launch service succeeded");},
  752. // function(e){console.log("launch service failed. Reason: " + e.name);});
  753. //}
  754. function sendMessage(){
  755. var message =
  756. "This is the position I want to show you from Mapo:" +
  757. "\nLatitute="+$("#lat").val()+
  758. "\nLongitude = "+$("#lon").val()+
  759. "\nIf you prefer in DMS, here it is: "+$('#dms').val()+
  760. "\nYou can see this position on OpenStreetMap: "+getLink('OSM')+
  761. "\nConnect you on Mapo for more details!";
  762. var appControl = new tizen.ApplicationControl(
  763. "http://tizen.org/appcontrol/operation/compose",
  764. "tel:9988776655", // tizen.smsmessages
  765. null,
  766. null,
  767. [
  768. new tizen.ApplicationControlData("http://tizen.org/appcontrol/data/messagetype",["sms"]),
  769. new tizen.ApplicationControlData("http://tizen.org/appcontrol/data/text",[message]),
  770. new tizen.ApplicationControlData("http://tizen.org/appcontrol/data/to", ["2345678900"]),
  771. ]
  772. );
  773. tizen.application.launchAppControl(appControl, null,
  774. function() {console.log("launch service succeeded");},
  775. function(e) {console.log("launch service failed. Reason: "+e);});
  776. }
  777. function call(){
  778. var appControl = new tizen.ApplicationControl("http://tizen.org/appcontrol/operation/dial","tel:9988776655", null);
  779. tizen.application.launchAppControl(appControl,null,
  780. function(){console.log("launch appControl succeeded");},
  781. function(e){console.log("launch appControl failed. Reason: " + e.name);},
  782. null);
  783. }
  784. /*
  785. * Contact Manager
  786. */
  787. /**
  788. * Use the Contact Application Control to add a contact with the corresponding position
  789. */
  790. function createContact() {
  791. var appControl = new tizen.ApplicationControl(
  792. "http://tizen.org/appcontrol/operation/social/add",
  793. null,
  794. null,
  795. //TODO
  796. // null for the emulator
  797. // "vnd.tizen.item.type/vnd.tizen.contact" for the device
  798. "vnd.tizen.item.type/vnd.tizen.contact",
  799. [
  800. new tizen.ApplicationControlData(
  801. "http://tizen.org/appcontrol/data/social/item_type",
  802. [ "contact" ]),
  803. new tizen.ApplicationControlData(
  804. "http://tizen.org/appcontrol/data/social/email",
  805. [ "mapo.tizen+"+
  806. fromLatLonToDMS($('#lat').val(), $('#lon').val()) + "@gmail.com" ]),
  807. new tizen.ApplicationControlData(
  808. "http://tizen.org/appcontrol/data/social/url",
  809. [ getLink('OSM') ])
  810. ]);
  811. tizen.application.launchAppControl(appControl, null,
  812. function() {console.log("launch service succeeded");},
  813. function(e) {console.log(
  814. "launch service failed. Reason: " +e.name+e);});
  815. }
  816. /*
  817. * Calendar Manager
  818. */
  819. /**
  820. * Use the Contact Application Control to add an event in the calendar with the corresponding date
  821. */
  822. function createCalendarEvent(){
  823. var appControl = new tizen.ApplicationControl(
  824. "http://tizen.org/appcontrol/operation/social/edit",
  825. null,
  826. null,
  827. "tizen.calendar",
  828. [
  829. new tizen.ApplicationControlData(
  830. "http://tizen.org/appcontrol/data/social/item_type",
  831. [ "event" ])
  832. ]);
  833. tizen.application.launchAppControl(appControl, null,
  834. function() {console.log("launch service succeeded");},
  835. function(e) {console.log(
  836. "launch service failed. Reason: " +e.name+e);});
  837. }
  838. /*
  839. * Storage Manager
  840. */
  841. /**
  842. * Store the coordinates values in the local storage
  843. */
  844. function storeData(){
  845. localStorage.setItem('lat', $('#lat').val());
  846. localStorage.setItem('lon', $('#lon').val());
  847. localStorage.setItem('dms', $('#dms').val());
  848. }
  849. /**
  850. * Store the settings values in the local storage
  851. */
  852. function storeSettings() {
  853. localStorage.setItem('connection', $('#switchOnline').val());
  854. localStorage.setItem('energySaving', $('#switchEnergy').val());
  855. localStorage.setItem('timeout', $('#selectorTimeout').val());
  856. }
  857. function store() {
  858. var r = $.Deferred();
  859. storeData();
  860. storeSettings();
  861. for ( var i = 0; i < localStorage.length; i++) {
  862. log(i+" -- "+localStorage.key(i)+" : "+localStorage.getItem(localStorage.key(i)));
  863. }
  864. r.resolve();
  865. return r;
  866. }
  867. /*
  868. * Settings Manager
  869. */
  870. /**
  871. * Function called when the online swith is activated or desactived
  872. * Verify if the the device has a connection before connecting the application
  873. */
  874. function switchOnline() {
  875. if (!isOnline) {
  876. if (navigator.onLine) {
  877. isOnline = true;
  878. } else {
  879. $('#switchOnline').val('offline');
  880. $('#switchOnline').slider('refresh');
  881. alert("Can not connect");
  882. }
  883. } else {
  884. isOnline = false;
  885. }
  886. refresh();
  887. }
  888. /*
  889. * General Manager
  890. */
  891. /**
  892. * Refresh all the application according to the coordinates and the settings
  893. */
  894. function refresh() {
  895. log("{refresh");
  896. if (isOnline && !navigator.onLine) {
  897. $('#switchOnline').val('offline').slider('refresh');
  898. isOnline = false;
  899. alert("Connection lost");
  900. }
  901. //setDMS();
  902. $('#myMap').empty();
  903. log("isOnline = "+isOnline);
  904. if (isOnline) {
  905. setMapSize();
  906. chargeMap();
  907. } else {
  908. $('#myMap').html(
  909. "<p align='center'>" +
  910. "Please connect your application online in the settings" +
  911. " if you want to charge the map</p>");
  912. }
  913. log("refresh}");
  914. }
  915. /**
  916. * Quit the application
  917. */
  918. function exit() {
  919. tizen.application.getCurrentApplication().exit();
  920. }
  921. /**
  922. * Store the data before quitting the application
  923. */
  924. function quit() {
  925. log("{exit")
  926. store().done(exit);
  927. log("exit}");
  928. }
  929. /*
  930. * Initialization Manager
  931. */
  932. /**
  933. * Recover in the local storage the coordinates values from the preceding use
  934. */
  935. function initData(){
  936. if (localStorage.getItem('lat') != null) {
  937. $('#lat').val(localStorage.getItem('lat'));
  938. }
  939. if (localStorage.getItem('lon') != null) {
  940. $('#lon').val(localStorage.getItem('lon'));
  941. }
  942. if (localStorage.getItem('dms') != null) {
  943. $('#dms').val(localStorage.getItem('dms'));
  944. }
  945. storeData();
  946. }
  947. /**
  948. * Recover in the local storage the setting values from the preceding use
  949. */
  950. function initSettings() {
  951. if (localStorage.getItem('connection') == 'online') {
  952. $('#switchOnline').val(localStorage.getItem('connection'));
  953. isOnline = true;
  954. }
  955. if (localStorage.getItem('energySaving') != null) {
  956. $('#switchEnergy').val(localStorage.getItem('energySaving'));
  957. }
  958. if (localStorage.getItem('timeout') != null) {
  959. $('#selectorTimeout').attr('value', localStorage.getItem('timeout'));
  960. }
  961. storeSettings();
  962. }
  963. /**
  964. * Initialize the data from the preceding use
  965. */
  966. function init(){
  967. initData();
  968. initSettings();
  969. refresh();
  970. }
  971. /*
  972. * Schedule
  973. */
  974. /**
  975. * Show a message
  976. * @param message
  977. */
  978. function log(message) {
  979. if (!false) console.log("# "+message);
  980. }
  981. /**
  982. * Use the tactil swipe to change between every pages
  983. */
  984. function swipePage() {
  985. $('div.ui-page').live("swipeleft",
  986. function() {
  987. var nextpage = $(this).next('div[data-role="page"]');
  988. // swipe using id of next page if exists
  989. if (nextpage.length > 0) {
  990. $.mobile.changePage(nextpage,
  991. {transition : "slide", reverse : false});
  992. }});
  993. $('div.ui-page').live("swiperight",
  994. function() {
  995. var prevpage = $(this).prev('div[data-role="page"]');
  996. // swipe using id of next page if exists
  997. if (prevpage.length > 0) {
  998. $.mobile.changePage(prevpage,
  999. {transition : "slide", reverse : true});
  1000. }});
  1001. }