Recently I was helping a customer of ours with an interesting problem: they have a Socrata dataset full of events, in this case public meetings, and they wanted a flexible way of displaying them within a monthly calendar embedded within their website.
A colleague of mine recommended the MIT-licensed FullCalendar project, and it worked out wonderfully. This example will demonstrate how you can combine the power and flexibility of Socrata’s APIs with open source software, and quickly build out a monthly calendar visualization for your dataset that looks like the one below:
There are a couple of prerequisites for this example:
I recommend following the FullCalendar “Basic Usage” doc to start off. All three libraries must be loaded, in that order, before your code can run.
Starting from the API docs for our source dataset, we’re going to craft a SoQL query that does the following:
$whereclause to pull the last 31 days of events, so we always can see all of the current month’s events
$orderto sort them by date
The full query will look like the following, but we’ll need to fill in the correct bounding date later on:
In this step, we’ll use jQuery’s
$.ajax(...) utility function to fetch our records from the API.
We’ll pass in the
url of our API endpoint, a
GET, and a
json. For our
data, we can use the broken out parameter pairs of our SoQL query. We also use Moment.js’s
format(...) functions to generate a date string for 31 days ago.
Next we’ll take each of the events in the response from our API call, and create FullCalendar Event Objects for each of them. At a minimum, we’ll need start and end dates for them, as well as a title. If we have a URL, that will make the event clickable.
This is the simplest part. We pass in our new collection of events to the FullCalendar initialization function, targeting the
#calendar div. This is also where you could use
eventClick(...) to change what happens when you click on an event:
That’s it! We’ll pull all the pieces together in one last to show all of the code at once, but that should be enough to help you build a basic calendar visualization!
Here’s all the code as one block, including all of the HTML to make it a standalone page: