Introduction

This document provides guidance in the use of an application programing interface (API) that has been developed for lower-level access of link attributes available as a part of the Streetlytics™ data product. The Streetlytics™ API is JavaScript based and gives the user the ability to return traffic link data attributes for an area of interest. This introductory guide seeks to build understanding through the development of simple examples. Advanced users seeking a more concise treatment may wish to skip this guide and instead reference the user documentation. While this document attempts to cater to a wide user audience it still assumes the reader has at least a minimal understanding of JavaScript and jQuery.

Getting Started

In this section we will show a simple example of retrieving link data using some of the basic Streetlytics™ API calls. For this functionality we first need an API key value which confirms authorization.

Authorization

The Streetlytics™ API uses JSON Web Tokens (JWTs) for authorization. The first call the user should make would be either getToken with a username and password to receive a new API key or isValidToken to ensure their existing key is still valid. The user should then form a token by preceding the key with 'jwt'. All tokens take the form 'jwt APIKEY' where APIKEY is returned by the getToken call. Note, the JavaScript client will automatically prepend API keys with jwt. Afterwards, all calls indicated as requiring authorization should set the Authorization header of the request with the JWT.

Get Token

getToken is an API call that allows the user to create a token.

FORM

getToken(username, password)

Parameters
Parameter Type Default Description
username String None The user who is to receive the token
password String None User password
persist Boolean False Determines whether to use a temporary token, or a long-term token
Notes
  • There are two types of tokens, a temporary token and a long-term token. The long-term token can be set by passing the boolean value True to the parameter persist. The default token is the temporary one.
  • There is a maximum number of persisted tokens available.

Streetlytics Example 1: Get Token

For our first example we will set up a simple html page with a button that retrieves a token when pressed. For this test you will need a username and password to proceed and these should be replaced under the appropriate variable names in the StreetlyticsTest1.html file. The JavaScript file StreetlyticsTest1.js contains the function that is used to retrieve the authorization token. Both of these files should be placed in the same file folder and the html file should be opened in a web browser. Click the button and you should see either the token value if successful or an error message if not. Any issues with retrieving a valid token should be directed to Citilabs support.


<!DOCTYPE html>
<html>
    <head>
    <script src="jquery-3.3.1.min.js"></script>
    <script src="streetlyticstest1.js"> </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("button").click(function () {
                var streetlytics_username = "Your_Username";
                var streetlytics_Password = "Your_Password";
                getToken(streetlytics_username, streetlytics_password);
            });
        });
    </script>
    </head>
    <body>
    <button type="button">Get Token</button>
    <p></p>
    </body>
</html>

Figure 1: StreetlyticsTest1.html


function getToken(streetlytics_username, streetlytics_password){
    var streetlyticsToken = "";
    $.ajax({
        url: "https://api.streetlytics.com/getToken",
        dataType: "json",
        contentType: "application/json",
        method: "POST",
        data: JSON.stringify({
            username: streetlytics_username,
            password: streetlytics_password
        }),
        success: function (data) {
            streetlyticsToken = data.token;
            $("p").append("Streetlytics Token = " + streetlyticsToken);
        },
        error: function () {
            alert("Error");
        }
    });
    return streetlyticsToken;
});

Figure 2: StreetlyticsTest1.js

If the user can receive a valid authorization token then they are ready to move on to the next step to retrieve data from a point using the segments API call.

Segments

The segments API call allows users to retrieve link data within a geographical region.

Parameters

Parameter Type Default Description
segments_result_type string COMPRESSED Choose how to display the results data. options COMPRESSED, COMPRESSED_NO_ATTRIBUTE_NAMES, PURE_GEOJSON
segments_limit int 10000 Limits the segment list ex. 500
paging boolean false Whether to show pagination
search_type string point Search by point or bbox. bbox parameter must be in BBOX format
dir string none Filters by selected direction
road_name string none Restricts search to roads with specified name
road_name_match_type string none How to match against the provided road name. Options: EXACT, LEFT_MATCH, IS_NOT_EXACT, EXACT_WITH_DIR_PREFIXES
func_classes int none Use a function class of 1 to 5
lat float none latitude of a point
lng float none longitude of a point
radius float 0 radius to search withing
bbox string none string of four floats separated by commas that represent a bounded box

Streetlytics Example 2: Get Point Segment Data

The simplest way to use the Streetlytics™ API utilizes a standard latitude and longitude location for accessing point data. This precise method of location is preferable over addresses which may provide inconsistent results in certain situations (though street names can be used as arguments for returning specific link data). For users who need to use addresses the chapter following this section describes how to convert an address into a geographic coordinate using a geocoding service which will be used here to build towards more advanced examples.

Here we will use the ‘point’ attribute of the segments API call to retrieve link data. We will perform a similar getToken call, this time returning the token value for use in a new function getPoint. Our html file will now be updated to include two JavaScript files, the first being Streetlytics1.js which includes the getToken call and the second StreetlyticsTest2.html which contains the new getPoint function. As before the html file should be loaded and this time when the user clicks the button a JSON response containing segment data for a point should appear.


