I have a problem concerning the geolocation function in my android app and used the code below to test this default functionality (copied 1:1 from the phonegap website), but somehow can't get it to work.
When I build the android app the geolocation function does absolutely nothing, not an error, nothing. However when I test it in a browser everything works and a location is retrieved. All location services on the phone are turned on, when I turn them off, I do get the appropriate error message.
When I test the geolocation functionality in the phone's browser it does work.
I am testing on the Galaxy Nexus (android 4)
Dreamweaver CS 5.5 (updated today)
Latest Android sdk (updated today)
Manifest file is default, everything is permitted
Can somebody please help me out, I am starting to become really desperate as I can’t get this standard code to work.
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
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: ' + new Date(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>
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.
Let me first start by saying that I have seen a lot of these questions, and many of them just says it <script src="cordova-x-x-x.js"></script> and some says not include the cordova.js file into Phonegap Build.
So I have been testing and fixing my code for some time now, and still getting the error from onError function. I have also copied and pasted the code from phonegap docs.
So here's the clean code from the url:
<!DOCTYPE html>
<html>
<head>
<title>Acceleration Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);
}
function onSuccess(acceleration) {
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
}
function onError() {
alert('onError!');
}
</script>
</head>
<body>
</body>
</html>
And in my config.xml file I have added:
<gap:plugin name="org.apache.cordova.device-motion" />
<gap:plugin name="org.apache.cordova.device-orientation" />
After testing and asking the Phonegap Build crew, they showed me a code with all the functions. And this is the best way to get the accelerometer to work with Phonegap Build
<!DOCTYPE html>
<html>
<head>
<title>Device Ready Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
alert("Device is Ready");
alert(device.available);
}
function getAcceleration(){
navigator.accelerometer.getCurrentAcceleration(onAccelSuccess, onError);
}
function onAccelSuccess(acceleration) {
var element = document.getElementById('accelerometer');
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp + '<br />';
}
function onError() {
alert('onError!');
}
function startWatch() {
// Update acceleration every 1 seconds
var options = { frequency: 1000 };
watchID = navigator.accelerometer.watchAcceleration(onAccelSuccess, onError, options);
}
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
</script>
</head>
<body onload="onLoad()">
<p>
<button onclick="getAcceleration()">Get Acceleration</button>
</p>
<p>
<button onclick="startWatch()">Watch Acceleration</button>
</p>
<p>
<button onclick="stopWatch()">Stop Watching Acceleration</button>
</p>
<div id="accelerometer">Waiting for accelerometer...</div>
</body>
</html>
I would say you try a total clean reinstall/rebuild with cordova. First off all you have to install cordova for that. If you want to know, how to get started with that you should have a look into the cordova documentation: Cordova CLI-Docs
After you installed cordova, you enter the Terminal and type in the following commands:
cd ~/desktop
cordova create test com.example.test test
cd test
cordova platform add android
cordova plugin add org.apache.cordova.device-motion
cordova build
Open the builded project in Eclipse and add
<!DOCTYPE html>
<html>
<head>
<title>Acceleration 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() {
navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);
}
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
}
// onError: Failed to get the acceleration
//
function onError() {
alert('onError!');
}
</script>
</head>
<body>
<h1>Example</h1>
<p>getCurrentAcceleration</p>
</body>
</html>
Save all and deploy the project to your device. And let me know, if this worked or not.
Can't comment, so answering instead.
In reference to above comment re "Phonegap and Cordova are similar (Same codebase)"
From http://docs.build.phonegap.com/en_US/3.1.0/introduction_getting_started.md.html:
To do so, simply ensure that the following reference is made in your
index.html
<script src="phonegap.js">
Note that this is interchangeable with
<script src="cordova.js">
I'm trying to get my location coordinates with HTML5 but it gives me error every time .
this is the code I have write to phone gap android project
I used the same code on the documentation of the phone gap geolocation .
and add the call for the function device-ready () to know if this code is running
and it gives me
error 2 : messege 2 : the last location provider was disabled
this is the code that I'm using to get my location on the android device !
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// PhoneGap is ready
//
function onDeviceReady() {
// Update every 3 seconds
var options = { frequency: 3000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
//alert("the lang is : "+position.coords.latitude);
document.write("the lang is : "+position.coords.latitude);
}
// clear the watch that was started earlier
//
function clearWatch() {
if (watchID != null) {
navigator.geolocation.clearWatch(watchID);
watchID = null;
}
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body>
<p id="geolocation">Watching geolocation...</p><br>
<button onclick="onDeviceReady();">onDeviceReady()</button> <br>
<button onclick="clearWatch();">Clear Watch</button> <br>
index 2
</body>
</html>
I got this tutorial from here http://docs.phonegap.com/en/1.7.0/cordova_geolocation_geolocation.md.html#Geolocation !
Hope to suggest what shall I do !!
Try setting the option enableHighAccuracy to true
this is my code:
function onDeviceReady() {
console.log("Device Ready");
startWatch();
};
function startWatch() {
// Update acceleration every 5 seconds
var options = { frequency: 5000 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
};
function onSuccess(acceleration){
console.log('Acceleration X: ' + acceleration.x +
'Acceleration Y: ' + acceleration.y +
'Acceleration Z: ' + acceleration.z +
'Timestamp: ' + acceleration.timestamp);
};
function onError(){
console.log("Acceleration Error occured");
};
I test it on 2 Android Phones (Samsung Galaxy Nexus GT-I9250, Android 4.0 and Huawei Ideos X3, Android 2.3.3), from my console outputs I know both only call the Error Callback, but why?
I can't find the cause for this on google, so please help if you have an Idea.
You might have a timing issue.
You should try the following which runs successfully on my HTC Evo or post your whole app:
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.3.0.js"></script>
<script type="text/javascript" charset="utf-8">
function onDeviceReady() {
console.log("Device Ready");
startWatch();
};
function startWatch() {
// Update acceleration every 5 seconds
var options = { frequency: 5000 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, accelerometerError, options);
};
function onSuccess(acceleration){
alert('Acceleration X: ' + acceleration.x +
'Acceleration Y: ' + acceleration.y +
'Acceleration Z: ' + acceleration.z +
'Timestamp: ' + acceleration.timestamp);
};
function accelerometerError(){
alert("Acceleration Error occured");
};
function init() {
document.addEventListener("deviceready", onDeviceReady, true);
}
</script>
</head>
<body onload="init();" id="stage" class="theme">
</body>
</html>
Could it be because you are passing in a reference that does not exist to your watchAccelerometer() call?
You are passing in onError, but the name of your handler is accelerometerError
Here is a thought. I have not tested this (my Mobile Dev machine is at home), but it occurs to me that you may need to tell Android devices that you want to use the accelerometer in your Android Manifest.
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
Do you have that setting in your manifest XML file?