Need Help with Local Weather App - Problem getting long & lat

Hey guys, tried to read some other posts first but none could exactly resolve my case. Also tried it on Gitter twice but no response. I hope some of you might help! :wink:

Here’s my JS code so far:

$(function() {
  $("#weather").on("click", function() {
    $.ajax({
      dataType: "json",
      url: "https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather",
      data: {
        lat: navigator.geolocation.getCurrentPosition(function(position) {
          return position.coords.latitude;
        }) + "",
        lon: navigator.geolocation.getCurrentPosition(function(position) {
          return position.coords.longitude;
        }) + "",
        appid: "21b35f3d0bf490f4a1e1f8fa88d5c404"
      },
      success: function(data) {
        console.log(data);
      }
    });
  });
});

I’m trying to provide an additional ‘data’ object to the ajax function so that it appends a query string to the URL with the information the API needs to get me the proper object, i.e. the weather data based on my latitude and longitude. How come it doesn’t work the way I coded it? I expected that the values to the keys ‘lat’ and ‘lon’ were resolved first before used as an argument for creating the query string. But that’s apparently not the case since I always get ‘lon=undefined&lat=undefined’ in my URL. Please help! :slight_smile:

I showed my students how to use another API for this, then nest the weather API call in it.

1 Like

Thanks for the reply, I’m gonna definitively bookmark the video! However, it doesn’t help me with my specific problem right now, since I don’t understand why the code does not work the way I expected it to and I’d like to understand why to learn what I did wrong. :slight_smile:

Thanks for the video. Are you going to share the video for actual weather API. Second video stops at imaage array.
Thanks,

I used https://ipapi.co for getting the latitude and longitude.
It’s ssl and no need to put that herokuapp part in front of it.

You can pass those values to your function which gets the data from openweathermap (which does need the prefix).

1 Like