navigator.geolocation.watchPosition - frequency - javascript

I tried this code :
<!DOCTYPE html>
<html>
<head>
<title>Location Location Location</title>
<script type="text/javascript" charset="utf-8">
var watchID = null;
// PhoneGap is ready
//
function f() {
// Update every 1 ms seconds
var options = {enableHighAccuracy: true,timeout: 5000,maximumAge: 0,desiredAccuracy: 0, frequency: 1 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var str = 'Latitude: ' + position.coords.latitude + '<br>' +
'Longitude: ' + position.coords.longitude + '<br>' +
'Timestamp: ' + position.timestamp + '<br>' ;
var url = "load.php";
var params = "data="+str;
xmlhttp.open("GET", url+"?"+params, true);
document.body.innerHTML += str;
document.writeln("line 33");
xmlhttp.send();
//document.writeln("send");
//document.writeln(str);
}
// 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>
<button onclick="f();"> Watch</button>
</body>
</html>
you can see that i add
var options = {......, frequency: 1 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
But I am getting new result if and only if I enter to tab and exit and enter agin.
What can I do?

The spec makes no mention of a frequency option which suggests that this parameter is being ignored. W3C Geolocation spec

You code seems to be working fine: http://jsfiddle.net/Mgk9J/1/
I tested it in Android and when I move the cellphone new lines came up. However in chrome desktop it plots new lines when I change tabs even though they're identical to the last ones, according to the spec this isn't the correctly behavior.
It makes a bit of sense for the desktop version do not plot new lines anyway, the computer isn't moving so new success calbacks execution should not be fired.
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="/js/lib/dummy.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
</style>
<script type="text/javascript">//<![CDATA[
window.onload=function(){
var watchID = null;
// PhoneGap is ready
//
function f() {
// Update every 1 ms seconds
var options = {enableHighAccuracy: true,timeout: 5000,maximumAge: 0,desiredAccuracy: 0, frequency: 1 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var str = 'Latitude: ' + position.coords.latitude + '<br>' +
'Longitude: ' + position.coords.longitude + '<br>' +
'Timestamp: ' + position.timestamp + '<br>\r\n' ;
document.getElementById('result').value += str;
}
// 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');
}
document.getElementById('button').addEventListener('click', f);
}//]]>
</script>
</head>
<body>
<p id="geolocation">Watching geolocation...</p>
<button id="button"> Watch</button>
<textarea id="result" cols="100" rows="10"></textarea>
</body></html>

Related

Tizen web app works on simulator, but doesn't work on gear 3

I'm trying to develop an app that reads data from the acceleration sensor, and save it on a text file. Using web app development, I've managed to make the app work on the emulator, but when I tried it on Samsung Gear 3 frontier, it didn't work. Can some figure out what I did wrong?
Below are the html and the java script code.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,user-scalable=no">
<title>Basic</title>
<link rel="stylesheet" href="lib/tau/wearable/theme/default/tau.min.css">
<link rel="stylesheet" media="all and (-tizen-geometric-shape: circle)" href="lib/tau/wearable/theme/default/tau.circle.min.css">
<!-- load theme file for your application -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="ui-page ui-page-active" id="main">
<header>
<h2 class="ui-title">TAU Basic</h2>
</header>
<div class="ui-content ui-content-padding">
<p id="readings"> Basic </p>
</div>
</div>
<script src="lib/tau/wearable/js/tau.min.js"></script>
<script src="js/app.js"></script>
<script src="js/lowBatteryCheck.js"></script>
<script src="js/circle-helper.js"></script>
</body>
</html>
Java script code:
function init() {
console.log("app started");
document.getElementById("readings").innerHTML="Starting";
accelerationSensor=tizen.sensorservice.getDefaultSensor("ACCELERATION");
if (accelerationSensor){
console.log("Sensor captured");
}
/* Update the clock hands every second */
accelerationSensor.start(onsuccessCB);
setInterval(function() {
updateTime();
}, 1000);
}
window.onload = init();
function onGetSuccessCB(sensorData)
{
var datetime = tizen.time.getCurrentDateTime();
var Date = ("0" + datetime.getHours()).slice(-2) + ":" +
("0" + datetime.getMinutes()).slice(-2) + ":" +
("0" + datetime.getSeconds()).slice(-2);
console.log(Date);
console.log("######## Get acceleration sensor data ########");
console.log("x: " + sensorData.x);
console.log("y: " + sensorData.y);
console.log("z: " + sensorData.z);
x = sensorData.x;
y = sensorData.y;
z = sensorData.z;
tizen.filesystem.resolve("documents", function(dir)
{
var newFile = dir.resolve("newFilePath.txt");;
newFile.openStream(
"a",
function(fs) {
fs.write(Date+"\t x:"+x+"\t y:"+y+"\t z:"+z+"\n");
fs.close();
}, function(e) {
console.log("Error " + e.message);
}, "UTF-8");
},function(){
document.getElementById("readings").innerHTML="Error";
});
document.getElementById("readings").innerHTML="Reading";
}
function onerrorCB(error)
{
console.log("error occurred: " + error.message);
}
function onsuccessCB()
{
console.log("acceleration sensor start");
var datetime = tizen.time.getCurrentDateTime();
var hour = datetime.getHours(),
var minute = datetime.getMinutes(),
var second = datetime.getSeconds();
tizen.filesystem.resolve("documents", function(dir)
{
newFile = dir.createFile("newFilePath.txt");
newFile.openStream(
"w",
function(fs) {
fs.write(hour+":"+minute+":"+second+"\tstart of recording \n");
fs.close();
}, function(e) {
console.log("Error " + e.message);
}, "UTF-8");
},function(){
document.getElementById("readings").innerHTML="Error";
});
}
function updateTime() {
accelerationSensor.getAccelerationSensorData(onGetSuccessCB, onerrorCB);
}
(function () {
window.addEventListener("tizenhwkey", function (ev) {
var activePopup = null,
page = null,
pageid = "";
if (ev.keyName === "back") {
activePopup = document.querySelector(".ui-popup-active");
page = document.getElementsByClassName("ui-page-active")[0];
pageid = page ? page.id : "";
if (pageid === "main" && !activePopup) {
try {
tizen.application.getCurrentApplication().exit();
} catch (ignore) {
}
} else {
window.history.back();
}
}
});
}());
Thanks in advance.
I've managed to find the solution, and I post it for helping others who would face the same issue.
It turns out that there is no acceleration sensor in S3, and everything works fine when I change the sensor from Acceleration to linear_acceleration. The codes for both html and javascript are as follow:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,user-scalable=no">
<title>Basic</title>
<link rel="stylesheet" href="lib/tau/wearable/theme/default/tau.min.css">
<link rel="stylesheet" media="all and (-tizen-geometric-shape: circle)" href="lib/tau/wearable/theme/default/tau.circle.min.css">
<!-- load theme file for your application -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="ui-page ui-page-active" id="main">
<header>
<h2 class="ui-title">TAU Basic</h2>
</header>
<div class="ui-content ui-content-padding">
<p id="readings"> Basic </p>
</div>
</div>
<script src="lib/tau/wearable/js/tau.min.js"></script>
<script src="js/app.js"></script>
<script src="js/lowBatteryCheck.js"></script>
<script src="js/circle-helper.js"></script>
</body>
</html>
The javascript:
var accelerationSensor;
function onsuccessCB() {
console.log("acceleration sensor start");
var datetime = tizen.time.getCurrentDateTime();
var hour = datetime.getHours();
var minute = datetime.getMinutes();
var second = datetime.getSeconds();
tizen.filesystem.resolve("documents", function(dir) {
var newFile = dir.createFile("newFilePath.txt");
newFile.openStream(
"w",
function(fs) {
fs.write(hour + ":" + minute + ":" + second + "\tstart of recording \n");
fs.close();
document.getElementById("readings").innerHTML = "Reading";
},
function(e) {
document.getElementById("readings").innerHTML = "File Error";
}, "UTF-8");
});
}
function init() {
console.log("app started");
document.getElementById("readings").innerHTML = "Starting";
accelerationSensor = tizen.sensorservice.getDefaultSensor("LINEAR_ACCELERATION");
document.getElementById("readings").innerHTML = "Starting1";
if (accelerationSensor) {
console.log("Sensor captured");
document.getElementById("readings").innerHTML = "Acceleration";
} else {
document.getElementById("readings").innerHTML = "Error";
}
/* Update the clock hands every second */
accelerationSensor.start(onsuccessCB);
document.getElementById("readings").innerHTML = "onsuccessCB done";
console.log("onsuccessCB done");
setInterval(function() {
updateTime();
}, 1000);
}
window.onload = init();
function onGetSuccessCB(sensorData) {
var datetime = tizen.time.getCurrentDateTime();
var Date = ("0" + datetime.getHours()).slice(-2) + ":" +
("0" + datetime.getMinutes()).slice(-2) + ":" +
("0" + datetime.getSeconds()).slice(-2);
console.log(Date);
console.log("######## Get acceleration sensor data ########");
console.log("x: " + sensorData.x);
console.log("y: " + sensorData.y);
console.log("z: " + sensorData.z);
var x = sensorData.x;
var y = sensorData.y;
var z = sensorData.z;
tizen.filesystem.resolve("documents", function(dir) {
var newFile = dir.resolve("newFilePath.txt");
newFile.openStream(
"a",
function(fs) {
fs.write(Date + "\t x:" + x + "\t y:" + y + "\t z:" + z + "\n");
fs.close();
},
function(e) {
console.log("Error " + e.message);
}, "UTF-8");
}, function() {
document.getElementById("readings").innerHTML = "Error";
});
document.getElementById("readings").innerHTML = "Reading";
}
function onerrorCB(error) {
console.log("error occurred: " + error.message);
}
function updateTime() {
accelerationSensor.getLinearAccelerationSensorData(onGetSuccessCB);
}
(function() {
window.addEventListener("tizenhwkey", function(ev) {
var activePopup = null,
page = null,
pageid = "";
if (ev.keyName === "back") {
activePopup = document.querySelector(".ui-popup-active");
page = document.getElementsByClassName("ui-page-active")[0];
pageid = page ? page.id : "";
if (pageid === "main" && !activePopup) {
try {
tizen.application.getCurrentApplication().exit();
} catch (ignore) {}
} else {
window.history.back();
}
}
});
}());
The above code will get linear_acceleration sensor readings, and save them to a text file in "Documents" folder.
You need filesystem.read and filesystem.write privileges to have access to "Document" folder.

how to append to div id

i know it is easy and silly question but how can i show the lat and lng append into div id instead of giving me on alert.Can i do something like that !!
document.getElementById("here").innerHTML = ("lat: +lat+"lng: " + lng)
<!DOCTYPE>
<html>
<meta name="viewport" content="width=device-width,
initial-scale=1, maximum-scale=1,user-scalable=no">
<head>
<script>
function geolocation(){
<!--checks if geolocation is available -->
var options = { enableHighAccuracy: true};
watchId = navigator.geolocation.watchPosition(onSuccess, onError, options);
<!-- function run if gets the geolocation back -->
function onSuccess(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
alert("lat: " + lat + "lng: " + lng);
}
<!-- this function run if there is any error in geolocation -->
function onError(error){
alert("message: " + error.message);
}
}
geolocation();
</script>
</head>
<body>
<div id="here"></div>
</body>
You may try something like this: Edit: Updated HTML
<div id="location"></div>
<script>
$( document ).ready(function() {
geolocation();
}
function geolocation(){
<!--checks if geolocation is available -->
var options = { enableHighAccuracy: true};
watchId = navigator.geolocation.watchPosition(onSuccess, onError, options);
<!-- function run if gets the geolocation back -->
function onSuccess(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//alert("lat: " + lat + "lng: " + lng);
document.getElementById("location").innerHTML = "lat: " + lat + "lng: " + lng;
}
<!-- this function run if there is any error in geolocation -->
function onError(error){
alert("message: " + error.message);
}
}
</script>
Ok So, I think what you want is this:
div = document.getElementById('here');
div.appendChild(watchId);
Thats how you append to your particular div.
Yes, it's possible, with the property innerHTML you wrote you should solve your problem.
Yes, you definetely can. However, the string you provided is not quoted correctly. Don' t you get an exception in console?
document.getElementById("here").innerHTML = "lat: " + lat + "lng: " + lng;
Using jQuery you can simply do this:
$("#here").text("lat: " + lat + " lng: " + lng");
Or if you want to keep the content of here and append the information at the end:
$("#here").append("lat: " + lat + " lng: " + lng");

Cordova: HTML5 geolocation - find the nearest place from JavaScript array

I have array of places in JavaScript. I need to get gps geolocation from gps sensor (on mobile phone using Apache Cordova).
If GPS accuracy is better than for example 40 meters, I need to do something (set css display:block, change color, ...).
I have this code:
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/distance.js"></script> <!-- https://github.com/janantala/GPS-distance/blob/master/javascript/distance.js -->
<script type="text/javascript" charset="utf-8">
var interval = 5; // [s]
var timeout = 60; // [s]
/* --------------------------------------------------- */
var latitude = new Array();
var longtitude = new Array();
var nameOfLocation = new Array();
// address 1
// Latitude : 10.20 | Longitude : 30.40
latitude[0] = 10.20;
longtitude[0] = 30.40;
nameOfLocation[0] = "address 1";
// address 2
// Latitude : 40.30 | Longitude : 20.10
latitude[1] = 40.30;
longtitude[1] = 20.10;
nameOfLocation[1] = "address 2";
// ...
/* --------------------------------------------------- */
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
console.log('in onDeviceReady()');
$(document).ready(function(){
setInterval(function(i) {
navigator.geolocation.getCurrentPosition(onSuccess, onError, {
maximumAge: 0,
timeout: (timeout*1000),
enableHighAccuracy: true }
);
}, (interval*1000))
});
}
// onSuccess Geolocation
function onSuccess(position) {
console.log('in onSuccess()');
console.log(position.coords.latitude, "position.coords.latitude");
console.log(position.coords.longitude, "position.coords.longitude");
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 />';
var place;
var accuracy;
$("#accuracy").html("GPS accuracy " + position.coords.accuracy + " m.");
if (position.coords.accuracy < 40) {
$("#accuracy").css("background-color", "Gray");
for (var i=0; nameOfLocation.length; i++) {
var distance = getDistance(latitude[0], longitude[0], position.coords.latitude, position.coords.longitude);
if (distance <= 25) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "OrangeRed");
} else if (distance <= 20) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "Yellow");
} else if (distance <= 15) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "Green");
}
}
$("#info").html("You are about <strong>" + accuracy + "</strong> meters from location <strong>" + nameOfLocation[i] + "</strong>");
} else {
$("#info").html("");
}
}
// onError Callback receives a PositionError object
function onError(error) {
console.log('in onError()');
console.log(error.code, "error.code");
console.log(error.message, "error.message");
$("#geolocation").html(
'code: ' + error.code + '<br />' +
'message: ' + error.message);
$("#accuracy").css("background-color", "");
}
</script>
</head><body>
<p id="info"></p>
<hr />
<p id="accuracy"></p>
<hr />
<p id="geolocation">GPS ...</p>
</body></html>
I use this JS lib for distance measurement of two GPS locations https://github.com/janantala/GPS-distance/blob/master/javascript/distance.js
I can't use google online gps distance lib. App must work without internet connection.
If I run app it start location gps. After first finding location any next finding take only about 5 seconds and after that stop finding locations (this repeats to infinity). I need permanent searching.
Do you know where is an error?
I'm going to do it well?

