1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522 |
- /*
- 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);
- isAdvanced = $('#switchDeveloper').val();
- localStorage.setItem('develmode', isAdvanced );
- 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');
- }
-
- if (localStorage.getItem('develmode') !== null) {
- isAdvanced = localStorage.getItem('develmode');
- }
- $('#switchDeveloper').val(isAdvanced ? 'on' : 'off');
- 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(isUpdate) {
- if (navigator.geolocation) {
- if (isUpdate) {
- navigator.geolocation.getCurrentPosition(handleShowLocation,
- handleErrorLocation, {
- enableHighAccuracy : $('#switchEnergy').val() == 'off'
- });
- } else {
- navigator.geolocation.watchPosition(updateMapCenter,
- handleErrorLocation, {
- enableHighAccuracy : $('#switchEnergy').val() == 'off'
- });
- }
- } else {
- document.getElementById("locationInfo").innerHTML = "Geolocation is not supported by this browser.";
- }
- }
- function updateMapCenter(position) {
- var latCenter = position.coords.latitude.toFixed(6).toString();
- var lonCenter = position.coords.longitude.toFixed(6).toString();
- map.setCenter(new OpenLayers.LonLat(lonCenter, latCenter).transform('EPSG:4326', 'EPSG:3857'));
- }
- /*
- * 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();
- switchDeveloper();
- 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);
- }
|