Problem with weather app API

Problem with weather app API
0

#1

Hi everyone,

I have been cracking my head around this app for the last few days and I can’t make it work. It seems that I can’t get callback data from API and I have tried both using getJSON and $.ajax. I know many people have posted similar questions on this, but nothing that had worked in the past seems to work in my case. Please if you can detect where the error is in my code, I would appreciate your help. Thanks

$(document).ready(function(){

  var long;
  var lat; 
   
  if (navigator.geolocation){
      navigator.geolocation.getCurrentPosition(function(position){
        long = position.coords.longitude;
        lat = position.coords.latitude;
    
    var html = "api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&APPID=***appi key here****";
       
        $.getJSON(html, function(data){
          var town = data.name;
          var temp = data.main.temp;
          $("#location").html(town);
          $("#temperature").html(temp);
          });
         
        });
}
});

#2

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


#3
  1. Add an error handling function to $.getJSON, which is passed as the second argument. This will give you a better idea of what goes wrong when the function executes.
$.getJSON(html, function(data){
          var town = data.name;
          var temp = data.main.temp;
          $("#location").html(town);
          $("#temperature").html(temp);
          });
         
        }, function(error) {
             // Hi!  I'm an error handler!
            console.error(error);
});
  1. Your URL needs a protocol
    "http://api.openweathermap.org/data/2.5/weather?lat="...

  2. You’re going to run into a problem with getting data from OpenWeatherMap when you (or anyone) connects to CodePen via HTTPS. When you’re on a site that’s securely hosted (the ‘s’ in HTTPS means it’s secured by SSL), then all code that comes from other servers must also be securely hosted. Unfortunately, OpenWeatherMap cheaps out on the free accounts and won’t let you connect via HTTP. Note that this does not mean you shouldn’t use HTTPS, but we need to work around this restriction. You’ll have to use a CORS proxy, which is a server that will do the insecure data fetching for you and then relay that data back to you securely. This is free and easy to use. Simply prepend your URL with the CORS proxy. I recommend http://cors-anywhere.herokuapp.com.

"https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather?lat="...

#4

Thank you!!
I did the changes you mentioned and twisted the code, so now is working. I really appreciate for helping me with this! I would have easily spent another week trying to figure it out!