Why does getting a LocalStorage item yield “undefined”?

We are using PhoneGap to develop a pedometer app using the iPhone accelerometer.
Below is a copy of the code we are currently running:
<!DOCTYPE html>
<html>
<head>
<title>Accelerometer</title>
<script type="text/javascript" charset="utf-8" src="js/cordova-1.7.0rc1.js"></script>
<script type="text/javascript" charset="utf-8">
// The watch id references the current `watchAcceleration`
var watchID = null;
var stepCount = 0;
window.localStorage.setItem('exp');
var expGain = 0;
var totalExp = window.localStorage.getItem('exp');
var userAge = window.localStorage.getItem('age');
var handicap = 0;
if (userAge <= 10) {
handicap = 10;
} else if (userAge > 10) {
handicap = 5;
}
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//e7
function onDeviceReady() {
startWatch();
}
// Start watching the acceleration
//
function startWatch() {
// Update acceleration every 5 seconds
var options = {
frequency: 1000
};
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
// Stop watching the acceleration
//
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
//count steps and calculate experience gained
function countSteps(accelx, timestamp, expGain, totalExp) {
var element = document.getElementById('accelerometer');
//var accCount = Math.round(acceleration.x);
//stepCount = stepCount + Math.abs(accCount);
stepCount = stepCount + 1;
expGain = stepCount * handicap;
totalExp = totalExp + expGain;
//window.localStorage.setItem('exp', totalExp);
element.innerHTML = '<br>Step Count: ' + stepCount + '<br/>' +
'Acceleration X: ' + Math.abs(accelx) + '<br />' +
'Timestamp: ' + timestamp + '<br />' +
'Experience: ' + totalExp + '<br />';
}
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');
var accelx = Math.round(acceleration.x)
var timestamp = acceleration.timestamp
//element.innerHTML = 'Acceleration X: ' + Math.abs(accelx) + '<br />' +
//'Acceleration Y: ' + acceleration.y + '<br />' +
//'Acceleration Z: ' + acceleration.z + '<br />' +
//'Timestamp: ' + acceleration.timestamp + '<br />';
if (Math.abs(accelx) > 1) {
countSteps(accelx, timestamp, expGain, totalExp);
}
}
// onError: Failed to get the acceleration
//
function onError() {
alert('onError!');
}
</script>
<link media="only screen and (max-device-width: 480px)" href="css/iPhone.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="accelerometer">Waiting for accelerometer...</div>
<button onclick="startWatch();">Start Watching</button>
<button onclick="stopWatch();">Stop Watching</button>
<br />
<p>back
</p>
</body>
</html>
The issue is: we keep getting an "undefined" next to our result for window.localStorage.setItem('exp');. We have been working all day to try and work this one out.
setItem takes two arguments (a key and a value). If you don't specify an argument, then undefined is the default value.
window.localStorage.setItem('exp'); means window.localStorage.setItem('exp', undefined);
If you want it to have some other value, then you need to specify it.
Doesn't localStorage.setItem require a second parameter? Have you tried:
window.localStorage.setItem("exp","");

