简体   繁体   中英

How can I use variables defined in javascript under functions in other functions. below is my exact Javascript Code

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) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    $(".demo").append("Latitude: " + position.coords.latitude +
        "<br>Longitude: " + position.coords.longitude);
}
var gettingJSON = function() {

    $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "APPID=4a74787aeb02dcb53dcc8c15e29bdfa1", function(json) {
        $(".para").append(JSON.stringify(json));
    });
}

$(document).ready(function() {
    getLocation();
    gettingJSON();
});

Above is my Code I'm getting the following error

jQuery.Deferred exception: lat is not defined ReferenceError: lat is not defined
    at gettingJSON (file:///G:/WebDev/WeatherAPI/js/main.js:19:73)
    at HTMLDocument.<anonymous> (file:///G:/WebDev/WeatherAPI/js/main.js:26:1)
    at j (file:///G:/WebDev/WeatherAPI/js/jquery.min.js:2:29948)
    at k (file:///G:/WebDev/WeatherAPI/js/jquery.min.js:2:30262) undefined
r.Deferred.exceptionHook @ jquery.min.js:2
k @ jquery.min.js:2
jquery.min.js:2 Uncaught ReferenceError: lat is not defined
    at gettingJSON (main.js:19)
    at HTMLDocument.<anonymous> (main.js:26)
    at j (jquery.min.js:2)
    at k (jquery.min.js:2)
gettingJSON @ main.js:19
(anonymous) @ main.js:26
j @ jquery.min.js:2
k @ jquery.min.js:2

The Code is not Working. I'm trying to get use lat and lon from the showPosition Fucntion, but it saying that lat and lon are not defined. I had made lat and lon global variables by not using var keyword. but they are not working. please anyone help me.

If you want to access those variables I'd recommend returning them from the function. Or you could do the same thing using class objects.

I think I've found the issue-

Your getLocation() function doesn't populate lat and lon fast enough, So when gettingJSON() is called lat and lon don't exist yet.

I've tested it with a 5 sec wait here-

$(document).ready(function(){
    getLocation();  
    gettingJSON();
    //checking lon and lat immediatelly
    console.log("lon:"+lon+ "lat:"+ lat);
    //setting a 5 sec timeout, and checking the lon and lat value again
    setTimeout(function(){ 
        console.log('waiting');
        console.log("lon:"+lon+ "lat:"+ lat);
        }, 5000); 
});

console log:

lon: undefined lat: undefined
after wait:
lon: 34.99041030000001 lat: 32.7888574

This is probably because the user doesn't allow the location check fast enough.

Maybe try changing the code like this:

function showPosition(position) {
  lat=position.coords.latitude;
  lon=position.coords.longitude;
  $(".demo").append("Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude); 
  gettingJSON(); //calling gettingJSON here assures that you already have the coordinates
}

Generally, for you to access a variable in all functions, they should have a global scope. This means that they are declared outside the functions.

Your lat and lon function are declared locally inside the showPosition(position) . This means that they can only be accessed by the showPosition(position) function and not the gettingJSON() function.

It should work if you declare var lat=position.coords.latitude; and lon=position.coords.longitude; outside and before the showPosition(position) function.

If you are working on freecodecamp, here is a link where global and local variable scope are explained. FreeCodeCamp: Global Scope , FreeCodeCamp: Local Scope , FreeCodeCamp: Global vs Local Scope

In addition, you did not call the showPosition(position) function remember to do this after adjusting your variable declaration as indicated by one of the comments

I hope this helps.

Put it all into a self-executing function and then declare your variables at the beginning. That way, they're not GLOBAL (you generally don't want to make variables GLOBAL) but they're available to everything in your code:

(function($){
  var lat, lon, x;

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

  function showPosition(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    $(".demo").append("Latitude: " + position.coords.latitude +
      "<br>Longitude: " + position.coords.longitude);
  }

  var gettingJSON = function() {
    $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "APPID=4a74787aeb02dcb53dcc8c15e29bdfa1", function(json) {
      $(".para").append(JSON.stringify(json));
    });
  }

  $(document).ready(function() {
    x = document.getElementById("demo");
    getLocation();
    gettingJSON();
  });

})(jQuery);

To ensure you do get the values of lat, long you could consider changing the structure of your program, and call gettingJSON inside showPosition:

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) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    $(".demo").append("Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude);

    //call gettingJson here, pass it lat, lon values...sure to work if lat,lon is in fact gettting populated.
    gettingJSON(lat, lon);

}
var gettingJSON = function(lat, lon) {

$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "APPID=4a74787aeb02dcb53dcc8c15e29bdfa1", function(json) {
    $(".para").append(JSON.stringify(json));
    });
}

$(document).ready(function() {
    getLocation();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM