Objective: To collect JSON data from forecast API and then read the JSON precipIntensity property over the number of days specified, this code starts at three. Since this take a number of steps to coherently follow please try to make sense of all the code.
My main issue is trying to name the JSON code pages that return then put them into another context to read the precipIntensity
property.
To outline: The back date gets the UNIX time, then requests an API for each forecast day. Then the APIs are put in an array. The array is put in a for() loop to request each JSON script... (now what to do? I would like to be able to read each or calculate something but I do not know how to ask for the formatted code. I can do the remaining bit).
A sample of JSON can be found at my other related post...
https://stackoverflow.com/questions/29949454/store-json-api-object-data-and-reuse-it (I found that the API server stores the data for me...solved)
EDITED since 5/1/15:
//Get the back dated times and current in UNIX,
//later make a lookup that gives datediff from current date and user's date and adjust index i condition to equal exact days.
var totalPrecipSinceDate;
var threeDayAPITimes = [];
for (var i = 0; i <= 2; i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //https://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime(); //1318023197289 number of ms since epoch
var unixEpoch = Math.round(epoch/1000)
threeDayAPITimes[i] = Math.round(unixEpoch - (86400 * i));
/*
var epoch = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
threeDayAPITimes[i] = Math.round(epoch - (86400 * i));
*/
}
//Plan to convert UNIX dates to display
//List of locations: LATITUDE,LONGITUDE
var locations = ["46.3494,-85.5083"]
var currentAPIKey ="privateAPIKey"; //gets an APIkey from user from forecaster input.
var listAPIs = "";
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time;
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
});
});
//Process result in foreach loop
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain")
{
$.each(result, function() {
eachPrecipSum += (this.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ;
});
}
alert(eachPrecipSum );
Your loop should be something like this:
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time;
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
});
}
Related
the Question:
How can I use the API to return a boolean value if the date is a bank holiday?
I have done some research and found a great, and free API which contains bank holidays, however I am having trouble using it: http://holidayapi.com/
if i was to use this code:
var year = 2016;
var month = 3;
var day = 25;
var isAHoliday = false;
$.getJSON(
"http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day, function (data) {
console.log(data); //DOES NOT DISPLAY IN CONSOLE
if (data.holidays.length > 0) {
// BANK HOLIDAY
isAHoliday = true;
}
else {
//IS NOT BANK HOLIDAY
//AND NOTHING NEEDS TO BE DONE
}
});
i want to be able to return a true or false value depending on if this returns any data or not, however im doing something wrong as the getJSON request is not being called, please could someone correct me where i have gone wrong?
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=25 returns {"status":200,"holidays":[{"name":"Good Friday","country":"GB","date":"2016-03-25"}]}
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=26 returns {"status":200,"holidays":[]}
it appears this is causing an issue: "http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day; if i pass one of the 2 URL's in above i get the correct result, I am having a play now with this
https://jsfiddle.net/dcxk6ens/
If you simply want to return a true value if the selected date is a holiday, or false if it is not, you could use a function like this:
(Please note that jsfiddle will not execute any AJAX calls to URLs using the "http://" protocol, since it is not secure.)
function isDateAHoliday(y, m, d) {
var jsonURL = "http://holidayapi.com/v1/holidays?country=GB&year=" + y + "&month=" + m + "&day=" + d;
var isAHoliday = false;
$.getJSON(jsonURL, function (data) {
// If the date is a holiday
if (data.holidays.length > 0) {
// Do some things
isAHoliday = true;
}
// Check values
console.log("JSON DATA: ", data);
console.log("Holiday?: " + isAHoliday);
return isAHoliday;
});
}
isDateAHoliday("2016", "3", "25");
If you wanted to return the name and country of the holiday as well, you could substitute isAHoliday = data.holidays[0]; inside of the if statement.
The holidays object must be called as a child of the returned data object:
Since the holidays object is an array you'll also need to use an index to access an item. Assuming there is at least one item returned, you would get the date like so:
var myDate = data.holidays[0].date;
However you should always check that there's at least one object in the array before getting the first one:
if(data.holidays.length > 0){...}
Incidentally, if all you want to do is check if there's a holiday on any particular day then this if statement is all you'll need, since an array length of more than zero means there's at least one holiday.
Edit
A full answer to your question, you could put this inside the .done() method:
var isAHoliday = false;
if(data.holidays.length > 0){
// There's at least one holiday today!
isAHoliday = true;
}
You don't have to declare a local variable, you'll probably use one that's declared elsewhere but that's up to you.
This is my API call:
https://itunes.apple.com/search?term=cut+the+cord&limit=1
I only want to get the value of the '"releaseDate":"2015-06-29' part.
Is there any way that I could only get that part in a textbox. I have this textbox in another page. Any ideas or suggestions?
Due to the cross-domaine policy, you must use JSONP to get json data and then format response value:
$.ajax({
url: "http://itunes.apple.com/search?term=cut+the+cord&limit=1",
dataType: "jsonp",
success: function( response ) {
console.log( response );
var d = new Date(response.results[0].releaseDate);
var y = d.getFullYear();
var m = pad( d.getMonth()+1, 2);
var d = pad( d.getDate(), 2);
$("#release").attr('value', y + "-" + m + "-" + d)
}
});
http://jsfiddle.net/yts728L5/2/
I guess you're parsing your result as JSON:
var result = JSON.parse(apiCallResult)
Then, assuming you only have one result as in the example request above, you should be able to get that value by simply accessing the object:
var results = result.results;
var releaseDate = results[0].releaseDate;
This will work if you have multiple results also, but it will only take the first result's releaseDate.
To add the text to a text box, you can use jQuery to get the text box and then set its value:
var textBox = $("#myTextBoxId");
textBox.val(releaseDate);
I have a twiter web app that I am building. It is following a select group of twitter IDs and only picking out tweets that they post based on again a select group of keywords. Everything is working fine except I want to convert the twitter ID i have in an array into the corresponding twitter user name (one by one) so for example the array of IDs is var trackedHandles; and i want to convert trackedHandles[i] to a user name and print it the console next to the actual tweet. SO it would look like this in the console: #me: here is my tweet Here is my code selection that relates to this:
t.stream(
"statuses/filter",
{track: trackedHandles + trackedWords, lang: "en" },
function(stream) {
stream.on('data', function(tweet) {
for (var i= 0; i < trackedData.length; i++) {
if(tweet.text.indexOf(trackedData[i]) > - 1) {
// incriments added value to the word
redisClient.incr(trackedData[i]);
console.log(trackedHandles[i] + ":" + " " + tweet.text + " " );
//console.log(trackedData[i]);
}
}
});
}
);
Right now i'm just printing the twitter ID, but again I want to print the username. I appreciate your help.
I figured it out on my own! In case someone in the future needs to know how though:
//Get Screen_Name from tweet object.
function getPosition(str,m, i) { //special helper function to find the nth position of a string.
return str.split(m, i).join(m).length;
}
var snStartingPos = getPosition(tweetObject, "screen_name", 2); //starting position of "screen_name" in tweet object.
var snEndingPos = snStartingPos + 14; //ending position of "screen_name" in tweet object (where we actually want to start).
var unStartingPos = getPosition(tweetObject, "location", 1); //starting position of the word after where we want to end.
var unPrePos = unStartingPos - 3; //subtract that by 3 characters to exclude the unnecessary characters
var snLength = unPrePos - snEndingPos; //this is now the length of the screen_name we want
var screen_name = "#" + tweetObject.substr(snEndingPos, snLength); //get the sub-str that we want (the "screen_name") from tweet object.
//End Get Screen_Name from tweet Object
tweetObject is just tweet converted as a string. the function getPosition, I got off another stackOverflow question page: How to get the nth occurrence in a string?
I am new to javascript and I used the tutorial found here: http://www.prettyklicks.com/blog/making-a-facebook-feed-using-the-graph-api-json-and-jquery/291/ but I am having trouble formatting the date given by facebook. My website is http://moussesalon.com/homePage.htm and my code is as follows:
(function($){
$.fn.fbstatus = function(options) {
set = jQuery.extend({
username: 'Removed for privacy',
token: 'Removed for privacy',
loading_text: null
}, options);
function fbstatus_link(text){
return text.replace(/(href="|<a.*?>)?[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function($0, $1) {
return $1 ? $0 : $0.link($0);
});
}
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "Removed for privacy";
$(this).each(function(i, widget){
var loading = $('<p class="loading">'+set.loading_text+'</p>');
var theObject = $(this);
if (set.loading_text) $(widget).append(loading);
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url,function(json){
var html = "<ul>";
//loop through and within data array's retrieve the message variable.
$.each(json.data,function(i,fb){
if (fb.message) {
html += "<li>" + fbstatus_link(fb.message) + "<br>" + fb.created_time + "</li>" + "<br>";
}
});
html += "</ul>";
//A little animation once fetched
theObject.animate({opacity:0}, 500, function(){
theObject.html(html);
});
theObject.animate({opacity:1}, 500);
});
});
};
})(jQuery);
Any help would be greatly appreciated.
According to the main Graph API Documentation under 'Dates' you can ask the API to return results in any date format you want - why not just get Facebook to return the dates in your preferred format?
Excerpt from docs:
All date fields are returned as ISO-8601 formatted strings. You can optionally override the date format by specifying a "date_format"
query parameter. The accepted format strings are identical to those
accepted by the php date function. For example,
https://graph.facebook.com/platform/feed?date_format=U returns the
Platform page's feed, with unixtime-formatted dates.
You could use the javascript function
string.substring(from, to);
This will allow you to specify the start character (0 for the start of the string) to the last character you want (length - 5)
fb.created_time.substring(0,(fb.created_time.length-5));
Here is a simple way to do this...
//graph API call
https://graph.facebook.com/YOURNAME?fields=YOURFIELDSHERE&date_format=F j, Y, g:i a&access_token=ACCESSTOKENHERE"
The results will be the date of the post such as; April 13, 2017, 4:40 pm
I'm using ZrssFeed to display an rss feed. I would like to limit it to only posts from the last 8 hours.
I tried adding the following block of code after ZRSS returns the feed:
// Add feeds
for (var i=0; i<feeds.entries.length; i++) {
// Get individual feed
var entry = feeds.entries[i];
feedcount = i;
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
var msPerDay = 8*60*60*1000; // 8 hours
var msPubDateTime = new Date(pubdate); // item date in ms
if (msNow.getTime() - entryDate.getTime() < msPerDay) //compare
{
// rest of plugin
This both doesn't work and seems to break the plugin altogether.
You may want to look at the jsDate script. It's great at handling all date-related JS issues.
http://www.datejs.com/