Search code examples
jqueryjsongeolocation

rendering data with JSON (weather API)


I'm starting out with JSON, trying to implement a weather app using Open Weather Map's API. I'm trying to return the value for key "name" into <h2 id="city"></h2> based on the user's coordinates, and I'm unsure as to why it's currently not returning anything. I understand something similar has been asked before, but I'm not sure how this applies in this case.

$(document).ready(function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var lati = position.coords.latitude;
      var longi = position.coords.longitude;
      var address = "api.openweathermap.org/data/2.5/weather?lat=" + lati +"&lon=" + longi + "&APPID=*****";

      $.getJSON(address, function(json) {
        $("#city").html(json["name"]);
      });
    });
  }
});

Solution

  • use url like http://api.openweather... instead of api.openweather...

    Else the browser will think it is a relative address and attempt to open it like http://example.com/api.openweather... assuming the page url is http://example.com.

    The rest seems to work. I added the http:// prefix and replaced the API key with mine and the code worked on my environment as expected.