1

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"]);
      });
    });
  }
});
Community
  • 1
  • 1
gonzalo2000
  • 628
  • 1
  • 8
  • 22

1 Answers1

1

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.

Iceman
  • 6,035
  • 2
  • 23
  • 34
  • Thanks for the heads up! I'm trying it at codepen and am not seeing any change. – gonzalo2000 Aug 06 '16 at 08:22
  • @gonzalo2000 probably wont work in codepen, `navigator` permission issue? are you getting the permission prompt? – Iceman Aug 06 '16 at 08:22
  • Good point. No, I'm not getting the permission prompt. Is this something I can account for in the code, or is there another analogous service that would work? – gonzalo2000 Aug 06 '16 at 08:24
  • 1
    No chances. `Navigator` is a "powerfull feature" as chrome dev team calls it and can be accessed only from `https` and `localhost` i.e secure sources. codepen as well as the code runner here all sandbox and so won't work!! See this: https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins – Iceman Aug 06 '16 at 08:25
  • 1
    Got it. Thanks for the help--it is still a relief to know I was otherwise on the right track. I will work on this from my editor. – gonzalo2000 Aug 06 '16 at 08:29
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/120303/discussion-between-gonzalo2000-and-iceman). – gonzalo2000 Aug 06 '16 at 08:55