Why does my JavaScript code fire prematurely?

I have an event listener added in onDeviceReady to listen for back button event, and respond with stopWatch when it is pressed. However it responds when the app is started.
<!DOCTYPE html>
<html>
<head>
<title>UNH BSApp</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
// The watch id references the current `watchAcceleration`
var watchID = null;
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
document.addEventListener("backbutton", stopWatch(), false);
startWatch();
}
// Start watching the acceleration
//
function startWatch() {
document.addEventListener("menubutton", stopWatch(), false);
// Update acceleration every 0.1 seconds
var options = { frequency: 10 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
// Stop watching the acceleration
//
function stopWatch() {
alert("Hello!");
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(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 />';
}
// onError: Failed to get the acceleration
//
function onError() {
alert('onError!');
}
</script>
<style>
#start {
display:block;
border:solid;
}
</style>
</head>
<body>
<div id="accelerometer">Waiting for accelerometer...</div>
<div id="start">Start</div>
</body>
</html>
document.addEventListener("menubutton", stopWatch(), false);
This calls the stopWatch function immediately. You want something like:
document.addEventListener("menubutton", stopWatch, false);
^^ no parens!
Remove the () from the setup of the listener - this is calling the function not passing it as an argument :
document.addEventListener("menubutton", stopWatch, false);

Categories

Resources