Send gps coordinates to server every minute - jquery-mobile

I'm tyring to build a PhoneGap app with jQueryMobile. In my app I need to send a users current geolocations GPS coordinates to server every 4 minute. How can I do this?
This is the code I have been using right now, but it doesn't send any data. How can i modify this to make it work?
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// PhoneGap is ready
//
function onDeviceReady() {
// Update every 4 minute
var options = { maximumAge: 240000, timeout: 5000, enableHighAccuracy: true };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var lat = Position.coords.latitude;
var lng = Position.coords.longitude;
jQuery.ajax({
type: "POST",
url: serviceURL+"locationUpdate.php",
data: 'x='+lng+'&y='+lat,
cache: false
});
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}

Instead of calling setInterval, let phonegap do that for you.
// onSuccess Callback
// This method accepts a `Position` object, which contains the current GPS coordinates
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Options: retrieve the location every 3 seconds
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 });
http://docs.phonegap.com/en/1.0.0/phonegap_geolocation_geolocation.md.html#geolocation.watchPosition

Related

Audio file does not persist in Cordova with LocalFileSystem.PERSISTENT

I have been trying to store Audio file in persistent storage for two days without success.
So far I am able to create an audio file which records audio from Microphone (The app has the permission) using the code attached below.
The audio file is getting generated & stored successfully, I can play it.
But the real problem is when I close the app and come back and try to play the file it shows error.
"{"message": "Cannot use audio file from resource '/myrecording.wav'",
"code":1}"
The file is not persistent across app sessions even though I used LocalFileSystem.PERSISTENT.
I am not sure whether the problem is with my Media/Audio code or File storage code.
Please find the code attached below:
Below function records the audio from the microphone.
function _recordAudio() {
var deferred = $q.defer();
var src = "myrecording.wav";
alert("SRC:" + src);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(src, {
create: true,
exclusive: false
}, function (fileEntry) {
alert("File " + src + " created at " + fileEntry.fullPath);
var mediaRec = new Media(fileEntry.fullPath,
function () {
alert("Success");
}, function (error) {
alert("error:" + JSON.stringify(error));
});
// Record audio
mediaRec.startRecord();
// Stop recording after 10 sec
var recTime = 0;
var recInterval = setInterval(function () {
recTime = recTime + 1;
if (recTime >= 5) {
clearInterval(recInterval);
mediaRec.stopRecord();
deferred.resolve(fileEntry.fullPath);
}
}, 1000);
}, function (error) {
alert("getFile error:" + JSON.stringify(error));
deferred.reject();
}); //of getFile
}, function (error) {
alert("requestFileSystem error:" + JSON.stringify(error));
deferred.reject();
}); //of requestFileSystem
return deferred.promise;
}
Below function plays the audio.
function _play2() {
var src = "myrecording.wav";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(src, null, function (fileEntry) {
alert("File " + src + " created at " + fileEntry.fullPath);
var mediaRec = new Media(fileEntry.fullPath,
function () {
alert("Success play2");
}, function (error) {
//Getting error after closing and opening the app
//Error message = {"message": "Cannot use audio file from resource '/myrecording.wav'","code":1}
alert("error play2:" + JSON.stringify(error));
});
mediaRec.play();
});
});
}
I solved this problem by passing cdvfile: path to the Media plugin in PlayAudio function code and copying the file from Temp storage to persistent storage.
I had to use localURL of the file.
This part solved my problem:
fileEntry.file(function (file) {
_playNow(file.localURL);
}
For full functions refer code snippets below:
recordAudio: function (projectNo, ItemNo) {
try {
var deferred = $q.defer();
var recordingTime = 0;
_audioLoader = $("#audioLoader");
_audioLoader.show();
UtilityService.showPopup('audio');
_isRecording = true;
_recordFileName = "Audio_" + projectNo + "_" + ItemNo + ".wav";
_mediaRecord = new Media(_recordFileName);
//Record audio
_mediaRecord.startRecord();
var recordingInterval = setInterval(function () {
recordingTime = recordingTime + 1;
$('#audioPosition').text(_secondsToHms(recordingTime));
if (!_isRecording) {
clearInterval(recordingInterval);
_mediaRecord.stopRecord();
_mediaRecord.release();
deferred.resolve();
}
}, 1000);
//document.getElementById('audioPosition').innerHTML = '0 sec';
$('#audioPosition').text('0 sec');
return deferred.promise;
}
catch (ex) {
alert('WMMCPA|recordAudio:- ' + ex.message);
}
},
Get file path from the persistent storage and send it to the play method.
//To play recorded audio for specific project item
playAudio: function (projectNo, ItemNo) {
try {
_recordFileName = "Audio_" + projectNo + "_" + ItemNo + ".wav";
var newFileUri = cordova.file.dataDirectory + _recordFileName;
window.resolveLocalFileSystemURL(newFileUri, function (fileEntry) {
fileEntry.file(function (file) {
_playNow(file.localURL);
}, function (error) {
alert("WMMCPA|playAudio.file:-" + JSON.stringify(error));
});
}, function (error) {
alert("WMMCPA|playAudio.resolveLocalFileSystemURL:-" + JSON.stringify(error));
});
}
catch (ex) {
alert("WMMCPA|playAudio:-" + ex.message);
}
}
function _playNow(src) {
try {
var mediaTimer = null;
_audioLoader = $("#audioLoader");
_audioLoader.show();
UtilityService.showPopup('audio');
//Create Media object from src
_mediaRecord = new Media(src);
//Play audio
_mediaRecord.play();
} catch (ex) {
alert('WMMCPA|_playNow.mediaTimer:- ' + ex.message);
}
}, 1000);
} catch (ex) {
alert('WMMCPA|_playNow:- ' + ex.message);

Showing Page Loading Message in single application in jquery mobile

I am trying to show loading message ...... I am working on single page application in phonegag using jquery mobile.
$(document).delegate("#cartaxvalidityPage", "pageinit", function () {
$.mobile.showPageLoadingMsg();
createCarTaxValidPage();
$.mobile.hidePageLoadingMsg();
});
function createCarTaxValidPage() {
var buyerList = carHaatDatabaseParsed.BuyerList;
$("#buyer-listview").empty();
for (var i = 0; i < buyerList.length; i++) {
var listItem = $('<li> </li>');
var listAnc = $('<a> </a>');
var carImag = "<img " + "src='" + "data:image/jpg;base64," + buyerList[i].BuyerPhoto + "'/>";
var listHeader = $('<h3> ' + "Buyer Name: " + buyerList[i].BuyerName + ' </h3>');
var listParagraph = $('<p> Buyer Id: ' + buyerList[i].BuyerTaxId + ' </p>');
var listParagraphValidDate = $('<p> Tax Expire Date: ' + buyerList[i].CarValidityDate + '</p>');
listAnc.append(carImag);
listAnc.append(listHeader);
listAnc.append(listParagraph);
listAnc.append(listParagraphValidDate);
listItem.append(listAnc);
$("#buyer-listview").append(listItem);
}
$("#buyer-listview").listview("refresh");
}
It doesn't show any message.
.delegate is deprecated and replaced with .on.
$(document).on("pageinit", "#cartaxvalidityPage", function () { });
On pageinit event, use setTimeout to dela showing loading message.
setTimeout(function () {
$.mobile.loading("show");
}, 10);
Use $.mobile.loading("show") and $.mobile.loading("hide")
Demo

Why does this (javascript) closure fail?

The variable "called" is false when is should be set to true.. why is that?
It is set to true when called by the plugin but outside the closure it remains false.
Its a bit baffling. Thanks in advance for any pointers.
(function() {
module("when InitializedApplication() is called");
test("it should call the success function", function () {
// arrange
$("#qunit-fixture").append(
'<script id="events-catalog-view-template"' +
' type="text/html"'+
' src="_events-catalog.view.html">' +
'</script>' +
'<div id="events-catalog-view-container"' +
' data-bind="template: {' +
' name="events-catalog-view-template" ' +
' afterRender="tpw.mediator.eventscatalog.setupViewDataBinding" ' +
' }"' +
'</div>'
);
var called = false;
// act
var init = TPW.InitializeApplication();
init({
logLevel: "debug",
success: function (successfullResolution) {
called = true;
},
error: function (failedResolution) {
}
});
// assert
ok(called, "success function called");
});
})();
The qunit ok() function was being called before the success callback. Async problem.

fileupload plugin in ios is not working

i am developing a phonegap project in mac os with xcode. in xcode if i create a cordova based application it automatically creates cordova-1.6.0.js. i am using fileupload plugin for sending svg file to my server. in fileupload.js i have written alert fileuplaoder function as following,
var FileUploader = function() {
alert("gi");
}
this alert is working, but when i give the aler under upload function,
FileUploader.prototype.upload = function(server, file, params, fileKey, fileName, mimeType, success, fail, progress) {
alert("upload");
this._doUpload('upload', server, file, params, fileKey, fileName, mimeType, success, fail, progress);
};
this alert is not working. my call for this plugin in html page is,
window.plugins.fileUploader.upload('http:192.168.1.54:8080/downloadFiles', '/Users/User/Library/Application Support/iPhone Simulator/5.0/Applications/408DBBC7-67F7-4E8B-B41C-663CDC0377B5/Documents/image5_1.jpg.txt.svg', {foo: 'bar'}, 'myPhoto', 'image5_1.jpg.txt.svg', 'image/svg',
function(result) {
console.log('Done: ' + result);
},
function(result) {
console.log("Error: " + result);
},
function(loaded, total) {
var percent = 100 / total * loaded;
console.log('Uploaded ' + percent);
}
);
in fileupload.js there is cordova.addConstructor method. but in my generated cordova.1.6.0.js file there is no such method. i dont know whats happening. pl help me to work this plugin.
i found the solution. there is a upload and download options in the cordova file api itself. its working fine. the code is,
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("image5_2.jpg.svg", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
var localpath=fileEntry.fullPath;
uploadPhoto(localpath);
//fileEntry.createWriter(gotFileWriter, fail);
}
function uploadPhoto(imageURI) {
alert(imageURI);
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName="image5_2.jpg.svg";
options.mimeType="image/svg+xml";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://192.168.1.54:8080/POC/fileUploader", win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
pl use this.

Geo Location not works in BlackBerry

I have developed an application using phonegap to retrieve Geo Location.
function getLoc() {
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
}
// onSuccess Geolocation
function onSuccess(position) {
var locInfo = new Object();
locInfo.Latitude = position.coords.latitude;
locInfo.Longitude = position.coords.longitude;
locInfo.Altitude = position.coords.altitude;
locInfo.Accuracy = position.coords.accuracy;
locInfo.AltitudeAccuracy = position.coords.altitudeAccuracy;
locInfo.Heading = position.coords.heading;
locInfo.Speed = position.coords.speed;
alert(locInfo.Latitude + " " + locInfo.Longitude);
}
// onError Callback receives a PositionError object
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
above code is working fine in Android, iPhone and BlackBerry Simulator, but not in BlackBerry device. I'm using BlackBerry Torch for testing.
what could be the issue. pls reply.
Thanks :)
Try to set timeout for getCurrentPosition.

Resources