Weather API - Need help

Hi. I’ve been stuck on this for agessss. For some reason my lat and lon come out as 0 when I check the console after the getLocation is called and I just can’t figure out how to fix it

$(document).ready(function() {

var lat = 0;
var lon = 0;

var getLocation = function() {
  
  if(navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(displayPosition);
  } else {
    alert("This browser does not support geolocation");
  }
  
  function displayPosition(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
  }
}
  
$.when(getLocation).done(function() {
$.ajax ({
  type: "GET",
  dataType: "json",
  url: "https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=19c9b893457b8f5ea0d0d040c080d04d",
  success: function(data) {
    alet(data.weather);
  }
  
    
});
});

       });

Please help, I have no idea what’s wrong with my code

Are you using chrome ?

Yes but i tested it out in other browsers and still had the same issue

I think your code is fine. The problem is you’re using an object with your alert(). The alert method only accepts strings, so javascript coerces your object received from the ajax request into a string representation of the object. Use console.log() instead or if you’re keen on using alert() you can override the toString() prototype to fit your use case. Checkout this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

1 Like

Hi there,

Have a look at the result of your query in http://api.openweathermap.org/data/2.5/weather?lat="%20+%20lat%20+%20"&lon="%20+%20lon%20+%20"&appid=19c9b893457b8f5ea0d0d040c080d04d

Choose the data item that you want to alert/display like so:

alert(data.weather[0].main);

or

alert(data.weather[0].description)

“weather” is a nested array so to access its data you gotta add [0] to it.

Hope this helps!