0

I have a page on which I am showing the weather.

I make calls to the Weatherbit.io API to get the information. Part of the information they need is the latitude and longitude of the location.

For some reason, the lat_lon variable I am setting at the beginning of my JavaScript file is not accessible to some functions I have further down in the file. Whenever I try to use it, I keep getting an "undefined" error.

index.html:

<head>
    <script type="text/javascript" src="./JavaScript.js"></script>
</head>
<body onload="startup();">
    ...
</body>

JavaScript.js:

var lat_lon = "lat=37.600000&lon=-95.665047";

function startup(){
    if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(function(position){
            lat_lon = "lat=" + position.coords.latitude + "&lon=" + position.coords.longitude;
            console.log("FIRST: " + lat_lon);
        });
    }
    console.log("SECOND: " + lat_lon);

    weatherFunctionCurrent(lat_lon);
    weatherIntervalVarCurrent = setInterval(weatherFunctionCurrent, 600000);
}

// .
// .
// .

weatherFunctionCurrent(lat_lon){
    console.log("IN THE weatherFunctionCurrent FUNCTION: " + lat_lon);
}

Say my actual lat/lon is: lat=123.4 and lon=-123.4

SECOND: lat=37.600000&lon=-95.665047
IN THE weatherFunctionCurrent FUNCTION: lat=37.600000&lon=-95.665047
FIRST: lat=123.4&lon=-123.4
IN THE weatherFunctionCurrent FUNCTION: undefined
IN THE weatherFunctionCurrent FUNCTION: undefined
IN THE weatherFunctionCurrent FUNCTION: undefined
IN THE weatherFunctionCurrent FUNCTION: undefined
.
.
.

I tried var window.lat_lon = "" but Chrome did not like that. I received the error

Uncaught SyntaxError: Unexpected token '.'

What am I doing wrong?

Brian
  • 1,726
  • 2
  • 24
  • 62
  • 1
    `weatherFunctionCurrent(lat_lon) { /* ...*/ }` - you're shadowing the global `lat_lon` with this parameter. Just remove it. Or pass in an argument. – VLAZ Jun 03 '21 at 19:34

1 Answers1

1

pass the lat_ton to your function:

weatherIntervalVarCurrent = setInterval(weatherFunctionCurrent(lat_lon), 600000);
Aa. Ai
  • 31
  • 3
  • This will *call* the function, it wouldn't schedule it to execute regularly. You need `setInterval(weatherFunctionCurrent, 600000, lat_lon)` or `setInterval(() => weatherFunctionCurrent(lat_lon), 600000)` See: [Pass parameters in setInterval function](https://stackoverflow.com/q/457826) – VLAZ Jun 03 '21 at 19:42