Speed Coordinate shows null value in GeoLocation PhoneGap - javascript

i am creating android application that gets Lat Lng and check the speed of user i am using PhoneGap GeoLocation Api but i am getting only Longitude and Latitude but in Altitude and Speed it shows null
here is the JavaScript that i get from PhoneGap website
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
var options = { enableHighAccuracy: true };
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('time');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + new Date(position.timestamp) + '<br />';
setTimeout('loop();',100);
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function loop(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
</script>
I am check this in Android Mobile as well as emulator same result both places that is null
The Html part is
<body>
<p id="time">Finding geolocation...</p>

Source
it might be device specific, as to whether or not those parameters are supported "If the implementation cannot provide {those variables you're having trouble with} information, the value of this attribute must be null."

Related

Cordova geolocation plugin doesn't work on android

I'm using cordova ,geolocation plugin for showing latitude and longitude on android. There are plenty of question same as this so I read and tried their solution but couldn't fix the problem. The code below works perfectly on browser.
I tried 3 method, first: "navigator.geolocation.watchPosition" which returns wrong result(37.42,-122.08) in emulator(Android Studio) and doesn't return anything in device.
I also tried "navigator.geolocation.getCurrentPosition" with both "enableHighAccuracy" set 'true' and 'false' and I get timeOut error alerted.
When I delete deviceready, I don't get the timeOut, just wrong result from all three methods.
(function (window) {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var minAccuracyInMetres = 50;
var positionWatcher;
positionWatcher = navigator.geolocation.watchPosition(
geolocationSuccess2,
geolocationError2,
{ maximumAge: 0, timeout: 100000, enableHighAccuracy: true });
function geolocationSuccess2(position) {
// Reject if accuracy is not sufficient
if (position.coords.accuracy > minAccuracyInMetres) {
return;
}
// Only single position required so clear watcher
navigator.geolocation.clearWatch(positionWatcher);
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');
};
function geolocationError2(error) {
console.warn("Error while retrieving current position. " +
"Error code: " + error.code + ",Message: " + error.message);
}
//2
var onSuccess1 = 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');
};
function onError1(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n' + 'highaccuracy: true');
}
var options1 = { maximumAge: 0, timeout: 300000, enableHighAccuracy: true };
navigator.geolocation.getCurrentPosition(onSuccess1, onError1, options1);
//3
var onSuccess = function (position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n')
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n' + ' high accuracy:false');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: false, timeout: 300 * 1000, maximumAge: 0 });
}
})(window);
I get the watchPosition part from another question in stackoverflow.
I use cordova version: 6.4.0.
I deleted the plugin and tried again but it didn't work.
the device I'm testing with is a lenovo tablet.
Thanks a lot.
UPDATE: my Geolocation version is: 2.4.0 Is it important???
After two days of struggling I turned on "High accuracy" in location settings. The app Works now!!!

How to launch Navigator in cordova in ios

