I am developing a phonegap application that uses the current location of the device in its functionalities but when tested on Iphone the App give an error message every 60 seconds as follows:
The Source code I am using to get the location is:
function onDeviceReady() {
var options = { maximumAge: 0, timeout: 10000,enableHighAccuracy: false };
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
function onSuccess(position) {
if (position.coords.latitude) {
sessionStorage.setItem("appLatitude", position.coords.latitude);
sessionStorage.setItem("appLongitude", position.coords.longitude);
}
//alert(sessionStorage.getItem("appLatitude") + "&" + sessionStorage.getItem("appLongitude"));
}
function onError(error) {
z.appNotification.getAlert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
How can stop that error message from prompting?
If you only want to get the location once use:
navigator.geolocation.getCurrentPosition(onSuccess, onError);
If you want to stop watching for any reason, use:
navigator.geolocation.clearWatch(watchID);
Related
I want to show an alert saying that "Please turn on your GPS".
How can I get GPS status using phonegap?
I have used following code but I don't get any alert message if GPS is turned off. Instead nothing happens.
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var test= navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Accuracy: ' + position.coords.accuracy + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Heading: ' + position.coords.heading + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + position.timestamp + '<br />';
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body>
<p id="geolocation"> Finding geolocation...</p>
</body>
</html>
Assuming we're talking just about Android platform only, as #Joerg rightly says, you can use cordova.plugins.diagnostic to check if GPS is enabled using isGpsLocationEnabled():
cordova.plugins.diagnostic.isGpsLocationEnabled(function(enabled){
console.log("GPS location is " + (enabled ? "enabled" : "disabled"));
}, function(error){
console.error("The following error occurred: "+error);
});
If the result is that GPS is switched off, you can either switch the user to the location settings page to manually enable GPS:
cordova.plugins.diagnostic.switchToLocationSettings();
Or, in addition, you could use cordova-plugin-request-location-accuracy to request high accuracy location mode (i.e. GPS) directly from within the app. This will show a native confirm dialog and if user agrees, GPS will be enabled automatically:
function onRequestSuccess(success){
console.log("Successfully requested accuracy: "+success.message);
}
function onRequestFailure(error){
console.error("Accuracy request failed: error code="+error.code+"; error message="+error.message);
if(error.code !== cordova.plugins.locationAccuracy.ERROR_USER_DISAGREED){
if(window.confirm("Failed to automatically set Location Mode to 'High Accuracy'. Would you like to switch to the Location Settings page and do this manually?")){
cordova.plugins.diagnostic.switchToLocationSettings();
}
}
}
cordova.plugins.locationAccuracy.request(onRequestSuccess, onRequestFailure, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
The answer to your question is below.
You cannot check *if gps is enabled*
You can set a timeout and get the timeout.
You can do this by setting the timeout parameter in the geolocationoptions parameter. (which you did not use)
From the documentation
timeout: The maximum length of time (milliseconds) that is allowed to pass from the call to navigator.geolocation.getCurrentPosition or geolocation.watchPosition until the corresponding geolocationSuccess callback executes. If the geolocationSuccess callback is not invoked within this time, the geolocationError callback is passed a PositionError.TIMEOUT error code. (Note that when used in conjunction with geolocation.watchPosition, the geolocationError callback could be called on an interval every timeout milliseconds!) (Number)
WAIT I WAS WRONG
There is now a plugin that checks to see if the GPS is turned on.
In fact, more than one.
https://www.npmjs.com/package/cordova-plugin-fastrde-checkgps
https://www.npmjs.com/package/cordova-plugin-android-gpsdetect
The best way to check if GPS, Wifi, … is enabled, is to use this plugin:
https://www.npmjs.com/package/cordova.plugins.diagnostic
Using this plugin you can check a lot of features and you can switch the user to the settings.
I rebooted my android phone and the geolocation code in my app has stopped working. The navigator.geolocation is returning true but getCurrentPosition and watchPosition aren't working. It isn't returning an error message either. I have location turned on the phone, the phone version is 5.0.1 and the cordova version I am using is 5.3.3.
Any help would be greatly appreciated!
The JavaScript code I am using:
function showCurrentPosition(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
}
// onSuccess Callback
// This method accepts a Position object, which contains the
// current GPS coordinates
//
var onSuccess = function(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
};
// onError Callback receives a PositionError object
//
function onError() {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
Console Log:
The key "target-densitydpi" is not supported.
file:///android_asset/www/css/images/ajax-loader.gif Failed to load resource: net::ERR_FILE_NOT_FOUND
whitelist.js:23 No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.(anonymous function) # whitelist.js:23
index.js:41 Uncaught TypeError: Cannot read property 'querySelector' of null
521whitelist.js:25 No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.
I figured out what was causing my geolocation to stop working. When I rebooted my android is set the location services to GPS only. When I changed it use WiFi, phone network and GPS for my location it was able to obtain my longitude and latitude.
The problem with my android phone is that the GPS has stopped working so this turned out to be a hardware problem not a software problem.
I am building a PhoneGap app, and currently have setup some datasources that have a JSON feed I pull from, to populate my app with data. Right now, it only pulls that data once, the first time the app is run.
I would like to download data everytime the app first opens, and then if it stays open for longer than 15 minutes, it updates again. The json feed can be queried with a last_mod_day in the URL so it pulls only the data that has changed.
What would be recommended to go about this, and how to check for a WiFi/Data Connection on the phone, and if not it fails quietly?
Below is the code for my current function to grab the feed.
function downloadFileError(evt) {
console.log('downloadFileError: ');
console.log(evt.target.error);
}
function downloadFile(ep) {
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile("dummy.json", {
create: true,
exclusive: false
},
function gotFileEntry(fileEntry) {
var filename = cordova.file.dataDirectory + 'assets/json/' + ep + '.json';
var fileTransfer = new FileTransfer();
fileEntry.remove();
console.log('looking at ' + filename);
fileTransfer.download(
encodeURI("http://www.myURL.com/theApp?ep=" + ep),
filename,
function(theFile) {
console.log("download complete: " + theFile.toURL());
},
function(error) {
console.log("DLERR: src=" + error.source + " t=" + error.target);
}
);
},
function(evt) {
console.log(evt);
console.log('fn: ' + filename);
}
);
},
downloadFileError);
}
function downloadDynamicPages() {
var deferred = $.Deferred();
var pages = ['setOne','setTwo','setThree','setFour','setFive','setSix'];
var cnt = 0;
var total_pages = pages.length;
//checkConnection();
$.each(pages,function(k,v) {
console.log('looking at ' + v);
downloadFile(v);
cnt++;
if(cnt >= total_pages) {
deferred.resolve('all done with files');
}
});
return deferred.promise();
}
Any help on any part of these questions would help me greatly. If needed, I can answer any questions. Thank you Stack.
here is the code below
if (navigator.geolocation) {
alert("ok");
// var options = { timeout: 0, maximumAge: 600000 };
navigator.geolocation.watchPosition(onSuccess, onError);
}
function onSuccess(position) {
alert("success");
lat = position.coords.latitude;
lng = position.coords.longitude;
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
It works in all browsers , iphone and WindowsPhone. But in andorid in gives me error code :3 timeout expired error.
I enabled gps, wi-fi also in the settings menu--> location services -->location and Google Search,
In the browser menu settings--> privacy and settings enable location is checked.
What is the problem , any ideas? i really stuck in.
Normally , we accept the website request that wants to share your location.
In android if you do not see the question then in the browser settings advanced--> website settings add your URL to there.
It solves the problem.
i am using the Media class to record from device mic, is sucessful recorded but i can't find the audio file(myrecording.amr) on my android device.
function recordAudio() {
var src = "myrecording.amr";
var mediaRec = new Media(src, onSuccess, onError);
// Record audio
mediaRec.startRecord();
// Stop recording after 10 sec
var recTime = 0;
var recInterval = setInterval(function() {
recTime = recTime + 1;
setAudioPosition(recTime + " sec");
if (recTime >= 10) {
clearInterval(recInterval);
mediaRec.stopRecord();
}
}, 1000);
}
function onDeviceReady() {
app.enabled("btnRecord", true);//IDE widget
}
// onSuccess Callback
//
function onSuccess() {
app.alert("recordAudio():Audio Success");//IDE widget
//app.setValue("labelmobile1", mediaRec.); IDE widget
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Set audio position
//
function setAudioPosition(position) {
app.setValue("label1", position);//IDE widget
}
Where i can find it?
Try this
var filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,<directoryName>);
var src=file.getAbsolutePath()+""myrecording.amr"
Your file will be created inside <directoryName>
My guess that it's created in your Android app home directory, since you are using relative path.
You can check here how to find your home directory:
Android Get Application's 'Home' Data Directory
However, I agree with Mukund. It's much better to specify absolute path in this case.
If you do not specify a path then the Media.startRecord() method will default to putting your file at the location specified by Environment.getExternalStorageDirectory(). Check for it in /sdcard or /mnt/sdcard.
you can find it in the sdcard and the path will be:
"/sdcard/myrecording.amr"