To work with our βTripsβ API (from Assignment 1) on the client-side to produce a rich user interface for accessing data.Β We will practice using well-known CSS/JS code and libraries including Lodash, Leaflet, jQuery & Bootstrap
Sample Solution:
You can see a video of the solution running at the following location: https://patβcrawfordβsdds.netlify.app/shared/summerβ2022/web422/A2/A2.mp4 Specification:
For this assignment, we will create a single table that shows a subset of the trip data (ie: columns: Bike Id, Start Station, End Station and Duration (Minutes)). When the user clicks on a specific trip (row) in the table, they will be shown a modal window that shows an interactive map indicating both the start location and end location.Β We will be making use of the Bootstrap framework to help design our UI, jQuery to work with the DOM, Lodash to specify our template(s) and Leaflet to render the map.
Β
Β
The Solution Directory
The first step is to create a new directory for your solution, open it in Visual Studio Code and add following folders / files:
Β
We will not be including any of the JavaScript / CSS libraries locally.Β Instead, we will be leveraging their CDN locations (See the Week 2 notes for the <script> and <link> elements necessary to include jQuery, Bootstrap, Lodash and Leaflet).Β Note: Remember that the order is important, ie: jQuery should be included before the Bootstrap JavaScript and your main.js file should be included last.
Β
Creating the Static HTML:
Next, we must create some Static HTML as a framework for the dynamic content.
Open your index.html file and add the minimum code required for an HTML5 page (HINT: type !
and then immediately type the tab key to get an HTML 5 skeleton).Β Once this is complete, include links for:
Β
- The Bootstrap 3.4.1 Minified CSS File (Using the CDN)
Β
Β
<link rel=βstylesheetβ href=βhttps://unpkg.com/[email protected]/dist/leaflet.cssβ integrity=βsha512xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChS R7A==β crossorigin=ββ/>
Β
- Your css file (NOTE: This file will consist of four selectors (for now) to ensure that your βtrips-tableβ (or whatever you wish to call it) causes the cursor to change to a βpointerβ whenever a user moves their mouse over a row. Also, we must ensure that your map is a specific height and you have set classes for βSubscriberβ and βCustomerβ background colours (to be used in your table rows, labels, etc) β please feel free to use whatever colours fit your design.
Β
#trips-table tr:hover { cursor:pointer; }
#leaflet { height: 400px; }
.Subscriber { background-color: β¦; color: β¦; }
.Customer { background-color: β¦; color: β¦; }
Β
- The jQuery 3.4.1 Slim, Minified JS File (Using the CDN)
Β
- The Bootstrap 3.4.1 Minified JS File (Using the CDN)
Β
- The Lodash 4.17.5 Minified JS File (Using the CDN)
Β
Β
<script src=βhttps://unpkg.com/[email protected]/dist/leaflet.jsβ integrity=βsha512-
XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynx wA==β crossorigin=ββ></script>
Β
- Your js file
With all of our libraries and files in place, we can concentrate on placing the static HTML content on the page.Β This includes the following:
Β
Navbar
Assignment 2 will use an extremely simplified Bootstrap 3 navbar.Β Begin by copying the full Default Navbar example HTML code from the official documentation: https://getbootstrap.com/docs/3.4/components/#navbarβdefault and pasting it as the first element within the <body> of your file.
- Next, proceed to remove all child elements from the βbs-example-navbar-collapse-1β <div> element
- In the (now empty) βbs-example-navbar-collapse-1β <div> element, put back a single navigation item and label it βTripsβ, ie:
<ul class=βnav navbar-navβ>
Β Β Β <li class=βactiveβ><a href=β#β>Trips<span class=βsr-onlyβ>(current)</span></a></li>
</ul>
- Finally, change the βnavbar-brandβ to be your name
When completed, your navbar should look like the following
Β
Β
Bootstrap Grid System (1 Column)
Since we are leveraging Bootstrap for this assignment, we should make use of their excellent responsive grid system.Β Beneath the navbar, add the following HTML
- Include a <div> element with the class βcontainerβ (so that our content is centered)
- Within the βcontainerβ, create a <div> with class βrowβ
- Within the βrowβ, create a <div> with class βcol-md-12β (we will only have one column to show our data)
Β
Citibike Trips Header
Before we create our main table skeleton (next), we should create an appropriate header informing the user about the content of the table, as well as indicating your chosen colours to indicate βSubscribersβ vs βCustomersβ in the table.
Start by adding a header (ie: <h2>) with the text βCitibike Tripsβ.Β Beneath this header, you can add two Bootstrap labels with the class βSubscriberβ and βCustomerβ, ie:
<span class=βlabel Subscriberβ style=βfont-size:smallβ>Subscribers</span>
<span class=βlabel Customerβ style=βfont-size:smallβ>Customers</span>
Β
Once these items are in place, your app should look similar the following (ie: you may have chosen different colours for β.Subscriberβ and β.Customerβ):
Β
Β
Main Table Skeleton
The main interface that users will interact with to view data in our application is a HTML table consisting of 4 columns: Bike Id, Start Station, End Station and Duration (Minutes).Β Create this table within your βcol-md-12β container according to the following specification:
- The <table> element should have the class βtableβ and a unique id, ie: βtrips-tableβ, since we will be accessing it programmatically from JavaScript
Β
- The <thead> element should contain one row
Β
- The single header row should have 4 table heading elements with the text:
- Bike Id o Start Station o End Station
- Duration (Minutes)
Β
- The <tbody> element should be empty
Β
Once your table is in place, your app should appear similar to:
Β
Β
Β
Paging Control
Since our βtripsβ collection contains approximately 10000 documents, we will leverage our Web APIβs pagination feature when pulling trips from the database (ie:
/api/trips?page=1&perPage=10, etc).Β To give the user some control over which page they wish to see, we must include a primitive pagination control (for this assignment, we will not let them βjumpβ to a specific page, but instead we will let them go back and
forth between the pages in sequence).Β To accomplish this, we must place the pagination buttons on our page before wiring up their functionality using jQuery:
Β
- Begin by copying the full Pagination HTML code from the official documentation:
https://getbootstrap.com/docs/3.4/components/#pagination and pasting it directly underneath your newly created βtrips-tableβ.
- Next, delete the list items that contain the numbers 2, 3, 4 and 5 (leaving just 1)
Β
- Give each of the 3 remaining <a> elements (nested within the <li> elements) unique id values such as βprevious-pageβ, βcurrent-pageβ and βnext-pageβ (we will use these id values to add functionality to the links and display the current page)
Β
- Finally, remove the text 1 from the middle link (it will be added dynamically later).
Β
Once your pagination control is in place, your app skeleton should look like the following:
Β
βGenericβ Modal Window Container
We will be showing our map for a specific trip in a Bootstrap modal window.Β Since every time we show the modal window, it will have different content (Specific to the Trip that was clicked), we must add an empty, generic modal window to the bottom of our page.
To get the correct HTML to use for your Bootstrap modal window, use the following example from the documentation as a starting point.
Once you have copied and pasted the βmodalβ HTML into the bottom of your <body> element (ie, below the other content) , make the following changes:
- Give your <div> with the class βmodal fadeβ a unique id, ie: βtrip-modalβ. We will need to reference this element every time we wish to show / work with the modal window.
- Remove the βModal Titleβ text from the <h4> element with class βmodal-titleβ. We will be using jQuery to populate this later.
- Remove the <p> element with the text βOne fine bodyβ¦β from the <div> element with class βmodal-bodyβ and replace it with the following elements:
Β
<div id=βleafletβ></div>
<br />
<div id=βmap-detailsβ></div>
Β
These are placeholders for both the map, and map details respectfully.
- Finally, remove the button element with the text βSave Changesβ. This modal is used to display information only, so a βsaveβ button is not required
Β
JavaScript File (main.js):
Now that we have all of our static HTML / CSS in place, we can start dynamically adding content and responding both user and bootstrap events using JavaScript.Β In your main.js file add the following variables & functions at the top of the file:
Β
- tripData (array)
Β
This should be an empty array (we will populate it later with a βfetchβ call to our back end API)
Β
- currentTrip (object)
Β
This should be an empty object (ie: {} β we will populate it later once the user clicks on a specific trip
within our UI)
Β
- page (number)
Β
This will keep track of the current page that the user is viewing.Β Set it to 1 as the default value
Β
- perPage (number)
Β
This will be a constant value that we will use to reference how many trip items we wish to view on each page of our application.Β For this assignment, we will set it to 10.
Β
- map (leaflet βmapβ object)
Β
This will be a reference to our current βmapβ, once it has been initialized.Β For now, simply assign it a value of null
Β
- tableRows (Lodash template)
Β
This will be a constant value that consists solely of a Lodash template (defined using the _.template() function). The idea for this template is that it will provide the functionality to return all the rows for our main βtrips-tableβ, given an array of βtripβ data.Β For example, if the tableRows template was invoked with the first two results back from our Web API (left), it should output the following HTML (right):
Β
Β
Β
Β
<tr data-id=β572bb8222b288919b68abf5aβ
class=βSubscriberβ>
<td>17827</td>
<td>E 31 St & 3 Ave</td>
<td>Broadway & W 32 St</td>
<td>6.32</td>
</tr>
Β
<tr data-id=β572bb8222b288919b68abf5bβ
class=βSubscriberβ>
<td>22794</td>
<td>Howard St & Centre St</td>
<td>South End Ave & Liberty St</td>
<td>14.82</td>
</tr>
You will notice a few things about the formatting of each row in the returned result, specifically:
- The template loops through each object in the array to produce a <tr> element (HINT: .forEach() can be used here)
Β
- Each <tr> has a βdata-idβ attribute that matches the _id property as well as a βclassβ attribute that matches the usertype property of the object in the current iteration
Β
- The first <td> contains the bikeid property of the object in the current iteration
Β
- The second <td> contains the βstart station nameβ property of the object in the current iteration (NOTE: To access properties that contain spaces, you may use the syntax obj[βproperty nameβ] instead of property name)
Β
- The second <td> contains the βend station nameβ property of the object in the current iteration
Β
- The final <td> content contains the tripduration for the object in the current iteration in minutes, shown to two decimal places. This can be obtained by using the expression (tripduration / 60).toFixed(2)
Β
HINT: Place all the HTML / Code for your template within a string defined using ` ` (this will allow you to write our template string across multiple lines.
Β
- loadTripData() (function)
Β
Now that our templates and global variables are in place, we can write a utility function to actually populate the tripData array with data from our API created in Assignment 1 (now sitting on Heroku).
To achieve this, the loadTripData function must:
Β
- make a βfetchβ request to our Web API hosted on Heroku using the route:
/api/trips?page=page&perPage=perPage
Here, the values of page and perPage must be the values of the variables: page and perPage that you declared at the top of the file at the beginning of this assignment β perPage is a constant value and page is the current working page.
- When the fetch request has returned and the json data has been parsed:
- set the global tripData array to be the data returned from the request
Β
- invoke the tableRows template with the data returned from the request (ie: tableRows({trips: data})) and store the return value in a variable.
Β
- Select the <tbody> element of your main βtrips-tableβ and set its html (.html()) to be the returned value from when you invoked the tableRows template function, above.
Β
- Select the current-page element (from your pagination control) and set its html (.html()) to be the value of the current page
Β
Now that our loadTripData() utility function as well as our templates and global variables are in place, letβs add the following code to be executed when the document is ready (ie: within the $(function(){ β¦ }); callback ):
Β
The first thing that needs to be done, is to invoke the loadTripData() function to populate our table with data and set the current working page
Β
Next, we must wire up the following 5 events using jQuery:
Β
1) Click event for all tr elements within the tbody of the trips-table
Once this event is triggered, we must perform the following actions:
- Locate the trip object in the tripData array whose β_idβ property matches the βdata-idβ property of the row that was clicked, and store it as the currentTrip object (declared at the top of the file). This will allow us to work with the clicked trip object (currentTrip) in our other events (below).
Β
HINT: the βdata-idβ value can be obtained by using the jQuery code: $(this).attr(βdata-idβ);)
Β
- Set the content of the βmodal titleβ (ie: <h4 class=βmodal-titleβ></h4>) for the βtrip-modalβ to the text Trip Details (Bike: bikeid), where bikeid is the value of βbikeidβ for the currenttrip
Β
- Set the contents of the βmap detailsβ (ie: <div id=βmap-detailsβ></div>) to show the following pieces of data for the currentTrip:
Β
- βstart station nameβ o βend station nameβ
- βtripdurationβ (represented in minutes, shown to two decimal places)
For example:
Β
Β
- Open the βTripβ Modal window (ie: <div id= βtrip-modalβ β¦ > β¦ </div>β).
Β
2) Click event for the βprevious pageβ pagination button
When this event is triggered we simply need to check if the current value of page (declared at the top of the file) is greater than 1.Β If it is, then we decrease the value of page by 1 and invoke the loadTripData function to refresh the rows in the table with the new page value.
Β
3) Click event for the βnext pageβ pagination button
This event behaves almost exactly like the click event for the βprevious pageβ, except that instead of decreasing the value of page, we increase the value of page by 1 and invoke the loadTripData function to refresh the rows in the table with the new page value.
Β
4) shown.bs.modal event for the βTripβ modal window
This event is actually a Bootstrap event that triggers once a modal window is fully shown (after the CSS transitions have completed).Β To wire up this event, we can use the following jQuery code:
Β
$(β#trip-modalβ).on(βshown.bs.modalβ, function () {});
Β
Once the modal has been βshownβ, we must include the following code in order to correctly render a map using our Leaflet library:
Β
map = new L.Map(βleafletβ, {
layers: [
new L.TileLayer(βhttps://{s}.tile.openstreetmap.org/{z}/{x}/{y}.pngβ)
]
});
Β
let start = L.marker([start station location β coordinate 1, start station location β coordinate 0]) .bindTooltip(start station name,
{
permanent: true,
direction: βrightβ
}).addTo(map);
Β
let end = L.marker([end station location β coordinate 1, end station location β coordinate 0]) .bindTooltip(end station name,
{
permanent: true,
direction: βrightβ
}).addTo(map);
Β
var group = new L.featureGroup([start, end]);
Β
map.fitBounds(group.getBounds(), { padding: [60, 60] });
Β
You will notice that there are placeholders for start station location β coordinate 1 and 0 as well as start station name Β / end station name.Β These should be replaced with the values from the associated properties within the currentTrip object..
Additionally, you will notice that the new L.Map(βleafletβ, { β¦ }); code creates an object that we assign to our map variable (originally defined as null at the top of our file).Β This is so that we are able to correctly remove the map once the modal window has closed.
Β
5) hidden.bs.modal event for the βTripβ modal window
This event is wired up in the exact same way as the βshown.bs.modalβ event, defined above.Β However, this time instead of creating a new map, we must remove the existing map using the code:
Β
map.remove();
Β
Β
6) Pushing code to a private GitHub repository You need to push to a remote repository:
- Create a new private repository in GitHub and name it web322-assignment4-app
- Share this repository by going to your web322-assignment4-app repository in GitHub β
> Settings -> Collaborators -> Add People -> Enter βat-senecaβ and Invite Collaborator
Β
Β
Assignment Submission:
- Add the following declaration at the top of your main.js file
Β
/****************************************************************************** ***
- WEB422 β Assignment 2
- I declare that this assignment is my own work in accordance with Seneca Academic Policy. *Β No part of this assignment has been copied manually or electronically from any other source * (including web sites) or distributed to other students. *
- Name: ______________________ Student ID: __________________ Date:
____________________
*
******************************************************************************
**/
- Compress (.zip) the files in your Visual Studio working directory (this is the folder that you opened in Visual Studio to create your client-side code).
Important Note:
- NO LATE SUBMISSIONS for assignments. Late assignment submissions will not be accepted and will receive a grade of zero (0).
- After the end (11:59PM) of the due date, the assignment submission link on My. Seneca will no longer be available.
- Submitted assignments must run locally, i.e.: start up errors causing the assignment/app to fail on Startup will result in a grade of zero (0) for the assignment.







