lib.js 36 KB

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