Values Not Being Passed Using API & JS - javascript

I'm creating a simple application to get the user's coordinates, plug them into the Forecast API, and get back the current weather. Things seem to be working smoothly for the first 2 parts but when it's all put together, the coordinates are not passed properly into the API call even though they are printed just fine. Pretty confused and appreciate any help.
<!DOCTYPE html>
<html>
<body>
<p>Here's the weather:<p>
<p id="weather"><p>
<p>Here's the coordinates:<p>
<p id="coordinates"><p>
<button onclick="b()">Submit</button>
<script>
function b(){
var apiKey = 'b04dbf475994a98f5849aa6856a4596d';
var url = 'https://api.forecast.io/forecast/';
var data;
var lati = 0;
var longi = 0;
navigator.geolocation.getCurrentPosition(getCoordinates);
function getCoordinates(position) {
lati = position.coords.latitude;
longi = position.coords.longitude;
}
$.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data) {
console.log(data);
$('#weather').html(data.currently.temperature);
$('#coordinates').html(lati + "," + longi);
});
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</body>
</html>

Try adding the $.get into your function that collects the geolocation. I suspect that is asynchronous.
function getCoordinates(position) {
lati = position.coords.latitude;
longi = position.coords.longitude;
$.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data) {
console.log(data);
$('#weather').html(data.currently.temperature);
$('#coordinates').html(lati + "," + longi);
});
}

Related

Trying to pass geolocation lat and longi to another function so that it can display certain data, what am i doing wrong?

I want the longitude and latitude passed from the geolocation function to my getjson function so that i can pull certain info like temperature, condition etc. What am i doing wrong that the lati and loni are not being passed properly? Are my functions set up correctly?
$(window).load(function() {
getLocation();
apiCall();
}); //run immediately on page load
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lati = position.coords.latitude;
var loni = position.coords.longitude;
function passData(lati, loni);
}
var weath = 0;
function apiCall() {
function passData(latitude, longitude) {
var lati = latitude;
var loni = longitude;
x.innerHTML = "Latitude: " + lati +
"<br>Longitude: " + loni;
}
//$(".city").html(data.city + "," + "" + data.countryCode);
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + lati + "&lon=" + loni, function(data1) {
weath = Math.round(data1.main.temp);
$(".temp").html(weath + " " + "&#8451");
$(".condition").html(data1.weather[0].description);
$(".iconDisplay").append('<img src=' + data1.weather[0].icon + '/>');
}); /*end of json*/
};

Location and weather based image search API for weather app

I am making a basic web-based weather app, which detects the current weather conditions in the user's location. My current code so far does work, but is missing an important feature - I want the background of the web page to change according to the user's location and weather conditions. For instance - if a user is in New York and the weather is sunny, I would like to display any New York based popular image(ex: Times Square) along with sunny skies as the body background. I've searched several APIs but haven't found any that meets my needs.
In my current code, I'm using IPInfo.io to get the user's location and OpenWeatherMap to get the weather conditions.
This pen has my code (NOTE - code for units hasn't been added yet), and here's the JS bit -
var lat = 0.0,
lon = 0.0;
var testURL = 'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=2de143494c0b295cca9337e1e96b00e0';
var myURL = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid="ae0acb60e8db4952e081c2fb470a1b23"';
var city = '',
state = '',
country = '',
postal = 0;
//if (navigator.geolocation) {
// /* geolocation is available */
// navigator.geolocation.getCurrentPosition(function (position) {
// lat = position.coords.latitude;
// lon = position.coords.longitude;
// console.log("Latitude = " + lat);
// console.log("Longitude = " + lon);
//
// display(position.coords.latitude, position.coords.longitude);
// });
//
//} else {
// /* geolocation IS NOT available */
// $("#jumbotron").html("geolocation not available");
//
//}
//get co-ordinates using ipinfo.io
$.getJSON('http://ipinfo.io', function (data) {
console.log(data);
var loc = data.loc;
lat = loc.split(",")[0];
lon = loc.split(",")[1];
display(lat, lon);
city = data.city;
state = data.region;
country = data.country;
postal = parseInt(data.postal, 10);
})
function display(x, y) {
$("#pos1").html("<b>" + x + "</b>");
$("#pos2").html("<b>" + y + "</b>");
}
//function to calculate wind direction from degrees
function degToCompass(num) {
//num = parseInt(num, 10);
console.log("Inside degtocompass = " + num);
var val = Math.floor((num / 22.5) + 0.5);
var arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
return arr[(val % 16)];
}
//function to return current temperature
function convertTemp(currTemp) {
//get celsius from kelvin
return Math.round(currTemp - 273.15);
}
$("button").click(function () {
console.log("In Latitude = " + lat);
console.log("In Longitude = " + lon);
//prepare api call
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid=ae0acb60e8db4952e081c2fb470a1b23',
//url: testURL,
type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
data: {}, // Additional parameters here
dataType: 'json',
success: function (data) {
console.log(data);
//---------get the clipart---------------
var picLink = 'http://openweathermap.org/img/w/';
var picName = data.weather[0].icon;
picLink += picName + ".png";
$("#picture").empty().append('<img src="' + picLink + '">');
//----------get the temperature-----------
var curTemp = convertTemp(data.main.temp);
console.log("Current temp = " + curTemp);
//$("#temp").empty().append("<b>" + curTemp + "</b>");
$("#picture").append("<b>" + curTemp + "</b>");
//----------get the place----------------------
var area = city + ", " + state + ", " + country;
$("#area").empty().append("<b>" + area + "</b>");
//----------get weather conditions------------
$("#conditions").empty().append("<b>" + data.weather[0].description + "</b>");
//----------get wind speed------------
//get wind direction
var windSpeed = degToCompass(data.wind.deg);
//add wind speed
windSpeed += ' ' + data.wind.speed;
//display wind speed
$("#wind-speed").empty().append("<b>" + windSpeed + "</b>");
},
error: function (err) {
alert(err);
},
beforeSend: function (xhr) {
//xhr.setRequestHeader("X-Mashape-Authorization", "32ROUuaq9wmshfk8uIxfd5dMc6H7p1lqdZSjsnXkB5bQtBteLK"); // Enter here your Mashape key
}
});
});
Well... First of all there is no need to use WebServices, but you can't do it without any API. As I can see you use openweathermap API . As far as I know this API returns both longitude and latitude, so you can use these values as input to another request to a photo API (like flickr) to get the image you want. Moreover openweathermap API returns city name which can make your photo request even more accurate.

