CTA Bus Map
This intermediate guide walks you through showing Chicago Transit Authority (CTA) bus locations on a Google Map. You'll learn how to create a StacheElement that integrates with 3rd party widgets.
In this guide, you will learn how to:
- Use
fetch
to request data. - Create a custom element that wraps a google map.
- Add markers to the google map.
The final widget looks like:
To use the widget:
- Click a Bus Route.
- Explore the markers added to the Google Map showing the bus locations for that route.
- Click the route name overlay to refresh the bus locations.
The following sections are broken down into the following parts:
- The problem — A description of what the section is trying to accomplish.
- What you need to know — Information about CanJS that is useful for solving the problem.
- How to verify it works - How to make sure the solution works if it’s not obvious.
- The solution — The solution to the problem.
Setup
START THIS TUTORIAL BY CLICKING THE “EDIT ON CODEPEN” BUTTON IN THE TOP RIGHT CORNER OF THE FOLLOWING EMBED::
This CodePen has initial prototype HTML and CSS which is useful for getting the application to look right.
What you need to know
There's nothing to do in this step. The CodePen is already setup with:
- A basic CanJS setup.
- A promise that resolves when the Google Maps has loaded.
- Some variables useful to make requests to get bus routes and locations.
Please read on to understand the setup.
A Basic CanJS Setup
A basic CanJS setup uses properties within a StacheElement to manage the behavior of a View as follows:
The component can be rendered by adding the custom tag to the HTML:
CanJS StacheElement uses can-stache to render data in a template and keep it live. Templates can be authored in the component's
view
property like:A can-stache template uses {{key}} "magic tags" to insert data into the HTML output like:
Mount the component in the HTML:
Loading Google Maps API
The following loads Google Maps API:
It creates a global googleAPI
promise that resolves when Google Maps is ready. You can use it like:
Loading CTA Bus Data
This app needs to make requests to the http://www.ctabustracker.com/ API. The
ctabustracker
API is hosted at:
The API needs a token as part of the request:
However, the API does not support cross origin requests. Therefore, we will request data using a proxy hosted at:
With that proxy, the requests for this app will look like:
Change the app title
The problem
In this section, we will:
- Explore the relationship between component Props and View.
- Make it so the title of the page changes from
<h1>YOUR TITLE HERE</h1>
to<h1>CHICAGO CTA BUS TRACKER</h1>
. - Let us adjust the title simply by changing the property like:
What you need to know
A can-stache template uses {{key}} magic tags to insert data into the HTML output like:
These values come from the component properties.
The StacheElement props allows you to define a property with a default value like:
How to verify it works
Run the following in the Console
tab:
You should see the title update.
The solution
Update the JavaScript tab to:
List bus routes
The problem
In this section, we will:
- Load and list bus routes.
- Show
<p>Loading routes…</p>
while loading routes.
We will do this by:
- Store the promise of bus routes in a
routesPromise
property. routesPromise
will resolve to anArray
of the routes.- Loop through each route and add an
<li>
to the page. - Show the loading message while
routesPromise
is pending.
What you need to know
The default property definition can return the initial value of a property like:
The fetch API is an easy way to make requests to a URL and get back JSON. Use it like:
You'll want to use the
proxyUrl
andgetRoutesEnpoint
variables to make a request for CTA bus routes. The routes service returns data like:Make sure that
routesPromise
will be a Promise that resolves to an array of routes.Promises can transform data by returning new values. For example if
outerPromise
resolves to{innerData: {name: "inner"}}
,resultPromise
will resolve to{name: "inner"}
:Use {{# if(value) }} to do
if/else
branching in can-stache.Use {{# for(of) }} to do looping in can-stache.
Promises are observable in can-stache. Given a promise
somePromise
, you can:- Check if the promise is loading like:
{{# if(somePromise.isPending) }}
. - Loop through the resolved value of the promise like:
{{# for(item of somePromise.value) }}
.
- Check if the promise is loading like:
The solution
Update the JavaScript tab to:
Pick a route and log bus locations
The problem
In this section, we will:
- Highlight the selected bus route after a user clicks it.
- Log the bus (vehicle) locations for the selected route.
We will do this by:
- Listening to when a user clicks one of the bus routes.
- Adding
active
to the class name of that route's<li>
like:<li class="active">
. - Making the request for the vehicle locations of the selected route.
What you need to know
Use on:event to listen to an event on an element and call a method in can-stache. For example, the following calls
doSomething()
when the<div>
is clicked:Use the
"any"
type to define a property of indeterminate type:You'll want to store the selected bus route as
route
.Use
fetch(proxyUrl + getVehiclesEndpoint + "&rt=" + route.rt)
to get the vehicles for a particular route. If there is route data, it comes back like:If there is an error or no buses, the response looks like:
How to verify it works
In the Console
tab, when you click a bus route (like Cottage Grove
), you should see
an array of bus routes.
The solution
Update the JavaScript tab to:
Show when buses are loading and the number of buses
The problem
In this section, we will:
- Show
<p>Loading vehicles…</p>
while bus data is being loaded. - Show
<div class="error-message">No vehicles available for this route</div>
in the overlay if the request for bus data failed. - Show the number of buses inside the
<div class="gmap">
like:Bus count: 20
.
We will do this by:
- Defining and setting a
vehiclesPromise
property.
What you need to know
- In stache, you can check if a promise was rejected like:
- The Promise.reject method returns a rejected promise with the provided
reason
: - Promises can transform data by returning new promises. For example if
outerPromise
resolves to{innerData: {name: "inner"}}
,resultPromise
will be a rejected promise with thereason
as{name: "inner"}
:
The solution
Update the JavaScript tab to:
Initialize Google Maps to show Chicago
The problem
In this section, we will:
- Create a custom
<google-map-view/>
element that adds a google map. - The google map should be added to a
<div class="gmap"/>
element. - The google map should be centered on Chicago (latitude:
41.881
, longitude-87.623
).
We will do this by:
- Creating a custom StacheElement that adds the
<div class="gmap"/>
to its HTML. - Listens to when the element is in the page and creates a new google map.
What you need to know
Use StacheElement to create custom elements. Start by extending
StacheElement
and then define the custom element with the constructor:Next, provide the HTML can-stache template with the content you want to insert within the element.
Any values you want the custom element to hold must be defined on props. The following specifies a
map
property that can be any value:An element reference can be passed to the component like the following:
StacheElement's connected hook can be used to know when the component's element is inserted into the document as follows:
To create a google map, use new google.map.Map( /* ... */ ) once the
googleAPI
has completed loading:
The solution
Update the JavaScript tab to:
Set markers for vehicle locations
The problem
In this section, we will:
- Show markers at bus locations when the user clicks a route.
We will do this by:
- Passing the
vehicles
fromvehiclePromise
to<google-map-view>
. - Listening when
vehicles
changes and creating google mapMarker
s.
What you need to know
childProp:from can set a component's property from another value:
The component can listen to events fired by its properties like:
Use new google.maps.Marker to add a marker to a map like:
The solution
Update the JavaScript tab to:
Clean up markers when locations change
The problem
In this section we will:
- Remove markers from previous routes.
- Update marker locations when the user clicks the overlay.
We will do this by:
- Storing the active list of markers
- Clearing the old active markers when the list of vehicles is updated.
- Calling
pickRoute
when someone clicks on theroute-selected
overlay.
What you need to know
- Use
marker.setMap(null)
to remove a marker from a map.
The solution
Update the JavaScript tab to:
Result
When finished, you should see something like the following CodePen: