0

I try this method it's create a global variable but it's not working:

var long;
var lat;
function getLocation() {
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(showPosition);
} else {
  alert("Geolocation is not supported by this browser.");
}
}

function showPosition(position) {
// console.log(position.coords.latitude) 
// console.log(position.coords.longitude) 
lat = position.coords.latitude;
long = position.coords.longitude;
// console.log(lat) 
// console.log(long) 
}

console.log(lat) // the output is undefined
console.log(long) // the output is undefined



window.addEventListener('load', getLocation());

the output is

undefined undefined

how can I have this data outside the function ??

1 Answers1

0

lat and long in your code are local variables, so if you change them in function, the global variables do not change. There are several ways to solve this. One way is to use the object concept.

var location = {long: "", lat: ""}

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

function showPosition(position) {
// console.log(position.coords.latitude) 
// console.log(position.coords.longitude) 
location.lat = position.coords.latitude;
location.long = position.coords.longitude;
// console.log(lat) 
// console.log(long) 
}

console.log(location.lat) // the output is undefined
console.log(location.long) // the output is undefined

window.addEventListener('load', getLocation());

The second way is to return the lat and long values as the outcomes of the function.