I have an app where (AngularJs+cordova), I need to get current position of the user and navigate to destination using google maps.
I am unable to get it work in iOS:
I have tried:
/* $scope.launchNavigator = function() {
console.log("$scope.launchNavigator...");
var deviceType = (navigator.userAgent.match(/iPad/i))  == "iPad" ? "iPad" : (navigator.userAgent.match(/iPhone/i))  == "iPhone" ? "iPhone" : (navigator.userAgent.match(/Android/i)) == "Android" ? "Android" : (navigator.userAgent.match(/BlackBerry/i)) == "BlackBerry" ? "BlackBerry" : "null";
cordova.plugins.diagnostic.isLocationEnabled(onRequestSuccess, onRequestFailure);
if(deviceType === 'Android'){
cordova.plugins.locationAccuracy.request(onRequestSuccess, onRequestFailure, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
}
else {
// vm.showGPSAlert = true;
// vm.GPSTextAlert = "Please enable Location Services in Settings and Try again"
//function onDeviceReady() {
cordova.plugins.diagnostic.switchToLocationSettings();
//navigator.geolocation.getCurrentPosition(onSuccess, onError);
//}
}
}
function onRequestSuccess(success){
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
}
function onSuccess(position){
console.log('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');
latitudeStart = position.coords.latitude;
longitudeStart = position.coords.longitude;
launchnavigator.isAppAvailable(launchnavigator.APP.GOOGLE_MAPS, function(isAvailable){
var app;
console.log("Location navigate .lat." + )
if(isAvailable){
app = launchnavigator.APP.GOOGLE_MAPS;
}else{
console.warn("Google Maps not available - falling back to user selection");
app = launchnavigator.APP.USER_SELECT;
}
launchnavigator.navigate([vm.dest.latitude,vm.dest.longitude], {
app: app,
start: [latitudeStart,longitudeStart]
});
});
}
function onError(){
}
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();
}
}
}*/
<--the above doesn't work for both iOS and Android-->
For android, following works:
/*Get Direction*/
function onDeviceReady() {
//window.open = cordova.InAppBrowser.open;
console.log("Hello... Device redy");
var latitudeStart = '';
var longitudeStart = '';
$scope.launchNavigator = function() {
function onRequestSuccess(success){
console.log("Successfully requested accuracy: "+success.message);
if(navigator.geolocation){
console.log("navigator.geolocation works well");
}
else{
console.log("navigator.geolocation doesnt works well");
}
console.log("Luanch navigate..");
var onSuccess = function(position) {
console.log('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');
latitudeStart = position.coords.latitude;
longitudeStart = position.coords.longitude;
launchnavigator.isAppAvailable(launchnavigator.APP.GOOGLE_MAPS, function(isAvailable){
var app;
if(isAvailable){
app = launchnavigator.APP.GOOGLE_MAPS;
}else{
console.warn("Google Maps not available - falling back to user selection");
app = launchnavigator.APP.USER_SELECT;
}
launchnavigator.navigate([vm.dest.latitude,vm.dest.longitude], {
app: app,
start: [latitudeStart,longitudeStart]
});
});
};
// onError Callback receives a PositionError object
//
function onError(erro) {
console.log('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError,{enableHighAccuracy:true});
}
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 above doesn't work for both iOS and Android
Firstly, I would use cordova-plugin-device to determine the platform rather than user agent sniffing - it is more robust.
Secondly, it appears you have a function dependent on the deviceready event which is invoked on the successful outcome of a plugin result:
function onRequestSuccess(success){
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
}
Cordova plugins are dynamically loaded before the deviceready event is invoked, so it's likely that the inner function is never invoked.
Thirdly, the success callback function for both cordova.plugins.diagnostic.isLocationEnabled() and cordova.plugins.locationAccuracy.request() appears to be onRequestSuccess().
Both of the former are invoked in serial synchrony but their callbacks are invoked asynchronously, so this is likely to lead to problems.
I would try something like this:
function onDeviceReady(){
console.log("onDeviceReady...");
$scope.launchNavigator = function() {
console.log("$scope.launchNavigator...");
cordova.plugins.diagnostic.isLocationEnabled(function(enabled){
if(!enabled){
if(device.platform === 'Android'){
cordova.plugins.locationAccuracy.request(getCurrentPosition,
function(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_PRIORITY_HIGH_ACCURACY);
}
else {
// vm.showGPSAlert = true;
// vm.GPSTextAlert = "Please enable Location Services in Settings and Try again"
//function onDeviceReady() {
cordova.plugins.diagnostic.switchToLocationSettings();
//navigator.geolocation.getCurrentPosition(onSuccess, onError);
//}
}
}else{
getCurrentPosition();
}
}, function onLocationEnabledFailure(error){
console.error("Failed to check if location is enabled");
});
function getCurrentPosition(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
function onSuccess(position){
console.log('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');
latitudeStart = position.coords.latitude;
longitudeStart = position.coords.longitude;
launchnavigator.isAppAvailable(launchnavigator.APP.GOOGLE_MAPS, function(isAvailable){
var app;
console.log("Location navigate .lat." + )
if(isAvailable){
app = launchnavigator.APP.GOOGLE_MAPS;
}else{
console.warn("Google Maps not available - falling back to user selection");
app = launchnavigator.APP.USER_SELECT;
}
launchnavigator.navigate([vm.dest.latitude,vm.dest.longitude], {
app: app,
start: [latitudeStart,longitudeStart]
});
});
}
function onError(positionError){
// Handle Error
}
} //$scope.launchNavigator
}// onDeviceReady
In general, I would highly recommend using Safari Remote Debugging and Chrome Remote Debugging tools to debug your app while running on iOS and Android devices respectively.
Using the step-through debugger with appropriate breakpoints will highlight issues such as those present in your code snippet.
See the Debugging Cordova apps section in the Cordova docs for details.

How to use appendTo to display information instead of in an alert box?

I'm a newbie so thanks in advance for any help.
I am setting up a simple geolocation page.
Currently when I click a button, an alert popup box states the geolocation settings.
The problem - instead of the result popping up in a box, I need the geolocation info to display on the page itself.
I was told I need to use the appendTo element and I've tried many different ways but nothing happens.
Here is the current script:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Geolocation</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.
js"</script>
<section>
<script>
$(document).ready(function() {
$('#startGeo').click(checkLocation);
function checkLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getLocation,
locationFail);
}
else {
document.write('You do not have geolocation');
}
}
function getLocation(position) {
var latitude = position.coords.latitute;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var timestamp = position.coords.timestamp;
alert('latitude: ' + latitude + 'longitude: ' + longitude +
'accuracy: ' + accuracy + 'timestamp: ' + timestamp);
}
function locationFail() {
document.write('We did not get your location. Please check your
settings.')
}
});
</script>
</head>
<body>
<button id="startGeo">Click here to check your geolocation
abilities</button>
</body>
</html>
Create a container in your html
<div id="geoDisplay"></div>
Then create an element containing the geolocation and append it to the new container.
$('<div>latitude: ' + latitude + ' longitude: ' + longitude +
' accuracy: ' + accuracy + ' timestamp: ' + timestamp + '</div>')
.appendTo($('#geoDisplay'));
Now every time you click the button, it will append a div containing the geolocation information.
Insert a <p class="data"></p> in your document
Replace:
alert('latitude: ' + latitude + 'longitude: ' + longitude +
'accuracy: ' + accuracy + 'timestamp: ' + timestamp);
}
With:
$('.data').html('latitude: ' + latitude + 'longitude: ' + longitude +
'accuracy: ' + accuracy + 'timestamp: ' + timestamp);
}
Here is a simple way of using append, which is very similar to appendTo, just with a different syntax:
$('body').append('latitude: ' + latitude + 'longitude: ' + longitude + 'accuracy: ' + accuracy + 'timestamp: ' + timestamp);
You need to create an element and add it to your DOM. For example:
var coordlabel = '<label>latitude: ' + latitude + 'longitude: ' + longitude +
'accuracy: ' + accuracy + 'timestamp: ' + timestamp + '</label>';
$('body').append(coordlabel);
I assume you are asking how to get your string:
'latitude: ' + latitude + 'longitude: ' + longitude + 'accuracy: ' + accuracy + 'timestamp: ' + timestamp
inside an existing node on the DOM.
If this is the case, then please read the remaining information in this post because there are some things you need to know.
DOM stands for the Document Object Model.
Nodes are your html Elements that can be manipulated by Javascript using selectors. Example. JQUERY: $('#element') is a node selector.
If you are wanting to use Jquery to output your string generated by javascript then you would do:
var str = 'latitude: ' + latitude + 'longitude: ' + longitude + 'accuracy: ' + accuracy + 'timestamp: ' + timestamp;
$('#element').text(str);
http://jsfiddle.net/amLtprmt/
This will not append the Node, i do not believe that is what you were trying to do.
To do this in native JavaScript you would do:
var node = document.getElementById('element');
var str = 'latitude: ' + latitude + 'longitude: ' + longitude + 'accuracy: ' + accuracy + 'timestamp: ' + timestamp;
node.innerHTML = '';
node.appendChild(document.createTextNode(str));
http://jsfiddle.net/56tp7te1/
This is assuming your html looks similar to:
<html>
<body>
<div id='element'></div>
</body>
</html>

Phonegap worked fine but now it isn't

A strange thing is happend with cordova, even the simpliest code doesn't work anymore. The code worked fine enough but since yesterday it isn't. I didn't change anything in the manifest.xml or any other file. Is it my device?
<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 Cordova to load
//
function onload(){
document.addEventListener("deviceready", onDeviceReady, false);
}
// Cordova is ready
//
function onDeviceReady() {
alert('test')
var element = document.getElementById('deviceProperties');
console.log('test');
element.innerHTML = 'Device Name: ' + device.name + '<br />' +
'Device Cordova: ' + device.cordova + '<br />' +
'Device Platform: ' + device.platform + '<br />' +
'Device UUID: ' + device.uuid + '<br />' +
'Device Model: ' + device.model + '<br />' +
'Device Version: ' + device.version + '<br />';
}
</script>
Now I can't run cordova anymore. This is what I get in logcat:
05-15 11:46:33.478: I/CordovaLog(26092): Changing log level to DEBUG(3)
05-15 11:46:33.478: I/CordovaLog(26092): Found preference for useBrowserHistory=true
05-15 11:46:33.478: D/CordovaLog(26092): Found preference for useBrowserHistory=true
05-15 11:46:33.478: I/CordovaLog(26092): Found preference for exit-on-suspend=false
05-15 11:46:33.478: D/CordovaLog(26092): Found preference for exit-on-suspend=false
05-15 11:46:33.483: I/CordovaLog(26092): Found preference for loadingDialog=MORE, Loading...
05-15 11:46:33.483: D/CordovaLog(26092): Found preference for loadingDialog=MORE, Loading...
05-15 11:46:33.503: D/JsMessageQueue(26092): Set native->JS mode to 2
05-15 11:46:33.508: D/DroidGap(26092): DroidGap.init()
05-15 11:46:33.618: D/CordovaWebView(26092): >>> loadUrl(file:///android_asset/www/index.html)
05-15 11:46:33.618: D/PluginManager(26092): init()
05-15 11:46:33.623: D/CordovaWebView(26092): >>> loadUrlNow()
05-15 11:46:33.628: D/DroidGap(26092): Resuming the App
05-15 11:46:33.688: D/SoftKeyboardDetect(26092): Ignore this event
05-15 11:46:33.698: D/DroidGap(26092): onMessage(onPageStarted,file:///android_asset/www/index.html)
05-15 11:46:34.088: D/SoftKeyboardDetect(26092): Ignore this event
05-15 11:46:36.068: D/Cordova(26092): onPageFinished(file:///android_asset/www/index.html)
05-15 11:46:36.068: D/DroidGap(26092): onMessage(onNativeReady,null)
05-15 11:46:36.068: D/DroidGap(26092): onMessage(onPageFinished,file:///android_asset/www/index.html)
05-15 11:46:38.068: D/DroidGap(26092): onMessage(spinner,stop)
05-15 11:46:38.353: W/dalvikvm(26092): disableGcForExternalAlloc: false
What is wrong?
The phonegap plugins: camera, accelerator etc. works but the geolocation not.
This is the code all permissions are installed like before:
<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 Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
console.log('test');
alert('test');
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
console.log(position.coords.latitude);
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>
But the variable "position" isn't set or something, this plugin was working before now it ain't. :(

PhoneGap deviceready event not firing

I'm developing a web application using PhoneGap 1.5.0 but I'm unable to fire deviceready event.
The cordova-1.5.0.js I'm using was located at PhoneGap 1.5.0\lib\android\ and I'm testing at several Android devices without success.
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert("onDeviceReady");
}
</script>
</head>
<body>
<p id="deviceProperties">Loading device properties...</p>
</body>
</html>
First of all You need to test it as an application and not on the web browser.
Secondly if you want to use geolocation then you can use it like this
<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>
i never could get cordova-1.5.0 to fire deviceready as expected on android (api 8).. no problem after switching to 1.6.1, however.

Categories