<!DOCTYPE html>
<html>
    <head>
    <script src="jquery-3.3.1.min.js"></script>
    <script src="streetlyticsTest1.js"> </script>
    <script src="streetlyticsTest2.js"> </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("button").click(function () {
                var streetlytics_username = "Your_Username";
                var streetlytics_Password = "Your_Password";
                var token = getToken(streetlytics_username, streetlytics_password);
                var latitude = 33.74835801133548;
                var longitude = -84.39336776733398;
                getPoint(token, latitude, longitude);
            });
        });
    </script>
    </head>
    <body>
    <button type="button">Get Segment</button>
    <p></p>
    </body>
</html>

Figure 3: StreetlyticsTest2.html


function getPoint(token, latitude, longitude){
    $.ajax({
        url: "https://api.streetlytics.com/segments",
        dataType: "json",
        contentType: "application/json",
        method: "POST",
        data: JSON.stringify({
            search_type:'point',
            lng:	longitude,
            lat:	latitude,
            bbox:	null,
            func_classes:	null,
            road_name	: null,
            road_name_match_type:	'EXACT',
            dir:	null,
            segments_result_type:	'COMPRESSED',
            segments_limit:	null,
            paging:	false,
            page_number:	null
        }),
        beforeSend: function(xhr){
            xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
            xhr.setRequestHeader("Authorization", "jwt " + token);
        },
        success: function(data){
            const resultHtml = '${JSON.stringify(data,null,2)}';
            $results.val(resultHtml);
        },
        error: function(xhr, status, error) {
            // The query failed
            $("p").html("### Streetlytics Query Failure");
        },
        complete: function (data_response) {
            alert(data_response.responseText);
        }
    })
}

Figure 4: StreetlyticsTest2.js

Converting Addresses with a Geocoding Service

While the Streetlytics™ API utilizes geographic coordinates, it is often desirable to the user to have the capability to input street addresses. For a small number of addresses it is advised that the user simply seek out a web app to do the conversions manually but for a large number of address queries the user will want to utilize a geocoding API in their script to handle this automatically. There are numerous Geocoding API services available such as from Google or Mapquest which allow the user to convert an address into a precise set of coordinates. Geocoding APIs are not all created equal in terms of price and accuracy (e.g. open source geocoding APIs exist but may not be the most accurate) so it is advisable that the user explore the various options available and use the API best suited to their needs.. In this document we will provide an example of using the Mapquest Geocoding API but this is by no means an endorsement of this product.

Using the MapQuest Geocoding API

The Mapquest Geocoding API requires an authentication key which can be generated upon signing up for their developer plan (a free tier is available for small scale users and those wishing to test out this API). Information and full documentation for this API can be found at https://developer.mapquest.com/documentation/geocoding-api/address/get/.

Users can acquire a Mapquest key by signing up for the free service plan at https://developer.mapquest.com/plans. Once an account has been created, keys can be generated and managed from the user profile page.

We will show here a simple test that utilizes a JavaScript function call to invoke a jQuery GET request for a desired address which returns a JSON response from which we can extract the latitude and longitude. This test consists of two files which are included in the API documentation package, geocodetest.html and geocodetest.js. If trying to copy these files the user must ensure they have a jquery JavaScript file available. To test this, simply replace the Mapquest key value in the geocodetest.html file with a unique key and then load it with a web browser. The user should see a simple “Get Geocode” button at the top left corner of the page which when clicked will execute the code contained in the geocodetest.js file. After clicking the button the user should see the address corresponding to the geocodelocation variable in the html file with the corresponding latitude and longitude coordinates appear below the button.


<!DOCTYPE html>
<html>
    <head>
    <!-- User must download jquery file and reference it here -->
    <script src="jquery-3.3.1.min.js"></script>
    <script src="geocodetest.js"> </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("button").click(function () {
                var mapquestkey = "XXX"; // Replace 'XXX' with your unique key
                var geocodelocation = "8739 Gulf Blvd, Navarre FL";
                getGeocode(mapquestkey, geocodelocation);
            });
        });
    </script>
    </head>
    <body>
    <button type="button">Get Geocode</button>
    <p></p>
</body>
</html>

Figure 5: geocodeTest.html


function getGeocode(mapquestkey, geocodelocation) {
    $("p").html(geocodelocation + '
'); var latitude = ""; var longitude = ""; $.ajax({ type: 'GET', url: "http://www.mapquestapi.com/geocoding/v1/address", data: "key=" + mapquestkey + "&outFormat=json&location=" + geocodelocation, dataType: 'json', error: function (xhr, status, error) { // The query failed $("p").html("### Geocode Failure"); }, success: function (data) { //console.log(data) //Uncomment to log the returned object in console //For simplicity we just use the first returned location latitude = data.results[0].locations[0].latLng.lat longitude = data.results[0].locations[0].latLng.lng $("p").append("LATITUDE, LONGITUDE =" + latitude + ", " + longitude); }, /* // Uncomment this block to recieve a pop-up with the full json response complete: function (data_response) { alert(data_response.responseText); } */ }); }

Figure 6: geocodeTest.js

This is just a simple example of using a Geocode API, moving forward we will expand upon this and use the geocode API to process a list of addresses into coordinates and use them to return link attribute data with the Streetlytics™ API.