TESTING THE LONDON TFL API ROUTE PLANNER FUNCTIONALITY:
As I mentioned in my previous post, the TFL API route planner functionality proved far more complex to implement within my project than the line status updates. I have therefore written this separate post to document the process with further accuracy.
ROUTE PLANNER – API REQUIREMENTS:
The TFL API requires the user to enter specific station location identification numbers known as “NAPTAN IDs” in order to then calculate a given route. If a user’s input does not correspond to a relevant ID, the API returns a “disambiguation” result that does not include any route planning data.
To overcome this potential issue, I implemented two html “select” fields that offer users the functionality of searching for a station and selecting a relevant result known as an “option” from a “drop-down” list (see below). The advantage of “options” is that they hold additional data values. In this case, I assigned a NAPTAN ID value to each of the corresponding station options across TFL’s rail network. Users can therefore select/search for any station within the TFL network and the correct ID’s will be automatically referenced. It should be noted that I implemented custom select fields using the Select2 library. This enables the user to quickly search the range of options available from each select field.
CALLING THE API:
The functionality behind the route planner can be broken down into 3 major functions:
All three of these functions are called when a mouse click is detected from the route plan button.
The first two functions are nearly identical, they simply reference and retrieve the values from the “select” input fields from both the current station location and destination station location.
The third function (genRoute) is then passed the ID/Name of both the location/destination that were referenced within the previous two functions.
The genRoute() function performs the heavy-lifting in regards to the API. In turn, genRoute calls the route planner url from the TFL API using a jQuery ajax request. If the request is successful, the following data is referenced from the JSON data returned from the API:
- Route Duration
- Route Summary
- Route Details
- Start time
- Arrival time
- Stop points (stations which the train stops at)
Parsing the relevant JSON data was definitely the most complex aspect of this task. I consistently used the console log to test the results returned. On reflection I have learned a great deal about indexing results/arrays whilst also improving my ability to identify and iterate over specific data sets. Getting the stop point station data was particularly difficult as it required both correctly indexing arrays and then iterating through data correctly.
Below is the full ajax method I developed that calls the TFL API and parses the relevant JSON data to jquery variables:
DISPLAYING THE RESULTS
REFINING THE PRESENTATION