Java script logic error - javascript

I am new to Java scripting and need quick help. Here is my code:
<html>
<head>
<title> GeoLocation Application </title>
<script>
$counter=0;
while ($counter < 10) {
if (!navigator.geolocation) {
alert('Your browser does not support geolocation');
} else {
navigator.geolocation.getCurrentPosition(success, error);
document.write("Count ",$counter,"<br>");
}
$counter ++;
}
function success(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
alert (lat +','+lng);
document.write("calling update mysql");
//document.location='update_java_data.php?lat=' + lat+'&lng='+lng;
}
function error(error) {
alert('an erro occured, error code is '+error);
}
</script>
</head>
<body>
<h1> Hello </h1>
</body>
</html>
I am trying to get coordinates using navigator 10 times. But when I am seeing only a quick list of counter display from 0 to 9, but only once it displays ""calling update mysql".
To me it means it only executed success function once.
Any idea how I can make it get the coordinate 10 times (means it should also call success function 10 times I guess)?

I would suggest instead looking at using the setInterval function to do your lat/long collection at specified intervals... If what you have above runs successfully, it would probably collect the same point 10 times quickly.
So, since you do those function calls without any type of a wait/interval, they all fire off at basically the same time (0-9 counter display)... As for only seeing the 'calling update mysql' once, I would imagine that it has something to do with you changing the location of the window to a different url, and the other calls not being able to reach the success function since you have already mo

Related

Javascript console logging 2 times the function using geolocation api from the browser

SCRIPT
"<script>
function success(pos) {
console.log('Your current position is:');
console.log(`Latitude : ${pos.coords.latitude}`);
console.log(`Longitude: ${pos.coords.longitude}`);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error);
</script>"
Hey all, I have this script in the HTML file, and when I run the html, the console log 2 times the latitude, and longitude. What can the problem be?
I tried to remove everything down just to sucess function and the last line "navigator...", but it still happens.
I only want the script to display 1 time latitude and longitude.

Geolocation doesn't work with cordova

I'm currently working on a mobile application with Intel XDK (In background it's Cordova finally, that's why I put Cordova in title.)
With an Ajax request, I get some adresses and with these adresses I want to calculate the distance between them and the current position of user.
So, I get adresses, I convert them and I make the difference.
But actually, nothing is working !
function codeAddress(id, addresse) {
geocoder.geocode( { 'address': addresse}, function(results, status) {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function(){}, 100);
}
console.log(id);
console.log(addresse);
//document.addEventListener("intel.xdk.device.ready",function(){
if (navigator.geolocation)
{
if (status == google.maps.GeocoderStatus.OK)
{
navigator.geolocation.getCurrentPosition(function(position) {
addressEvent = results[0].geometry.location;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var position = new google.maps.LatLng(pos.lat, pos.lng)
var resultat = google.maps.geometry.spherical.computeDistanceBetween(addressEvent, position);
console.log(resultat);
console.log(addressEvent);
console.log(pos);
console.log(position);
var convert = Math.floor(resultat);
var finalConvert = convert + " m";
var distance = document.createElement('span');
distance.innerHTML = finalConvert;
distance.className = "geo";
document.getElementsByClassName('meta-info-geo')[id].appendChild(distance);
}, function() {
handleLocationError(true, infoWindow);
});
}
}
//},false);
});
}
In the console.log(id), console.log(addresse), I HAVE results !
Actually i'm getting 4 IDs and 4 adresses.
I checked on all the topics I could find on StackOverFlow, and I had normally to add the line in // with the addEventListener but it changes nothing.
Is there someone who knows how to change that ?
ps : Of course, cordova geoloc is in the build and permissions are granted !
EDIT : I'm targeting Android 4.0 min and iOS 5.1.1. I'm using SDK.
EDIT 2 :
Geolocation frequently does not work the way people expect it to work, for a variety of reasons that have been expressed here and here.
You can experiment with geo by using the "Hello, Cordova" sample app that is in the XDK and also available on GitHub. Try using it on a variety of devices to see how things work. Push the "fine" button to initiate a single geo call for a "fine" location and push the "coarse" button to initiate a single geo call for a "coarse" location. Push the "watch" button to initiate a request for a series of geo data points (set to coarse or fine by pushing one of the single buttons first).
The behavior you get in the Emulate tab will be dramatically different than what you get on a real device. The type of device (Android, iOS, etc.) and the version of that device will influence your results; the manufacturer of the device and your location (inside or outside) will influence your results. Do not assume that making a call to the geo APIs will always give you immediate and reliable data, geolocation hardware does not work that way... In fact, you cannot assume that you can even get a valid result! See the two links I pointed to earlier in the post for some reasons why.

Safari and Firefox have different behaviour on dojo ready function

