I have a question about geolocation and the javascript variable scope. Ive been toying around with it a bit but I'm a php guy, js is not my best language. Im making a google map and I want to set the users coords as the map center and set a zoom. If the request fails/is denied then I'm hitting a web service to get their approximate coords from the IP. I would like to get the position/zoom back from the getLocation() function, but I can't get the information out of navigator.geolocation.getCurrentPosition()
I've tried returning the object from within the error and position functions but it looks like its not set up for that, I can't get anything back but an error code. I thought I might be able to set the var and then overwrite it but I can't get it to return anything but undefined, I still don't 100% understand scope and hoisting enough to find the solution.
the geolocFail() works as expected, returning the object correctly. Since its called from the error function within navigator.geolocation.getCurrentPosition - I can't get the information out of there.
function getLocation() {
var mapLocation;
if (navigator.geolocation) {
var location_timeout = setTimeout("geolocFail()", 10000);
navigator.geolocation.getCurrentPosition(
function(position) {
clearTimeout(location_timeout);
mapLocation = {position: position.coords.latitude + "," + position.coords.longitude, zoom:10};
}, function(error) {
clearTimeout(location_timeout);
switch(error.code) {
case error.PERMISSION_DENIED:
alertDiv.innerHTML="<p class='text-danger'>User denied the request for Geolocation.</p>";
break;
case error.POSITION_UNAVAILABLE:
alertDiv.innerHTML="<p class='text-danger'>User Location information is unavailable.</p>";
break;
case error.TIMEOUT:
alertDiv.innerHTML="<p class='text-danger'>The request to get user location timed out.</p>";
break;
case error.UNKNOWN_ERROR:
alertDiv.innerHTML="<p class='text-danger'>An unknown error occurred.</p>";
break;
}
mapLocation = geolocFail();
});
}
else {
// Fallback for no geolocation
alertDiv.innerHTML="<p class='text-danger'>Geolocation is not supported by this browser.</p>";
mapLocation = geolocFail();
}
}
function geolocFail(){
//fallback to webservice
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");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if (typeof callback == "function") {
// apply() sets the meaning of "this" in the callback
callback.apply(xmlhttp);
}
}
}
xmlhttp.open("GET","/map/determineLocation?t=" + Math.random(),true);
xmlhttp.send();
if(this.responseText){
var mapLocation = {position: this.responseText, zoom:10}
}
else{
var mapLocation = {position: "40.0000,-100.0000", zoom:4};
}
return mapLocation;
}