how to append to div id

i know it is easy and silly question but how can i show the lat and lng append into div id instead of giving me on alert.Can i do something like that !!
document.getElementById("here").innerHTML = ("lat: +lat+"lng: " + lng)
<!DOCTYPE>
<html>
<meta name="viewport" content="width=device-width,
initial-scale=1, maximum-scale=1,user-scalable=no">
<head>
<script>
function geolocation(){
<!--checks if geolocation is available -->
var options = { enableHighAccuracy: true};
watchId = navigator.geolocation.watchPosition(onSuccess, onError, options);
<!-- function run if gets the geolocation back -->
function onSuccess(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
alert("lat: " + lat + "lng: " + lng);
}
<!-- this function run if there is any error in geolocation -->
function onError(error){
alert("message: " + error.message);
}
}
geolocation();
</script>
</head>
<body>
<div id="here"></div>
</body>
You may try something like this: Edit: Updated HTML
<div id="location"></div>
<script>
$( document ).ready(function() {
geolocation();
}
function geolocation(){
<!--checks if geolocation is available -->
var options = { enableHighAccuracy: true};
watchId = navigator.geolocation.watchPosition(onSuccess, onError, options);
<!-- function run if gets the geolocation back -->
function onSuccess(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//alert("lat: " + lat + "lng: " + lng);
document.getElementById("location").innerHTML = "lat: " + lat + "lng: " + lng;
}
<!-- this function run if there is any error in geolocation -->
function onError(error){
alert("message: " + error.message);
}
}
</script>
Ok So, I think what you want is this:
div = document.getElementById('here');
div.appendChild(watchId);
Thats how you append to your particular div.
Yes, it's possible, with the property innerHTML you wrote you should solve your problem.
Yes, you definetely can. However, the string you provided is not quoted correctly. Don' t you get an exception in console?
document.getElementById("here").innerHTML = "lat: " + lat + "lng: " + lng;
Using jQuery you can simply do this:
$("#here").text("lat: " + lat + " lng: " + lng");
Or if you want to keep the content of here and append the information at the end:
$("#here").append("lat: " + lat + " lng: " + lng");

Skycons break when calling Forecast.io API with time interval

I'm using Forecast.io API with Skycons for icons in a function that calls the API every n seconds.
On the second function call the icon disappears. Interestingly, when setting the icon with hardcoded icon type it works and I'm confused. What am I doing wrong?
My script:
var counter = 0;
var skycons = new Skycons({
"color": "#6c5848"
});
var data;
var apiKey = '6b5c02819a985881e46287c6507a9800';
var lati = 50;
var longi = 25;
var url = 'https://api.forecast.io/forecast/' + apiKey + '/' + lati + ',' + longi + '?callback=?&units=ca';
var callback = function (data) {
var icon = data.currently.icon;
var tempC = data.currently.temperature;
var tempCfeel = data.currently.apparentTemperature;
// Icon
skycons.set( 'icon', icon ); // this line doesn't work and breaks the function
//skycons.set('icon', Skycons.SNOW); // this line works
// Temperature
$('#temp').html(tempC.toFixed(1) + ' °C / feels like ' + tempCfeel.toFixed(1) + ' °C');
counter++;
$('#counter').html(counter + ' API calls');
};
var fetchForecast = function () {
$.getJSON(url, callback);
};
fetchForecast();
skycons.play();
setInterval(fetchForecast, 5000);
jsFiddle
Try this:
var apiKey = '6b5c02819a985881e46287c6507a9800';
var lati = 50;
var longi = 25;
var url = 'https://api.forecast.io/forecast/' + apiKey + '/' + lati + ',' + longi + '?callback=?&units=ca';
var fetchForecast = function () {
var counter = 0;
var skycons = new Skycons({
"color": "#6c5848"
});
$.getJSON(url, function (data) {
var icon = data.currently.icon;
var tempC = data.currently.temperature;
var tempCfeel = data.currently.apparentTemperature;
// Icon
skycons.set( 'icon', icon ); // this line doesn't work
//skycons.set('icon', Skycons.SNOW); // this line works
// Temperature
$('#temp').html(tempC.toFixed(1) + ' °C / feels like ' + tempCfeel.toFixed(1) + ' °C');
counter++;
$('#counter').html(counter + ' API calls');
skycons.play();
});
};
setInterval(function(){
fetchForecast();
}, 1000);
The counter is busted but check the console, its firing requests every second
When using the string from Forecast.io you have to enclose it in quotes. Where you are using icon which substitutes something like partly-cloudy-night, when you pass it into sky cons it has to be in quotes. Hope that makes sense.
i have same problem i was fix it with set string type of wheater.
var icon = String(data.currently.icon);

Getting hourly info from weather API

I am trying to access hourly info from a weather API.
The problem is its not quite working for me, and I am not 100% sure of how to gain access to the information.
This is the site I am working with, and the page on the hourly info.
http://www.wunderground.com/weather/api/d/docs?d=data/hourly&MR=1
I have a strong feeling it has to do with the way the access to variables...
This is my code:
<script>
jQuery(document).ready(function($) {
$.ajax({
url: "http://api.wunderground.com/api/6368023a57d122c7/geolookup/conditions/q/DominicanRepublic/Barahona.json",
dataType : "jsonp",
success : function(parsed_json) {
//get the hourly info -- cant get hourly to work...
var month = parsed_json['hourly_forecast']['FCTTIME']['mon_padded'];
var day = parsed_json['hourly_forecast']['FCTTIME']['mday_padded'];
var year = parsed_json['hourly_forecast']['FCTTIME']['year'];
var time = parsed_json['hourly_forecast']['FCTTIME']['civil'];
var updated = month + "/" + day + "/" + year + " " + time;
var weather = parsed_json['hourly_forecast']['condition'];
var temp = parsed_json['hourly_forecast']['temp']['metric'];
var humid = parsed_json['hourly_forecast']['humidity'];
var wind_direction = parsed_json['hourly_forecast']['wdir']['dir'];
var wind_speed = parsed_json['hourly_forecast']['wspd']['metric'];
var wind_string = wind_direction + " " + wind_speed + " Km/h";
document.getElementById("weather").innerHTML = weather;
document.getElementById("temp").innerHTML = temp;
document.getElementById("hum").innerHTML = humid;
document.getElementById("wind").innerHTML = wind_string;
}
});
});
</script>
If you open the JSON file from that URL you will see that it does not contain "hourly_forecast" or "FCTTIME".
EDIT:
Open up the JSON file that you are downloading and look at what fields it is sending back to you. JQuery already does the hard part and parses it into an object model. Also, the javascript debuggers in Chrome is great at showing you the JSON object model. You can just set a breakpoint at the beginning of the "success" function and use the "Local Variables" window to explore the JSON object.
Here's your code after I updated it to use the correct field names from the JSON file...
<script>
jQuery(document).ready(function ($) {
$.ajax({
url: "http://api.wunderground.com/api/6368023a57d122c7/geolookup/conditions/q/DominicanRepublic/Barahona.json",
dataType: "jsonp",
success: function (parsed_json) {
var current_observation = parsed_json.current_observation;
var lastUpdated = current_observation.observation_time;
var weather = current_observation.weather;
var temp = current_observation.temp_c;
var humid = current_observation.relative_humidity;
var wind_direction = current_observation.wind_dir;
var wind_speed = current_observation.wind_kph;
var wind_string = wind_direction + " " + wind_speed + " Km/h";
alert("Weather: " + weather + "\n"
+ "Temp: " + temp + "\n"
+ "Humidity: " + humid + "\n"
+ "Wind: " + wind_string + "\n"
+ lastUpdated
);
}
});
});
</script>

Categories

Resources