Astrocast

Bitesize Astronomy API

Examples

Here you'll find examples using the Astrocast API along with the code. Feel free to send us your examples and we'll be happy to share them. We would also like to list where the API is being used so get in touch via GitHub or tweet us at @carolune or @govender. Thanks and enjoy!

Random Astronomy bite:

This javacsript code fetches the bites, selects one at random, generates a google search link to find out more about the bite and prints in into a dov, clickable and all.


var randomBite;
var count;
var bites = new Object();

function showRandomBite() {
	// load the data
	var myUrl = "http://astrocast.herokuapp.com/bites";
	// workaround the cross-domain getJSON issue
	var astrocastApi = "proxy.php?url=" + encodeURIComponent(myUrl);
 	var myOutput = $.getJSON(astrocastApi, function(myBites) {
 		bites = myBites;
		count = Object.keys(myBites).length;
		printRandomBite(count, bites);
	})
	.fail(function() {
		console.log('fail!');
	});
}

function printRandomBite(count, bites) {
	// empty the div
	$('#randombite').empty();
	// pick a random index
	var index = Math.floor(Math.random() * (count));
	randomBite = bites[index].name;
	// generate the google search link
	var randomBiteToURL = encodeURI('https://www.google.com/search?q=' + randomBite);
	var content = '<a href="' + randomBiteToURL + '" target="_blank">' + randomBite+ '</a>';
	// put the bite and the link into the div.
	$('#randombite').append(content);
}

$(document).ready(function() {

	showRandomBite();

	$('#randomBiteButton').click(function () {
		printRandomBite(count, bites);
	}); 
});


					
@carolune 2017