I'm new to Javascript and the following code is confusing the hell out of me. By my understanding, you can assign values to global variables by dropping the var in front of them, and you don't need to define any initial value when you declare the global in the first place. However, why is the following co开发者_StackOverflowde not working? (By not working I mean that the call to document.write within main() spits out "undefined" for "ulat").
var ulat;
function write(latitude) {
ulat = latitude;
document.write("<h1> This works:" + ulat + "</h1>");
}
function getloc() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
write(position.coords.latitude);
},
function (error) {
switch(error.code) {
case error.TIMEOUT:
alert ('Timeout');
break;
case error.POSITION_UNAVAILABLE:
alert ('Position unavailable');
break;
case error.PERMISSION_DENIED:
alert ('Permission denied');
break;
case error.UNKNOWN_ERROR:
alert ('Unknown error');
break;
}
});
}
else {
alert("Geolocation is not supported by your web browser.");
}
}
function main() {
getloc();
document.write("<h1> This doesn't work: " + ulat + "</h1>");
}
Any help? Thanks!
getCurrentPosition
is asynchronous. It doesn't run when you call it, it starts running when you call it. So when main
checks for a value, the success callback hasn't been called, and nothing has been assigned to ulat
.
So here's what your code does:
main
gets calledmain
callsgetloc
getloc
sees that geolocation is available and starts a geolocation request. Then it returns immediately.main
outputs the value ofulat
, which is stillundefined
.- Some time later, your
success
callback (or, of course, failure) gets called. At that point, I'm a bit surprised that your page doesn't go blank, because you'll be callingdocument.write
after the main parse, which implies adocument.open
, which tears down the page and starts with a blank slate. But I don't usedocument.write
often enough to remember all the vagaries...
You need to call main: 'main();'
var
is for local variables. For global variables give the reference alone or as window.reference
. Try modifying your code to remove the first line var ulat;
.
精彩评论