As dojo 1.7> don't provide OnLoad status handling, some nice features such as OnLoad in Jquery not really support by Dojo. Dojo have a similar feature such as ready or DomReady is close to OnLoad, let us have a look.
I had some dojo form fields need to be checked on the page loaded. Those fields mainly was used to hold browser geoLocation information to facilitate user find local business information, I need a OnLoad function to check browser have geoLocation support or not, if it is, dojo script will populate user browser latitude and longitude information to a dojo form fields, other wise, I need enable an other field such as postcode to be changed to "required" to ask user provide his local postcode.
My dojo script looks like:
<script type="text/javascript">
require(["dojo/ready","dojo/dom","dojo/dom-attr"], function(ready,dom,domAttr){
ready(function(){
var Geo = {};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(success, error);
}else{
}
function success(position) {
Geo.lat = position.coords.latitude;
Geo.lng = position.coords.longitude;
populateHeader(Geo.lat, Geo.lng);
}
function error() {
console.log("Geocoder failed");
domAttr.set(dom.byId("criteria_postcode"),"required",true);
}
function populateHeader(lat, lng) {
dom.byId("criteria_latitude").value=Number(lat);
dom.byId("criteria_longitude").value=Number(lng);
}
});
});
</script>
This function supposed will be load on DOM ready, but it never work properly. criteria_postcode field never be set to required in the page.
I also tried to test on submit event function by using dojo script, my code looks like:
<script type="dojo/on" data-dojo-event="submit">
if(this.validate()){
require(["dijit/focus", "dojo/dom", "dojo/domReady!"], function(focusUtil,dom){
// fetch a node by id="someNode"
var pcnode = dom.byId("criteria_postcode");
var latnode = dom.byId("criteria_latitude");
var lngnode = dom.byId("criteria_longitude");
console.log(pcnode.value+"|"+latnode.value+"|"+lngnode.value);
});
return confirm('Form is valid, press OK to submit');
}
This paragraph of dojo script will print out a console log and waiting for user click ok to confirm before submit to server.
Unfortunately, firefox works but not for safari, safari print out the console log after submit, is that true? I was confused.
domReady is the right approach, but instead of doing it aty submit time, you should do it at load time.
also defining all function and then running the navigator.geolocation is better:
<script type="text/javascript">
require(["dojo/dom","dojo/dom-attr","dojo/domReady!"], function(dom,domAttr){
var Geo = {};
function success(position) {
Geo.lat = position.coords.latitude;
Geo.lng = position.coords.longitude;
populateHeader(Geo.lat, Geo.lng);
}
function error() {
console.log("Geocoder failed");
domAttr.set(dom.byId("criteria_postcode"),"required",true);
}
function populateHeader(lat, lng) {
dom.byId("criteria_latitude").value=Number(lat);
dom.byId("criteria_longitude").value=Number(lng);
}
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(success, error);
}else{
}
});
</script>
At submit time, you obviously don't need to use dojo/domReady! (DOM is ready otherwise user could not submit)

Javascript: how to programmatically kill an alert after X seconds

When asking for permission for geolocation the user gets a popup window asking for geolocation permission.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
}
Lets say the user doesn't respond after 5 seconds, I would like to "force the errorCallback".
How would I do so?
Thanks.
According the MDN, the third argument to getCurrentPosition() is an options object that allows you to specify a timeout value.
The documentation specifies that the timeout value is the max time allowed to wait for the GPS position, so you'd have to test it to see if it also includes the time waiting for the user to respond to a permission prompt.
I guess, it's more or less up to the browser how to handle the fact that the user is not replying on the question about permission.
Anyhow, a workaround could be a redirect after a given time:
<html>
<body>
<h1>My page</h1>
<script>
var userdidnothing=false;
function TimeoutHandler() {
if (!userdidnothing) {
window.location.href="http://www.yoursecondpage.com";
}
}
setTimeout("TimeoutHandler();",5000);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function() {
userdidnothing=true;
alert("SUCCESS");
},
function() {
alert("ERROR");
});
}
</script>
Geolocation feature is helpful, if you need to know where you are...
</body>
</html>

Accessing location using Javascript

I run the code shown below from different places but this results in same latitude and longitude value at different places.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body onload="getLocation()">
<p id="demo"> </p>
<script>
var x= document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML= position.coords.latitude;
x.innerHTML= position.coords.longitude;
var lat=position.coords.latitude;
var lon=position.coords.longitude;
}
</script>
**strong text**</body>
</html>
Any help would be appreciated.
In short, the problem isn't with your code, but most likely with your device. I can tell you're using the demo code from the W3Schools article on the geolocation API. That code seems to work fine for me, at least as much as I would expect.
Geolocation isn't terribly precise in all cases. According to MDN, the method use to determine location will be the most accurate available for your device at that time. If you're testing on a desktop browser, the results might be no more accurate than to the nearest city, and in some cases even more inaccurate than that (My home in Michigan registers as the middle of New York state, for some weird reason). If you test on a 3g or 4g phone, you might get better results, down to the nearest broadcast area. If you test on a phone with GPS, you might get highly accurate data, where you'll notice a difference if you move even a few feet or so. I say 'might' for these cases, because location data is a huge privacy concern area, and there's a lot of things that might interfere with geolocation to protect a user's privacy.
If you're seeing the same result from relativly small moves, this would easily be the cause. If you've travelled a few hundred miles to run your code elsewhere, then I would have to admit that there's something

Categories