Weather App - Dark Sky API Issue

Weather App - Dark Sky API Issue
0.0 0

#1

Just started working on the weather app. It looks like this code is sending a request for the JSON but the lat and long variables come out as undefined.

var conditions;
var tempF;
var tempC;
var icon;
var lat;
var long;
var weather;

$(document).ready(function() {

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
});
}

$.getJSON(“https://api.darksky.net/forecast/556c1ca549a3ce16469d8670260c3a1d/” + lat + “,” + long,
function(data) {
conditions = data.currently.summary;
tempF = data.currently.temperature;
tempC = (tempF - 32) / 1.8;
icon = data.currently.icon;
});

weather = "The weather is ";
weather += conditions;

$("#input").html(weather);
});

error looks like:
api.darksky.net/forecast/556c1ca549a3ce16469d8670260c3a1d/undefined,undefined Failed to load resource: the server responded with a status of 400 (Bad Request)

Not sure why the code isn’t working?

My codepen is here: https://codepen.io/dkane47/pen/wePzqy


#2

There’s a couple things happening – your lat and long variables aren’t accessible to the API call because they’re set within the scope of the geolocation callback, so you’ll need to restructure your call so those values are accessible to the API request, and then to the jQuery method adding it to the page. I used a separate function as the geolocation callback, within which used the position variable and hit the API.

You’re also getting a CORS error, which is common for this project. I wound up using the OpenWeatherMap API and prepended the request URL with https://cors-anywhere.herokuapp.com to get around the origin error.