I'm doing the FreeCodeCamp course and i'm trying to build a weather app. I found a nice tutorial on how to get the latitude and longitude with geolocation. But now when I try and run the app it doesn't seem to be retrieving the ajax data for me to parse through. I was trying locally and moved it to hosting thinking that might have been it but now I just get a weird error on line one of my html and i don't see anything wrong. Thanks guy here is the code and it's live on weatherapp.boomersplayground.com
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Weather APP</title>
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src='script.js'></script>
</head>
<body>
<div id="forecast">
<h1>Weather at <span id="location"> </span></h1>
<!-- <div id="imgdiv">
<img id="img" src=""/> -->
</div>
<p>It is currently <span id="temp"> </span>F with <span id="desc"> </span></p>
<p>Wind: <span id="wind"></span></p>
</div>
</body>
</html>
script.js
$(document).ready(function(){
var Geo = {};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(success,error);
} else {
alert('Geolocation is not supported');
}
function error(){
alert("That's weird! We couldn't find you!");
}
function success(position){
Geo.lat = position.coords.latitude;
Geo.lng = position.coords.longitude;
}
var key = 'c7e3b3ac66e765aa';
var Weather = "http://api.wunderground.com/api/"+ key +"/geolookup/conditions/q/" + Geo.lat + "," + Geo.lng + ".json";
$.ajax({
url : Weather,
dataType : 'jsonp',
success : function(data) {
var location =data['location']['city'];
var temp = data['current_observation']['temp_f'];
var img = data['current_observation']['icon_url'];
var desc = data['current_observation']['weather'];
var wind = data['current_observation']['wind_string'];
}
})
//setting the spans to the correct parameters
$('#location').html(location);
$('#temp').html(temp);
$('#desc').html(desc);
$('#wind').html(wind);
// filling the image src attribute with the image url
// $('#img').attr('src', img);
});
You use the variables initialised at the AJAX response outside of the success callback. You should use them inside the callback, since they're created asynchronously:
$.ajax({
url : Weather,
dataType : 'jsonp',
success : function(data) {
var location =data['location']['city'];
var temp = data['current_observation']['temp_f'];
var img = data['current_observation']['icon_url'];
var desc = data['current_observation']['weather'];
var wind = data['current_observation']['wind_string'];
$('#location').html(location);
$('#temp').html(temp);
$('#desc').html(desc);
$('#wind').html(wind);
}
});
Because you are treating an Asynchronous call as a synchronous one. The Ajax call needs to be in the success callback of getCurrentPosition. You are building the Ajax url before the at and lng is returned.
Related
I have simple idea:
Get geolocation from one API (http://ip-api.com/json) and display it
Base on this geolocation find (using another api http://api.geonames.org/) closest mountains within a radius of 70km
and display it names
I have a problem with third point - I get a link (displaying as alert) which leads me to the list of objects(?) in JSON format but ... I want an alert or html display with full list of mountains name. How to achieve this ?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="api_try.css">
<script src="api_try.js"></script>
</head>
<body>
<button type="submit" class="form-btn" value="sbutton" onsubmit="">Try!</button>
<div id="geo_view">..</div>
<div id="mountains">..</div>
</body>
</html>
JS:
$(document).ready(function () {
$(".form-btn").on("click", function () {
var lat;
var lon;
$.get("http://ip-api.com/json", function (data) {
lat = data.lat;
lon = data.lon;
$('#geo_view').html(data.city);
alert(data.city);
});
var url1 = "http://api.geonames.org/findNearbyJSON?lat=";
var url2 = "&lng=";
var url3 = "&featureCode=MTS&radius=70&username=zebru";
var url = url1 + lat + url2 + lon + url3;
alert(url);
alert("2");
$.get(url,function(data){
alert("3");
var mt = $('#mountains").html(data.toponymName);
alert(mt);
});
});
});
I am trying to get weather information from openweather.com api with the help of geo-location (lattitude and longitude). I can not get it why it is not getting data. Here is my code:
function getWeather(lat, long){
console.log(lat +" "+ long); //23.8008983 90.3541741
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&units=imperial&APPID=7a26948f2294e4d5754c951a6aaf7cf8", function(json) {
console.log("Successfully data recieved");
var temp = Math.round(json.main.temp);
console.log(temp);
$("#weather").value(temp);
});
I try to print "Successfully data recieved" in console but it does not print. I assume the callback is not happening. it is confirmed that function calling (getWeather()) is okay as I am getting values of latitude and longitude (I kept those values in comment). I badly need your help. I manually typed the url with latitude and longitude in browser, it returned me the expected output that I should get from this JSON call. But not working in code.
I messed with this for a bit and the realized that sometimes it's the simplest solution... try requesting the secure (https) URL:
$.getJSON("https://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&units=imperial&APPID=7a26948f2294e4d5754c951a6aaf7cf8", function(json) {
console.log("Successfully data recieved");
var temp = Math.round(json.main.temp);
console.log(temp);
$("#weather").value(temp);
});
Your function is not properly closed, you missed ending } brace (I guess it is a typo). I've tried your code and it works for me like a charm. Also Be sure your `jquery library is included perfectly.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
(function() {
getWeather(23.8008983,90.3541741);
})();
function getWeather(lat, long){
var watherAPI = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&units=imperial&APPID=7a26948f2294e4d5754c951a6aaf7cf8";
$.getJSON( watherAPI, function (json) {
console.log("Successfully data recieved");
var temp = Math.round(json.main.temp);
console.log(temp);
})}
</script>
</body>
</html>
I'm trying to build a basic JQuery app which loads images from Flickr, adds them to an array of jQuery objects, sequentially adds them to the DOM, fades them in, and fades them out in a 3 second cycle. However, in my displayImage function, I cannot use .hide(), .fadeIn() or .fadeOut() because it throws an 'Uncaught TypeError: Cannot read property 'fadeIn' of undefined' error. Here is my code, both the JS and the HTML:
var main = function(){
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&format=json&jsoncallback=?";
//Creates the empty array of jQuery image objects
var images = [];
$.getJSON(url, function(flickrResponse){
flickrResponse.items.forEach(function (photo){
var $img = $("<img>").hide();
$img.attr("src", photo.media.m);
//Populates the images array with jQuery objects defined from the Flickr JSON request
images.push($img);
// $("main .photos").append($img);
// $img.fadeIn();
});
});
function displayImage(imgIndex) {
var $displayedImg = images[imgIndex];
$(".photos").fadeOut('slow');
$(".photos").empty();
$(".photos").append($displayedImg);
$displayedImg.fadeIn('slow');
//Function which recursively calls 'displayImage' every three seconds
setTimeout(function(){
imgIndex = imgIndex + 1;
displayImage(imgIndex);
}, 3000);
}
displayImage(0);
};
$(document).ready(main);
And
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Flickr App</title>
<link rel="stylesheet" type="text/css" href="stylesheets/styles.css">
</head>
<body>
<header>
</header>
<main>
<div class = "photos">
</div>
</main>
<footer>
</footer>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/app.js"></script>
</body>
Any ideas what might be undefined? Note that the var $img = $("<img>").hide(); line in the $.getJSONrequest doesn't throw the undefined error!
Thanks very much!
EDIT:
I've also tried to make a synchronous request to fetch the JSON, to make sure it's loaded before the displayImage function is called, and still it throws the same errors:
var main = function(){
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&format=json&jsoncallback=?";
var images = [];
//THIS IS WHAT HAS CHANGED
$.ajax({url: url,
dataType: 'json',
async: false,
success: function(flickrResponse){
flickrResponse.items.forEach(function (photo){
var $img = $("<img>").hide();
$img.attr("src", photo.media.m);
images.push($img);
});
}});
function displayImage(imgIndex) {
var $displayedImg = images[imgIndex];
$(".photos").fadeOut('slow');
$(".photos").empty();
$(".photos").append($displayedImg);
$displayedImg.fadeIn('slow');
setTimeout(function(){
imgIndex = imgIndex + 1;
displayImage(imgIndex);
}, 3000);
}
displayImage(0);
};
$(document).ready(main);
You need to wait for the JSON to return before you try to displayImage(0). The JSON request is asynchronous, so your call to displayImage is happening before any JSON has been returned.
I recommend stepping through with a Javascript debugger to better understand what’s going on. You would see then that images is empty, and therefore $displayedImg is undefined.
I search music with youtube data api. I use javascript and jquery and i have a problem.
Here is my code
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="<?php echo SITE_PUBLIC; ?>/bootstrap-3.2.0/dist/js/bootstrap.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<script>
function keyWordsearch(){
gapi.client.setApiKey('myapikey');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"eminem"},{"name":"shakira"}] }' );
$.each(data["data"], function( index, value ) {
makeRequest(value["name"]);
});
});
}
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 10
});
request.execute(function(response) {
$('#results').empty()
var srchItems = response.result.items;
$.each(srchItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
})
})
}
keyWordsearch();
</script>
This code not working. Chrome console say "Uncaught TypeError: Cannot read property 'setApiKey' of undefined". But this code is working:
keyWordsearch() to
$(document).click(function(){
keyWordsearch()
})
I do not understand this issue. Thanks in advance
EDIT
My code run on jsFiddle.But not run my html file. My html file is here:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="container">
<h1>Search Results</h1>
<ul id="results"></ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<script>
$(function(){
function keyWordsearch(){
gapi.client.setApiKey('AIzaSyCWzGO9Vo1eYOW4R4ooPdoFLmNk6zkc0Jw');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"eminem"}] }' );
$.each(data["data"], function( index, value ) {
makeRequest(value["name"]);
});
});
}
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 10
});
request.execute(function(response) {
$('#results').empty()
var srchItems = response.result.items;
$.each(srchItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
})
})
}
keyWordsearch();
})
</script>
</body>
</html>
Looks like, you haven't load the javascript library. That's why it can't find the reference.
You can add it like:
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
You can specify an initial function while calling the API like this: client.js?onload=init (see my example below). Besides no need of a doucument.ready() wrapper. I'm not sure why it works with your API key on my local machine but I guess it's some kind of magic that checks if the site is availible to the public - if true the referrer entries in your google account will get important - correct me on that if somebody knows whats exactly happening here.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<!--<link rel="stylesheet" type="text/css" media="screen" href="main.css" />-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script type="text/javascript">
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 3
});
request.execute(function(response) {
$('#results').empty();
var resultItems = response.result.items;
$.each(resultItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
});
});
}
function init() {
gapi.client.setApiKey('AIzaSyCWzGO9Vo1eYOW4R4ooPdoFLmNk6zkc0Jw');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"orsons"}] }' );
$.each(data["data"], function(index, value) {
makeRequest(value["name"]);
});
});
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=init"></script>
</head>
<body>
<h1>YouTube API 3.0 Test</h1>
<ul id="results"></ul>
</body>
</html>
In addition to all the answers which explain that you must specify and provide a callback function for the Google API client <script> loading line, I'd like to point out that it seems that the onload parameter will never run the specified function (at least in Chrome) when you load the Google API client.js from a local file (even though you are serving the HTML page via a webserver and not loading it from the file-system, which apparently seemed to be the only gotcha with the Google API JS client...).
e.g.:
<script src="/lib/js/client.js?onload=handleClientLoad"></script>
Although client.js will be loaded, this will never launch the handleClientLoad function when it's finished loading. I thought it would be useful to point this out, as this was a really frustrating thing to debug.
Hope this helps.
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
This MUST be called at the end, or at least after you define your method "handleClientLoad". This is its callback, and only after it was called - it means google api is ready. This is why you get gapi.client is null.
For the fun of it, you can use a timeout of a few seconds before using gapi.client and see it is not null anymore.
I'm reading this tutorial and I'm having some problems with the examples... I tried to run the examples in localhost but I'm encountering with some errors and really don't know what could it be. I should be getting the first post of WP, but instead of that I'm getting this error Uncaught ReferenceError: url is not defined. Any sugestions??? Thanks!
<!DOCTYPE HTML>
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
(url,target_div) {
var URL = url
jQuery.ajax({
url: URL,
dataType: 'json',
success: function(data) {
jQuery(target_div).html(data.post.content);
}
});
}
jQuery(document).ready(function() {
jQuery("#title").html("<h1>Hello World</h1>");
varurl = "http://localhost/phonegap/?json=get_post&dev=1&p=1";
vartarget_div = "#contents";
readSinglePost(url, target_div);
});
</script>
</header>
<body>
<div id="main">
<div id="title"></div>
</div>
</body>
</html>
It looks like "varurl =" should have a space to be "var url =" and same with "vartarget_div =" should be "var target_div =" instead.
Change a code as var url not varurl and var target_div not 'vartarget_div'. Give space to keyword var and the variable.
jQuery(document).ready(function() {
jQuery("#title").html("<h1>Hello World</h1>");
var url = "http://localhost/phonegap/?json=get_post&dev=1&p=1";
var target_div = "#contents";
readSinglePost(url, target_div);
});