12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505 |
- /*
- Copyright (c) 2013 Mapo developers and contributors <mapo.tizen@gmail.com>
- This file is part of Mapo.
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
- /*
- * Application Global variables
- */
- var web = "http://notabug.org/tizen/mapo";
- web = "http://rzr.github.io/";
- var gEmail = "mapo.tizen@gmail.com";
- // The map of the application
- var map = null;
- // The boolean which provide the connection state of the application
- var isReady = true;
- var isAdvanced = false;
- var isOnline = navigator.onLine;
- var isLoaded = false;
- var isDownloaded = false;
- var gLocationDate = null;
- /*
- * Recording Global Variable
- */
- // Directory where the recording document is placed
- var docDir;
- // Name of the recording document
- var doc;
- // The file where the records are placed
- var file;
- // Boolean which provide the information if a file has been recorded
- var fileRecorded = false;
- var url_openlayers = "http://openlayers.org/api/OpenLayers.js";
- // var url_gmaps = "http://maps.google.com/maps/api/js?v=3.2&sensor=false";
- var url_gmaps = 'http://maps.googleapis.com/maps/api/js?v=3.2&signed_in=true&callback=handleLoadedGmaps';
- /*
- * General Manager
- */
- /**
- * Quit the application
- */
- function exit() {
- if ('undefined' !== typeof (tizen)) {
- tizen.application.getCurrentApplication().exit();
- } else {
- log("exit:");
- }
- }
- /**
- * Show a message
- *
- * @param message
- */
- function log(message) {
- var text = "# ";
- try {
- var json = JSON.stringify(message);
- text += json;
- } catch (e) {
- text += "not json: " + message;
- }
- if (isAdvanced) {
- console.log(text);
- var element = document.getElementById("console");
- element.innerHTML += "<pre>" + text + "</pre>";
- }
- }
- function logMap(data) {
- for (i = 0; i < data.length; i++) {
- log("#" + i + " key:" + data[i].key);
- for (j = 0; j < data[i].value.length; j++) {
- log(" value#" + j + ":" + data[i].value[j]);
- }
- }
- }
- // upstream: https://gist.github.com/kamranzafar/3136584#comment-1244934
- function toast(message, delay) {
- if (typeof (b) === 'undefined') {
- delay = 2000;
- }
- var $toast = $('<div class="ui-loader ui-overlay-shadow ui-body-e ui-corner-all"><h3>'
- + message + '</h3></div>');
- $toast.css({
- display : 'block',
- background : '#fff',
- opacity : 0.90,
- position : 'fixed',
- padding : '7px',
- 'text-align' : 'center',
- width : '270px',
- left : ($(window).width() - 284) / 2,
- top : $(window).height() / 2 - 20
- });
- var removeToast = function() {
- $(this).remove();
- };
- $toast.click(removeToast);
- $toast.appendTo($.mobile.pageContainer).delay(delay);
- $toast.fadeOut(400, removeToast);
- }
- function handleError(message) {
- message = "error: " + message;
- log(message);
- toast(message);
- return message;
- }
- function handleException(e) {
- return handleError(e.name);
- }
- function handleSuccess() {
- return log("success: ");
- }
- function handleFailure() {
- return log("failure: ");
- }
- /*
- /*
- * Storage Manager
- */
- /**
- * Store the coordinates values in the local storage
- */
- function storeData() {
- localStorage.setItem('lat', $('#lat').val());
- localStorage.setItem('lon', $('#lon').val());
- localStorage.setItem('dms', $('#dms').val());
- }
- /**
- * Store the settings values in the local storage
- */
- function storeSettings() {
- log("#{ storeSettings: " + isOnline);
- localStorage.setItem('connection', $('#switchOnline').val());
- localStorage.setItem('energySaving', $('#switchEnergy').val());
- localStorage.setItem('timeout', $('#selectorTimeout').val());
- localStorage.setItem('downloaded', isDownloaded);
- log("#} storeSettings: " + isOnline);
- }
- function store() {
- var i = 0;
- var r = $.Deferred();
- storeData();
- storeSettings();
- for (i = 0; i < localStorage.length; i++) {
- log(i + " -- " + localStorage.key(i) + " : "
- + localStorage.getItem(localStorage.key(i)));
- }
- r.resolve();
- return r;
- }
- /**
- * Store the data before quitting the application
- */
- function quit() {
- log("#{ exit");
- store().done(exit);
- log("#} exit");
- }
- /*
- * Set Manager
- */
- /**
- * Modify the latitude value
- *
- * @param lat :
- * new latitude value
- */
- function setLat(lat) {
- if (document.getElementById("lat").value !== lat) {
- document.getElementById("lat").value = lat;
- }
- }
- /**
- * Modify the longitude value
- *
- * @param lon :
- * new longitude value
- */
- function setLon(lon) {
- if (document.getElementById("lon").value !== lon) {
- document.getElementById("lon").value = lon;
- }
- }
- function makeMessageShort() {
- var tag = fromLatLonToTag($("#lat").val(), $("#lon").val()) ;
- var message = web + "#" + tag + " I am at " + "#" + tag;
- return message;
- }
- function makeTwitterUrl() {
-
- var tag = fromLatLonToTag($("#lat").val(), $("#lon").val()) ;
- var url = web + "%23" + tag ;
- var message = " I am at " + "#" + tag;
- var baseurl = 'https://twitter.com/intent/tweet?&via=TizenHelper&url=${web}&text=${message}';
- url = baseurl.replace("${web}", url);
- message = encodeURIComponent(message);
- url = url.replace("${message}", message);
- return url;
- }
- /*
- * Link Manager
- */
- /**
- * Get the OpenStreetMap link with the corresponding latitude and longitude
- *
- * @returns url
- */
- function getLink(provider) {
- var lat = $("#lat").val();
- var lon = $("#lon").val();
- var url = web;
- var message = null;
- var tag = null;
-
- switch (provider) {
- case 'OSM':
- url = "http://www.openstreetmap.org/?&zoom=10&layers=mapnik&lat=${lat}&lon=${lon}";
- break;
- case 'GM':
- url = "http://maps.google.com/maps?&z=10&ll=${lat},${lon}";
- break;
- case 'HERE':
- url = "http://maps.nokia.com/${lat},${lon},16,0,0,normal.day";
- break;
- case 'bing':
- url = "http://www.bing.com/maps/?v=2&style=r&lvl=13&cp=48.11~${lat}~${lon}&style=r&lvl=4";
- break;
- case 'twitter':
- url = makeTwitterUrl();
- break;
- default:
- tag = fromLatLonToTag(lat, lon);
- url = provider;
- break;
- }
- url = url.replace("${lon}", lon);
- url = url.replace("${lat}", lat);
- url = url.replace("${tag}", tag);
- url = url.replace("${url}", web);
- url = url.replace("${web}", web);
- return url;
- }
- /**
- * Use the Internet Application Control to go to OSM link with the browser
- */
- function goToURL(provider) {
- var i = 0;
- var j = 0;
- var url = getLink(provider);
- log(url);
- if ('undefined' !== typeof (tizen)) {
- if (isOnline) {
- var appControl = new tizen.ApplicationControl(
- "http://tizen.org/appcontrol/operation/view", url, null);
- var appControlReplyCallback = {
- onsuccess : logMap,
- onfailure : handleFailure
- }
- tizen.application.launchAppControl(appControl, null, function() {
- log("launch internet application control succeed");
- }, function(e) {
- log("launch internet application control failed. reason: "
- + e.message);
- }, appControlReplyCallback);
- } else {
- handleError("Please connect your application online in the settings"
- + " if you want to open a browser")
- }
- } else {
- window.open(url);
- }
- }
- /**
- * update links TODO: check if needed ?
- */
- function updateLinks() {
- $('#OSMLink').attr('href', getOSMLink());
- }
- /*
- * Map Manager
- */
- /**
- * get the size of the map (width, height) according to the dimension of the
- * screen
- *
- * @returns [ width, height ]
- */
- function getMapSize() {
- var viewHeight = $(window).height();
- var viewWidth = $(window).width();
- var header = $("div[data-role='header']:visible:visible");
- var footer = $("div[data-role='footer']:visible:visible");
- var navbar = $("div[data-role='navbar']:visible:visible");
- var content = $("div[data-role='content']:visible:visible");
- var contentHeight = viewHeight - header.outerHeight()
- - navbar.outerHeight() - footer.outerHeight();
- var contentWidth = viewWidth - 30;
- return [ contentWidth, contentHeight ];
- }
- /**
- * Modify the dimension of the map according to getMapSize()
- */
- function setMapSize(size) {
- size = getMapSize();
- $('#myMap').css("width", size[0]);
- $('#myMap').css("height", size[1]);
- }
- function initIcon() {
- var size = new OpenLayers.Size(21, 25);
- var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
- return new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',
- size, offset);
- }
- function loadTrace(data) {
- var i = 0;
- log("loadTrace data : " + data['dates'][0]);
- var icon = initIcon();
- log("tab lons = " + data['lons']);
- log("tab lats = " + data['lats']);
- log("tab dates = " + data['dates']);
- for (i = 0; i < data['dates'].length; i++) {
- var lon = parseFloat(data['lons'][i]);
- var lat = parseFloat(data['lats'][i]);
- var date = data['dates'][i];
- log("data['dates'][" + i + "] = " + date);
- log("data['lons'][" + i + "] = " + lon);
- log("data['lat'][" + i + "] = " + lat);
- log("lat before : " + lat);
- log("lon before : " + lon);
- var lonlat = new OpenLayers.LonLat(lon, lat).transform('EPSG:4326',
- 'EPSG:3857');
- var mark = new OpenLayers.Marker(lonlat, icon);
- trace.addMarker(mark);
- }
- map.addLayer(trace);
- }
- /**
- * Load the OpenLayers map with different OpenStreetMap and Google maps' layers
- * TODO: check if needed ?
- */
- function loadMap() {
- log("#{ loadMap: " + OpenLayers);
- if (OpenLayers === null) {
- log("error: OpenLayers " + isDownloaded);
- return;
- }
- var latCenter = $("#lat").val();
- var lonCenter = $("#lon").val();
- var zoom = $("#zoom").val();
- var layers = [ new OpenLayers.Layer.OSM("OpenStreetMap") ];
- log("# is gmaps available ? " + gmaps + "/" + gmaps);
- if (gmaps !== null) {
- var array = [ new OpenLayers.Layer.Google("Google Satellite", {
- type : google.maps.MapTypeId.SATELLITE,
- numZoomLevels : 22,
- })
- , new OpenLayers.Layer.Google("Google Physical", {
- type : google.maps.MapTypeId.TERRAIN
- }), new OpenLayers.Layer.Google("Google Hybrid", {
- type : google.maps.MapTypeId.HYBRID,
- numZoomLevels : 20
- }),
- new OpenLayers.Layer.Google("Google Streets", {
- numZoomLevels : 20
- }) ];
- // layers = array.concat(layers);
- layers = layers.concat(array);
- }
- log("# add ui " + layers);
- map = new OpenLayers.Map('myMap', {
- projection : 'EPSG:3857',
- layers : layers,
- center : new OpenLayers.LonLat(lonCenter, latCenter).transform(
- 'EPSG:4326', 'EPSG:3857'),
- zoom : zoom,
- controls : [ new OpenLayers.Control.TouchNavigation(),
- new OpenLayers.Control.PanZoom(),
- new OpenLayers.Control.ArgParser() ]
- });
- if (isAdvanced)
- map.addControl(new OpenLayers.Control.LayerSwitcher());
- if (fileRecorded) { // TODO : Data vide : data([0])?.length!=0 or
- // fileRecorded
- // var trace = new OpenLayers.Layer.Markers( "Latest recorded trace"
- // );
- // map.removeLayer(trace);
- var markers = map.getLayersByName("Last recorded trace");
- if (markers.length != 0) {
- var previousTrace = markers[0];
- log("trace = " + previousTrace.name);
- previousTrace.destroy();
- }
- trace = new OpenLayers.Layer.Markers("Last recorded trace");
- // readFile().done(loadTrace);
- readFile();
- // setTimeout(
- // // log("result 0 : "+result[0]);
- // // log("result 1 : "+result[1]);
- // loadTrace
- // , 5000);
- }
- log("#} loadMap: " + OpenLayers);
- }
- /*
- * Refresh Manager
- */
- /**
- * Refresh all the application according to the coordinates and the settings
- */
- function refresh() {
- log("#{ refresh: " + OpenLayers);
- if (isOnline) {
- isReady = (OpenLayers !== null);
- } else {
- isReady = false;
- }
- log("isReady=" + isReady);
- if (isReady) {
- $('#myMap').empty();
- setMapSize();
- loadMap();
- } else {
- // isOnline = navigator.onLine;
- // $('#switchOnline').val(isOnline ? 'online' : 'offline');
- $('#myMap').empty();
- $('#myMap')
- .html(
- "<p align='center'>"
- + "Please connect your application online in the settings"
- + " if you want to load the map</p>");
- }
- // isOffline $('#switchOffline').val() // TODO
- updateDMS();
- if (gLocationDate != null) {
- var lat = $("#lat").val();
- var lon = $("#lon").val();
- var text = "Last update:<br/>" //
- + gLocationDate.toString() //
- + "<br/>" + "#" + fromLatLonToTag(lat, lon) //
- ;
- $('#locationInfo').html(text);
- }
- // var locationInfo = document.getElementById("locationInfo");
- // locationInfo.innerHTML = fromLatLonToDMS(lat, lon);
- log("#} refresh: " + isReady);
- }
- /*
- * Initialization Manager
- */
- /**
- * Recover in the local storage the coordinates values from the preceding use
- */
- function initData() {
- log("#{ initData");
- if (localStorage.getItem('lat') !== null) {
- $('#lat').val(localStorage.getItem('lat'));
- }
- if (localStorage.getItem('lon') !== null) {
- $('#lon').val(localStorage.getItem('lon'));
- }
- if (localStorage.getItem('dms') !== null) {
- $('#dms').val(localStorage.getItem('dms'));
- } // not needed
- storeData();
- log("#} initData");
- }
- /**
- * Recover in the local storage the setting values from the preceding use
- */
- function initSettings() {
- log("#{ initSettings: " + isOnline);
- if (null !== localStorage.getItem('connection')) {
- isOnline = (localStorage.getItem('connection') == 'online');
- }
- $('#switchOnline').val(isOnline ? 'online' : 'offline');
- if (localStorage.getItem('energySaving') !== null) {
- $('#switchEnergy').val(localStorage.getItem('energySaving'));
- }
- if (localStorage.getItem('timeout') !== null) {
- $('#selectorTimeout').attr('value', localStorage.getItem('timeout'));
- }
- if (localStorage.getItem('downloaded') !== null) {
- isDownloaded = localStorage.getItem('downloaded');
- }
- storeSettings();
- log("#} initSettings: " + isReady);
- }
- /*
- * Coordinates transformation Manager
- */
- /**
- * Transform the latitude/longitude into DMS coordinate
- *
- * @param lat :
- * latitude
- * @param lon :
- * longitude
- * @returns dms : DMS coordinate
- */
- function fromLatLonToDMS(lat, lon) {
- var latitude = lat;
- var longitude = lon;
- var dms = "";
- var NS = "";
- if (latitude >= 0) {
- NS += "N";
- } else {
- latitude = -latitude;
- NS += "S";
- }
- var dLat = parseInt(latitude, 10);
- var mLat = parseInt((latitude - dLat) * 60, 10);
- var sLat = parseInt((latitude - dLat) * 60 * 60 - 60 * mLat, 10);
- dms += NS + " " + dLat + "° " + mLat + "' " + sLat + "\" ";
- var EW = "";
- if (longitude >= 0) {
- EW += "E";
- } else {
- EW += "W";
- longitude = -longitude;
- }
- var dLon = parseInt(longitude, 10);
- var mLon = parseInt((longitude - dLon) * 60, 10);
- var sLon = parseInt((longitude - dLon) * 60 * 60 - 60 * mLon, 10);
- dms += EW + " " + dLon + "° " + mLon + "' " + sLon + "\"";
- // text = NS+" "+d+"° "+m+"' "+s+"\" "+EW+" "+d+"° "+m+"' "+s+"\"";
- return dms;
- }
- /** @return string in this form : N26d21m28sE127d47m1s **/
- function fromLatLonToTag(lat, lon) {
- var result = "";
- var latitude = lat;
- var longitude = lon;
- var NS = "";
- if (latitude >= 0) {
- NS += "N";
- } else {
- latitude = -latitude;
- NS += "S";
- }
- var dLat = parseInt(latitude, 10);
- var mLat = parseInt((latitude - dLat) * 60, 10);
- var sLat = parseInt((latitude - dLat) * 60 * 60 - 60 * mLat, 10);
- result += NS + dLat + "d" + mLat + "m" + sLat + "s";
- var EW = "";
- if (longitude >= 0) {
- EW += "E";
- } else {
- EW += "W";
- longitude = -longitude;
- }
- var dLon = parseInt(longitude, 10);
- var mLon = parseInt((longitude - dLon) * 60, 10);
- var sLon = parseInt((longitude - dLon) * 60 * 60 - 60 * mLon, 10);
- result += EW + dLon + "d" + mLon + "m" + sLon + "s";
- return result;
- }
- /**
- * Transform the DMS into latitude/longitude coordinates
- *
- * @param dms :
- * DMS coordinate
- */
- function setDMS(input) {
- input = input.replace('°','d').replace('\'','m'),replace('"',s);
- setTag(input);
- }
- function setTag(input) {
- var re = /^#([NS])([0-9.\-]+)d([0-9.\-]+)m([0-9.\-]+)s([EW])([0-9.\-]+)d([0-9.\-]+)m([0-9.\-]+)s$/;
- if (re.test(input)) {
- var lat = (parseFloat(RegExp.$2) + parseFloat(RegExp.$3) / 60 + parseFloat(RegExp.$4)
- / (60 * 60)).toFixed(6);
- if (RegExp.$1 == 'S') {
- lat = -lat;
- }
- lat = lat.toString();
- setLat(lat);
- var lon = (parseFloat(RegExp.$6) + parseFloat(RegExp.$7) / 60 + parseFloat(RegExp.$8)
- / (60 * 60)).toFixed(6);
- if (RegExp.$5 == 'W') {
- lon = -lon;
- }
- lon = lon.toString();
- setLon(lon);
-
- refresh();
- }
- }
- /*
- * Coordinates Manager
- */
- /**
- * Modify the DMS value using the transformation's function fromLatLonToDMS
- */
- function updateDMS() {
- var lat = $("#lat").val();
- var lon = $("#lon").val();
- var text = fromLatLonToDMS(lat, lon);
- $('#dms').val(text);
- }
- function setLatLon() {
- setDMS($('#dms').val());
- }
- /**
- * Validate or not the DMS coordinate according to the form of the regular
- * expression
- *
- * @param dms :
- * DMS coordinates
- * @returns Validation
- */
- function validateDMS(dms) {
- 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*$/;
- if (re.test(dms)) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * Validate or not the latitudes and longitudes coordinates according to the
- * form of the regular expression
- *
- * @param latOrLon
- * @returns Validation
- */
- function validateLatOrLon(latOrLon) {
- if (/^[0-9.\-]+$/.test(latOrLon)) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * Function called when the latitude value changes Calculate the new DMS
- * coordinate
- */
- function changeLat() {
- var lat = $('#lat').val();
- if (validateLatOrLon(lat)) {
- $('#lat').val(parseFloat($('#lat').val()).toFixed(6).toString());
- refresh();
- storeData();
- } else {
- handleError("Latitude coordinate invalid : " + lat);
- initData();
- }
- }
- /**
- * Function called when the longitude value changes Calculate the new DMS
- * coordinate
- */
- function changeLon() {
- var lon = $('#lon').val();
- if (validateLatOrLon(lon)) {
- $('#lon').val(parseFloat($('#lon').val()).toFixed(6).toString());
- refresh();
- storeData();
- } else {
- handleError("Lontitude coordinate invalid : " + lon);
- initData();
- }
- }
- /**
- * Function called when the DMS value changes Calculate the new latitude and
- * longitude coordinates
- */
- function changeDMS() {
- var dms = $('#dms').val();
- if (validateDMS(dms)) {
- setLatLon();
- storeData();
- } else {
- alert("DMS coordinate invalid : " + dms);
- initData();
- }
- }
- /*
- * Location Manager
- */
- /**
- * Function called when the getCurrentPosition succeded Refresh the application
- */
- function handleShowLocation(position) {
- var lat = position.coords.latitude.toFixed(6).toString();
- var lon = position.coords.longitude.toFixed(6).toString();
- gLocationDate = new Date(position.timestamp);
- setLat(lat);
- setLon(lon);
- refresh();
- isLocated = true;
- }
- /**
- * Function called when the getCurrentPosition failed Show the error
- *
- * @param error
- */
- function handleErrorLocation(error) {
- var locationInfo = document.getElementById("locationInfo");
- switch (error.code) {
- case error.PERMISSION_DENIED:
- locationInfo.innerHTML = "error: User denied the request for Geolocation.";
- break;
- case error.POSITION_UNAVAILABLE:
- locationInfo.innerHTML = "error: Location information is unavailable.";
- break;
- case error.TIMEOUT:
- locationInfo.innerHTML = "error: The request to get user location timed out.";
- break;
- case error.UNKNOWN_ERROR:
- default:
- locationInfo.innerHTML = "error: An unknown error occurred.";
- break;
- }
- toast("Check settings and press update to track position", 4000);
- isLocated = false;
- }
- /**
- * Get the current position according to the GPS' device
- */
- function getLocation() {
- if (navigator.geolocation) {
- navigator.geolocation.getCurrentPosition(handleShowLocation,
- handleErrorLocation, {
- enableHighAccuracy : $('#switchEnergy').val() == 'off'
- });
- } else {
- document.getElementById("locationInfo").innerHTML = "Geolocation is not supported by this browser.";
- }
- }
- /*
- * Recording manager
- */
- /**
- * Function called when the file resolution succeded Create the recording file
- * in the corresponding directory
- *
- * @param dir :
- * directory where the file is placed
- */
- function handleResolveSuccess(dir) {
- docDir = dir;
- var date = new Date();
- var dateFile = "" + date.getFullYear().toString() + "-"
- + date.getMonth().toString() + "-" + date.getDate().toString()
- + "-" + date.getHours().toString() + "-"
- + date.getMinutes().toString() + "-" + date.getSeconds().toString();
- dateFile = (new Date).getTime();
- // log(dateFile);
- doc = 'mapo-' + dateFile + ".csv.txt";
- docDir.createFile(doc);
- $('#locationInfo').html("Track recording in file:<br/>" + doc);
- }
- /**
- * Function called when the file resolution failed Show the error
- *
- * @param e :
- * error
- */
- function handleResolveError(e) {
- handleError('resolve: ' + e.message);
- }
- /**
- * Resolve the file
- */
- function resolveFile() {
- try {
- file = docDir.resolve(doc);
- } catch (exc) {
- log('Could not resolve file: ' + exc.message);
- // Stop in case of any errors
- return;
- }
- }
- /**
- * Function called when the record failed, writing or reading Show the error
- *
- * @param e :
- * error
- */
- function handleErrorStream(e) {
- var msg = '';
- switch (e.code) {
- case FileError.QUOTA_EXCEEDED_ERR:
- msg = 'QUOTA_EXCEEDED_ERR';
- break;
- case FileError.NOT_FOUND_ERR:
- msg = 'NOT_FOUND_ERR';
- break;
- case FileError.SECURITY_ERR:
- msg = 'SECURITY_ERR';
- break;
- case FileError.INVALID_MODIFICATION_ERR:
- msg = 'INVALID_MODIFICATION_ERR';
- break;
- case FileError.INVALID_STATE_ERR:
- msg = 'INVALID_STATE_ERR';
- break;
- default:
- msg = 'Unknown Error';
- break;
- }
- handleError(msg);
- }
- /**
- * Function called when the writing succeeded Add the position at the end of the
- * file
- *
- * @param fileStream :
- * Stream to write
- */
- function handleStreamWrite(stream) {
- try {
- var date = (new Date).getTime();
- var lat = $("#lat").val();
- var lon = $("#lon").val();
- var line = "" + date + ";" + lat + ";" + lon + "\n";
- stream.write(line);
- stream.close();
- } catch (exc) {
- handleError('io: could not write to file: ' + exc.message);
- }
- }
- /**
- * Try to write the record into the file
- */
- function writeRecord() {
- try {
- file.openStream('a', handleStreamWrite, handleErrorStream);
- } catch (exc) {
- handleError('io: could not write to file: ' + exc.message);
- }
- }
- /**
- * Function called when the reading succeded
- *
- * @param fileStream :
- * Stream to read
- */
- function handleStreamRead(fileStream) {
- try {
- log('File size: ' + file.fileSize);
- var contents = fileStream.read(fileStream.bytesAvailable);
- fileStream.close();
- log('file contents: ' + contents);
- } catch (exc) {
- handleError('io: Could not read from file: ' + exc.message);
- }
- }
- /**
- * Try to read the file
- */
- function readRecord() {
- try {
- file.openStream('r', handleStreamRead, handleRecordError);
- } catch (exc) {
- handleError('io: Could not write to file: ' + exc.message);
- }
- }
- /**
- * Function called when getPosition got successfully the position Resolve the
- * file, write and read the records
- *
- * @param position
- */
- function handleRecordPosition(position) {
- if ($('#switchRecord').val() == "start") {
- handleShowLocation(position);
- resolveFile();
- writeRecord();
- readRecord();
- }
- }
- /**
- * Function called when getPosition failed to get the position Show the error
- *
- * @param error
- */
- function handleErrorPosition(error) {
- $('#switchRecord').val('stop').slider('refresh');
- var errorInfo = document.getElementById("locationInfo");
- switch (error.code) {
- case error.PERMISSION_DENIED:
- errorInfo.innerHTML = "User denied the request for Geolocation.";
- break;
- case error.POSITION_UNAVAILABLE:
- errorInfo.innerHTML = "Location information is unavailable.";
- break;
- case error.TIMEOUT:
- errorInfo.innerHTML = "The request to get user location timed out.";
- break;
- case error.UNKNOWN_ERROR:
- errorInfo.innerHTML = "An unknown error occurred.";
- break;
- }
- }
- /**
- * Get the recording position
- */
- function getPosition() {
- navigator.geolocation.getCurrentPosition(handleRecordPosition, log, {
- enableHighAccuracy : false,
- timeout : 2000,
- maximumAge : Ininity
- });
- navigator.geolocation.getCurrentPosition(handleRecordPosition,
- handleErrorPosition, {
- enableHighAccuracy : $('#switchEnergy').val() == 'off'
- });
- }
- /**
- * Function called when the record of a trace has been launched Record the
- * position whith a timeout predefined in the settings
- */
- function record() {
- if (navigator.geolocation) {
- var intervalID;
- if ($('#switchRecord').val() == "start") {
- tizen.filesystem.resolve('documents', handleResolveSuccess,
- handleResolveError, 'rw');
- getPosition();
- intervalID = setInterval(getPosition,
- $('#selectorTimeout').val() * 1000);
- } else {
- clearInterval(intervalID);
- $('#locationInfo').html("Trace recorded in the file:<br/>" + doc);
- fileRecorded = true;
- }
- } else {
- document.getElementById("locationInfo").innerHTML = "Geolocation is not supported.";
- }
- }
- /**
- * Extract from a file composed by the last recorded trace all the dates,
- * latitudes and lontitudes and place its in data TODO: test if parse CSV as
- * "date,la,lo\n"
- */
- function readFile() {
- // var deferred = $.Deferred();
- try {
- file = docDir.resolve(doc);
- log('File size: ' + file.fileSize);
- } catch (exceptionResolve) {
- log('error: Could not resolve file: ' + exceptionResolve.message);
- // Stop in case of any errors
- return;
- }
- try {
- file.readAsText(
- // success callback - display the contents of the file
- function(contents) {
- // log('File contents:' + contents);
- var lines = contents.split("\n");
- var re = /^([0-9.:\-]+),([0-9.\-]+),([0-9.\-]+)$/;
- var data = [];
- var dates = [];
- var lats = [];
- var lons = [];
- var iData = 0;
- for (var iLines = 0; iLines < lines.length; iLines++) {
- if (re.test(lines[iLines])) {
- log("line " + iLines + ": " + lines[iLines]);
- var parts = lines[iLines].split(";");
- for (var iParts = 0; iParts < parts.length; iParts++) {
- log(" part " + iParts + ": " + parts[iParts]);
- if ((iParts % 3) == 0) {
- dates[iData] = parts[iParts];
- log(" date " + iData + ": " + dates[iData]);
- } else if ((iParts % 3) == 1) {
- lats[iData] = parts[iParts];
- log(" lat " + iData + ": " + lats[iData]);
- } else {
- lons[iData] = parts[iParts];
- log(" lon " + iData + ": " + lons[iData]);
- }
- }
- iData++;
- }
- }
- data['dates'] = dates;
- data['lats'] = lats;
- data['lons'] = lons;
- log("readfile data" + data['dates'][0]);
- loadTrace(data);
- },
- // error callback
- handleRecordError);
- } catch (exceptionRead) {
- handleError("io: readAsText() exception:" + exceptionRead.message);
- }
- // deferred.resolve();
- // return deferred; // [data, referred]
- }
- /*
- * Social Manager
- */
- function makeMessage() {
- var message = "I am at this place:\n" //
- + "#" + fromLatLonToTag($("#lat").val(), $("#lon").val()) + " \n" //
- + "Latitude=" + $("#lat").val() + " \n" //
- + "Longitude = " + $("#lon").val() + " \n" //
- + "( " + $('#dms').val() + ")\n " + " \n" //
- + getLink('OSM') + " \n" + web + " \n";
- return message;
- }
- /**
- * Use the Email Application Control to share a position by Email
- */
- function sendEmail() {
- var email = gEmail;
- var message = makeMessage();
- var subject = "Mapo current position is ...";
- if ('undefined' !== typeof (tizen)) {
- if (isOnline) {
- var appControl = new tizen.ApplicationControl(
- "http://tizen.org/appcontrol/operation/compose", //
- null,
- null, null, [
- new tizen.ApplicationControlData(
- "http://tizen.org/appcontrol/data/subject",
- [ subject ]),
- new tizen.ApplicationControlData(
- "http://tizen.org/appcontrol/data/to",
- [ email ]),
- new tizen.ApplicationControlData(
- "http://tizen.org/appcontrol/data/text",
- [ message ]) ]);
- tizen.application
- .launchAppControl(appControl, "tizen.email", //
- handleSuccess, handleException);
- } else {
- alert("Please connect your application online in the settings"
- + " if you want to send an email");
- }
- } else {
- var url = "mailto:" + email + "?subject=" + subject + "&body="
- + message;
- window.open(url);
- }
- }
- function sendMessage() {
- var message = makeMessage();
- var appControl = new tizen.ApplicationControl(
- "http://tizen.org/appcontrol/operation/compose", null, null, null,
- [
- new tizen.ApplicationControlData(
- "http://tizen.org/appcontrol/data/messagetype",
- [ "sms" ]),
- new tizen.ApplicationControlData(
- "http://tizen.org/appcontrol/data/text",
- [ message ]) ]);
- tizen.application.launchAppControl(appControl, "tizen.messages", //
- handleSuccess, handleException);
- }
- /*
- * Settings Manager
- */
- function settings() {
- var url = "http://tizen.org/appcontrol/operation/setting";
- var id = "com.samsung.setting";
- var appControl = new tizen.ApplicationControl(url);
- tizen.application.launchAppControl(appControl, id, handleSuccess,
- handleException);
- }
- function settingsLocation() {
- var url = "http://tizen.org/appcontrol/operation/setting/location";
- var id = "org.tizen.setting-location";
- var appControl = new tizen.ApplicationControl(url);
- tizen.application.launchAppControl(appControl, id, handleSuccess,
- handleException);
- }
- function handleCapture(input) {
- log($('#capture').val()); // fakepath
- log("TODO: save to file using tag filename");
- }
- /*
- * Caller Manager : may not be needed
- */
- function call() {
- log("TODO");
- exit();
- var appControl = new tizen.ApplicationControl(
- "http://tizen.org/appcontrol/operation/dial", null, null);
- tizen.application.launchAppControl(appControl, "tizen.phone",
- handleSuccess, handleException, null);
- }
- function caller() {
- log("TODO");
- exit();
- var appControl = new tizen.ApplicationControl(
- "http://tizen.org/appcontrol/operation/call",
- null,
- null,
- null,
- [ new tizen.ApplicationControlData(
- "http://tizen.org/appcontrol/data/call/type", [ "voice" ]) ]);
- tizen.application.launchAppControl(appControl, "tizen.call", //
- handleSuccess, handleException);
- }
- /*
- * Contact Manager
- */
- /**
- * Use the Contact Application Control to add a contact with the corresponding
- * position
- */
- function createContact() {
- log("#{ createContact");
- var addressbook = tizen.contact.getDefaultAddressBook();
- var groups = addressbook.getGroups();
- var idMapo = "-1";
- for (var i = 0; i < groups.length; i++) {
- log(groups[i].name);
- if (groups[i].name == 'Mapo') {
- idMapo = groups[i].id;
- }
- }
- var group;
- if (idMapo != "-1") {
- group = addressbook.getGroup(idMapo);
- log('Group already exists ' + group.id);
- } else {
- group = new tizen.ContactGroup('Mapo');
- addressbook.addGroup(group);
- log('Group added with id ' + group.id);
- }
- // TODO: edit contact is present
- var contact = new tizen.Contact({
- emails : [ new tizen.ContactEmailAddress(gEmail) ],
- urls : [ new tizen.ContactWebSite(getLink('OSM'), 'HOMEPAGE') ],
- notes : [ 'Position: lat=' + $("#lat").val() + ' lon='
- + $("#lon").val() ],
- organizations : [ new tizen.ContactOrganization({
- name : "Mapo"
- }) ],
- groupIds : [ group.id ]
- });
- addressbook.add(contact);
- var appControl = new tizen.ApplicationControl(
- "http://tizen.org/appcontrol/operation/social/edit",
- null,
- "vnd.tizen.item.type/vnd.tizen.contact",
- null,
- [
- new tizen.ApplicationControlData(
- "http://tizen.org/appcontrol/data/social/item_type",
- [ "person" ]),
- new tizen.ApplicationControlData(
- "http://tizen.org/appcontrol/data/social/item_id",
- [ contact.personId ]) ]);
- tizen.application.launchAppControl(appControl, null, function() {
- log("contact: launch service succeeded");
- }, function(e) {
- handleError("contact: launch service failed. Reason: " + e);
- });
- log("#} createContact");
- }
- /*
- * Calendar Manager
- */
- /**
- * Use the Contact Application Control to add an event in the calendar with the
- * corresponding date
- */
- function createCalendarEvent() {
- var calendar = tizen.calendar.getDefaultCalendar("EVENT");
- var date = new Date();
- var event = new tizen.CalendarEvent({
- description : "Mapo Event",
- summary : "Mapo",
- startDate : new tizen.TZDate(date.getFullYear().toString(), date
- .getMonth().toString(), date.getDate().toString(), date
- .getHours().toString(), date.getSeconds().toString()),
- duration : new tizen.TimeDuration(1, "HOURS"),
- location : 'Position: lat=' + $("#lat").val() + ' lon='
- + $("#lon").val()
- });
- calendar.add(event);
- var url = "http://tizen.org/appcontrol/operation/social/edit";
- var appControl = new tizen.ApplicationControl(url, null, null, null, [
- new tizen.ApplicationControlData(
- "http://tizen.org/appcontrol/data/social/item_type",
- [ "event" ]),
- new tizen.ApplicationControlData(
- "http://tizen.org/appcontrol/data/social/item_id",
- [ event.id.uid ]) ]);
- tizen.application.launchAppControl(appControl, "tizen.calendar",
- function() {
- log("success: " + url);
- }, function(e) {
- handleError("launch service failed. Reason: " + e);
- });
- }
- /*
- * Settings Manager
- */
- /**
- * Function called when the online swith is activated or desactived Verify if
- * the the device has a connection before connecting the application
- */
- function switchOnline() {
- log("#{ switchOnline: " + isOnline);
- log($('#switchOnline').val());
- isOnline = ("online" === $('#switchOnline').val());
- if (isOnline && !navigator.onLine)
- log("connect system's wifi before");
- if (isOnline) {
- isReady = (null === OpenLayers);
- if (!isReady || (null === gmaps)) {
- download();
- }
- } else {
- isReady = false;
- }
- refresh();
- log("#} switchOnline: " + isOnline);
- }
- function switchDeveloper() {
- isAdvanced = ("on" === $('#switchDeveloper').val());
- var attribute = (isAdvanced) ? "visible" : "hidden";
- $("#logView").css("visibility", attribute);
- $("#recordView").css("visibility", attribute);
- log("logging...");
- }
- /**
- * Use the tactil swipe to change between every pages TODO : blink ?
- */
- function swipePage() {
- $('div.ui-page').live("swipeleft", function() {
- var nextpage = $(this).next('div[data-role="page"]');
- // swipe using id of next page if exists
- if (nextpage.length > 0) {
- $.mobile.changePage(nextpage, {
- transition : "slide",
- reverse : false
- });
- }
- });
- $('div.ui-page').live("swiperight", function() {
- var prevpage = $(this).prev('div[data-role="page"]');
- // swipe using id of next page if exists
- if (prevpage.length > 0) {
- $.mobile.changePage(prevpage, {
- transition : "slide",
- reverse : true
- });
- }
- });
- }
- function handleLoadedGmaps() {
- log("#{ handleLoadedGmaps: + " + google);
- gmaps = google;
- isDownloaded = true;
- refresh();
- log("#} handleLoadedGmaps: + " + isDownloaded);
- }
- function downloadScriptsBody() {
- log("#{ downloadScriptsBody: " + OpenLayers);
- {
- var element = document.createElement("script");
- element.type = 'text/javascript';
- element.src = url_openlayers;
- document.body.appendChild(element);
- }
- {
- var element = document.createElement("script");
- element.type = 'text/javascript';
- element.src = url_gmaps;
- document.body.appendChild(element);
- }
- log("#} downloadScriptsBody: " + OpenLayers);
- }
- function download() {
- log("#{ download: " + OpenLayers);
- if (null == OpenLayers) {
- $.getScript(url_openlayers, function() {
- log("download:" + OpenLayers);
- refresh();
- $.getScript(url_gmaps, function() {
- handleLoadedGmaps();
- });
- });
- } else if (null == google) {
- $.getScript(url_gmaps, function() {
- handleLoadedGmaps();
- });
- } else {
- handleLoadedGmaps();
- }
- // isLoaded = true; // TODO?
- log("#} download: " + OpenLayers);
- }
- function initScripts() {
- log("#{ initScripts: " + OpenLayers);
- log("# isDownloaded=" + isDownloaded);
- if (false === isDownloaded) {
- download();
- } else {
- download();
- refresh();
- }
- log("#} initScripts: " + OpenLayers);
- }
- /**
- * Initialize the data from the preceding use
- */
- function start() {
- log("#{ start: " + OpenLayers);
- $("#picture").hide()
- $("#capture").change(handleCapture);
- initData();
- initSettings();
- initScripts();
- changeLat();
- changeLon();
- log(window.location.hash);
- if(window.location.hash) {
- setTag(window.location.hash);
- } else {
- setTimeout(getLocation, 4000);
- }
- // refresh();
- if (false) { // TODO: buggy flash screen
- swipePage();
- }
- // refresh();
- log("#} start: " + OpenLayers);
- }
|