-2

I'm trying to store a variable inside a function into a global variable.

But the global variable outside of the function stays undefined.

Code snippet:

var x = document.getElementById("demo");

function getLocation() {
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
} else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
}
}

var latitude;
var longitude; 

function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + 
"<br>Longitude: " + position.coords.longitude;
 latitude = position.coords.latitude                   
 longitude = position.coords.longitude                 
 console.log(longitude);    // var longitude is set here 
}
console.log(longitude);   // var longitude is undefined here

I want to use the variable outside of the function too, how can I fix this?

Mansur D
  • 1
  • 1
  • 4
  • 3
    You need to execute the function. What is x and where do you define position? – mplungjan Apr 16 '17 at 12:55
  • Function not executed, and your code snippet seems to be incomplete – Christian Esperar Apr 16 '17 at 12:58
  • 1
    Given that these are geocoordinates, I'm guessing that the real problem is [how to return the response from an asynchronous call](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – JJJ Apr 16 '17 at 13:00
  • The geolocation operation is **asynchronous**. Your `showPosition()` function will be called only when the operation (the underlying network request) has completed. – Pointy Apr 16 '17 at 13:14

1 Answers1

-1

Refer this code

<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) {
  console.log("Latitude: " + position.coords.latitude +" Longitude: "          + position.coords.longitude)
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude; 
}
</script>
Richardson. M
  • 852
  • 2
  • 17
  • 28