Weather API app[HELP]

Weather API app[HELP]
0

#1

Hi, I’m having a hard time trying to understand why console.log(api) is showing ‘‘undefined’’ when it was supposed to show the geolocation.

I would appreciate a lot if someone could help me with this project

Thanks


#2

Well first of all did you sign up for an API key ?

It appears to me you are trying to use the ‘demonstration’ key as in the examples to access. You need to register your own account to get your own key. I would at least start from there because I believe that is at least is part of what is causing the ensuing

net::ERR_INSECURE_RESPONSE

error.

The key, once registered, would go here: ‘&appid= your key here’


#3

Hi,

Thanks for replying, I did what you said and it still showing that

samples. openweathermap. org/data/2.5/weather?lat=UNDEFINED&lon=UNDEFINED&appid=e7c4a7db8187caa7fc3e50e1806f4786"


#4

For one you should be using the following as the base URL for the API call (make sure to read the API docs closely).

https://api.openweathermap.org/data/2.5/weather?

Also it helps to sometimes first test the call in just the browser window to make sure you don’t any key problems, etc. Using the key you provided, put this in an open browser window:

https://api.openweathermap.org/data/2.5/weather?lat=25&lon=115&appid=e7c4a7db8187caa7fc3e50e1806f4786


#5

Second of all, you are using ‘lat’ and ‘long’ out of the variable scope. Also, you want to console.log ‘json’ (the return data) not ‘api’ (the variable you used to specify the address to call the API).

I made these changes and posted a fork here:

https://codepen.io/abalducci/pen/opwzYr

You can see it is now working. Please take note as I will remove the fork in a bit.

Hope this helps.


#6

The following line:

var api = 'https://samples.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+lon+'&appid=e7c4a7db8187caa7fc3e50e1806f4786';

is outside the navigator.geolocation.getCurrentPosition callback function. Because getCurrentPosition is an asynchronous function, other code after this call will go ahead an execute even though a response (the actual lat/lon coordinates) so lat and lon only have there original value of undefined, because you declared them at the start of your code. All declared but uninitialized variables have undefined values by default in JavaScript. To make use of the coordinates which lat and lon to get inside the callback function, you need to define the api variable inside the callback function along with making the getJSON call. Also beaware that getJSON is also asynchronous, so it will behave the same. If you move the console.log(api) into the callback function after assigning values to lat and lon, you will see the url in the console.


#7

@RandellDawson @abalducci Thank you both I really appreciated your help