Hi everyone
I have a bit of JavaScript code that I need a bit of help with. It concerns Local and Global scoped variables. In the code sample below, and in the function showLocation, are the two problem variables. If I un-comment the two document.writes, then obviously I can see the two values. But if I leave them commented and go to the bottom of this snippet, then the same two variables are blank.
I have read somewhere online that if you declare a variable outside a function, it is a Global variable and can be used within a function, presumably similar to my code below. But it doesn't work?
What I am trying to do is use GeoLocation to get my Latitude and Logitude (which this snippet does, but only within the Function) and then make use of these two variables later on within the same PHP/JavaScript page.
So my question is this.. How can I make use of a variable, created within a Function, outside of that Function?
Thanks
Terry
var latitude = "";
var longitude = "";
period = "oneday";
formDate = "<?php echo $formDate;?>";
offset = "<?php echo $summerTime;?>";
function showLocation(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
//document.write("Latitude 1: " + latitude + "<br/>"); // Variable correct if un-commented
//document.write("Longitude 1: " + longitude + "<br/>"); // Variable correct if un-commented
}
function getLocation(){
if(navigator.geolocation){
var options = {timeout:60000};
navigator.geolocation.getCurrentPosition(showLocation,errorHandler,options);
}else{
alert("Sorry, browser does not support geolocation!");
}
}
document.write("JavaScript-Latitude 2: " + latitude + "<br/>"); // Variable is blank
document.write("JavaScript-Longitude 2: " + longitude + "<br/>"); // Variable is blank
document.write("JavaScript-Period: " + period + "<br/>");
document.write("JavaScript-FormDate: " + formDate + "<br/>");
document.write("JavaScript-Offset: " + offset + "<br/>");