I need to pack the user's current location into an object and send it to a PHP script. So, I currently have the following.
position object
function position(lat, lon) {
this.latitude = lat;
this.longitude = lon;
this.setlat = function(lat) {
this.latitude = lat;
};
this.setlon = function(lon) {
this.longitude = lon;
};
this.print = function() {
alert(this.longitude + ", " + this.latitude);
};
}
control flow
var origin = new position(0, 0);
$(document).ready(function() {
getLocation();
origin.print();
});
Functions
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setLocation, showError, {timeout:60000});
} else {
alert("GeoLocation is not supported on this browser or device.");
return null;
}
}
function setLocation(position) {
alert('callback success!');
origin.setlat(position.coords.latitude);
origin.setlon(position.coords.longitude);
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
console.log("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
console.log("Location information is unavailable.");
break;
case error.TIMEOUT:
console.log("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
console.log("An unknown error occurred.");
break;
}
}
The problem is that before the callback is called, the setLocationmain control flow continues and ignores the fact that I asked him to get something for me. I call getLocation and I get the warning "0, 0", since it was initially set. Therefore, for some reason, my callback is setLocationsimply not called until everything else in the program is completed.
I looked through the documentation, but it is quite simple, and not so much happens, so it is difficult to determine why this is happening.
, , , , - " ", , , , -.
, , , .
navigator.geolocation.getCurrentPosition() while, , .
- maximumAge timeout PositionOptions, , setLocation .
- $(document).ready(function(){});, getLocation() origin.print().
- watchPosition getCurrentPosition.
, getCurrentPosition , .