API

Track My Ride - API

Integrating TMR with your website

Introduction

As a Track My Ride customer, you can integrate the data feed from your tracker directly into your website.

This is helpful for your customers if they need to see the location of your vehicles on your website or if you would like to connect Track My Ride’s data feed with your own application.

To access the data feed for your vehicles you need your API key and User key, these can be found in your account once your login.

Data Feed
XML and JSON

To display the position on your vehicles to your customers we need to access the Track My Ride API data feed. The data feed can export data in either XML or JSON format. These are two common data formats that developers use to organise data. The data feed is configured to return the past 24 hours of tracking data for all the vehicles associated with your account by default.

On request, a Track My Ride user will be given two unique keys, an ‘api key‘ and ‘user key‘. These two keys are used to authenticate your request for accessing the API and to fetch the appropriate data from our database.

The Track My Ride API is accessed by making a HTTPS request (GET OR POST) to the following URL :

https://www.trackmyride.com.au/app/php/api.php

The variables that need to be passed to the url as a GET or POST Request are as follows :

VariableTypeOptional?Details
api_key(string)RequiredYour unique api key, provied by the Track My Ride team on request.
user_key(string)RequiredYour unique user key, provied by the Track My Ride team on request.
limit(int)OptionalPass this variable to limit the number of data points returned in descending date order. A limit of 1 will ensure the fastest data lookup for the most recent point.
json(bool)OptionalPass this variable to have data returned as JSON format.

Making a Map
Putting it all together

To the right we have an example of the Track My Ride API integrated with the mapping library Leaflet to display the current location of the Canberra Hospital free bus for waiting passengers. Clicking on the bus will display some information regarding its current position. This data is captured in real-time!

In this example we will be integrating a mapping suite with out location data feed. We also want our map to automatically update the vehicle’s position when the vehicles move around without having to refresh the website. This can all be accomplished by using some simple Javascript code and an opensource mapping library called Leaflet. We will be using the Track My Ride Tile server to populate the map tiles into leaflet so our users can see the street names and easily locate our vehicles on the map.

  1. First, create a div on your website to place the map into.

    <div id="mapid" style="width: 600px; height: 400px"></div>
  2. Insert the JQuery and Leaflet javascript files along with the Leaflet CSS style files into the appropriate locations of your html page.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="https://npmcdn.com/[email protected]/dist/leaflet.js"></script>
    
    <link rel="stylesheet" href="https://npmcdn.com/[email protected]/dist/leaflet.css" />
  3. The below script was written to initialise the map div created above with the leaflet map, using the Track My Ride map tiles and to populate the map with the current location of the vehicles in the data feed. There is also a 10 second timeout to re-poll the API and update the position of the vehicles on the map.

    <script>
    
            //Your unique Track My Ride API and user keys.
            //These are required to access your data feed.
            var api_key  = 'fdsj329fjwd92kko439FDA12jFa12jk9402Ab';
            var user_key = 'ab46cf36de56ba93';
    
            //Disable jquery from caching out API requests.
            $.ajaxSetup({ cache: false });
    
            ///////////////////////////////////////////////////////
            // Do not change below this line
            ///////////////////////////////////////////////////////
    
            //Function to reload the current position of the bus.
            function getDeviceLocations( mymap, settings ) {
    
                var arrayOfLatLngs = [];
    
                //Load our icons
                $.ajax({
                    type: "GET",
                    url: "https://www.trackmyride.com.au/app/php/api.php?api_key="+api_key+"&user_key="+user_key+"&limit=1",
                    dataType: "xml",
                    cache: false,
                    success: function (xml) {
    
                        //remove the icons from prior runs of vehicles.
                        if(settings.vehicles.length > 0) {
                            for( c = 0; c < settings.vehicles.length; c++) {
                                settings.vehicles[c].icon.removeFrom(mymap);
                                delete settings.vehicles[c];
                            }
    
                            settings.vehicles = Array();
                        }
    
                        //Load in the new vehicle postion from the api data returned.
                        $(xml).find('data').children().each(function () {
    
                            var xmlData = $(this);
                            //For each vehicle in the XML feed.
                            var vehicle = { unique_id :   xmlData.find("unique_id").text(),
                                            name :        xmlData.find("name").text(),
                                            line_color :  xmlData.find("line_color").text(),
                                            arrow_color : xmlData.find("arrow_color").text(),
                                            updated_at :  xmlData.find("updated_at").text(),
                                            aaData :      xmlData.find("aaData").children(),
                                            icon : null};
    
                            //If no data is available for the vehicle, skip it.               
                            if(xmlData.find("aaData").children().length == 0 ) {
                                return;
                            }
    
                            var firstDataNode = vehicle.aaData.first();
                            var currentPosition = [firstDataNode.find("lat").text(), firstDataNode.find("lng").text()];
                            arrayOfLatLngs.push(currentPosition)
    
                            //Bind a clickable popup to the vehicle's icon.
                            vehicle.icon = L.marker(currentPosition, {icon: busIcon}).bindPopup("<b>Hello!</b><br />This is where the hospital bus<br/>currently is at "+firstDataNode.find("time").text());
                            vehicle.icon.addTo(mymap);
    
                            //Add the vehicle to our array of vehicles, so we can remove the icon next round.
                            settings.vehicles.push(vehicle);
                        });
    
                        //Fit the map to the markers.
                        var bounds = new L.LatLngBounds(arrayOfLatLngs);
                        mymap.fitBounds(bounds, {maxZoom : 17});
                    }
    
                });
            }
    
            //Internal settings.
            var settings = { runs : 0,
                             vehicles : [] };
    
            //Create the map and bind it to the div with ID 'mapid'
            var mymap = new L.Map('mapid', {
                                            trackResize: true,
                                            center: [-35.34807, 149.10084],  //The home position of the map. This is the ACT Health hospital. geographical point (longitude and latitude)
                                            zoom: 10
                                });
    
            //Map tiles can be loaded from Track My Ride's map tile engine.
            var mapStyle       = 'https://www.trackmyride.com.au/app/tiles.php?z={z}&x={x}&y={y}&r=nokia_plain',
                satelliteStyle = 'https://www.trackmyride.com.au/app/tiles.php?z={z}&x={x}&y={y}&r=nokia&v=1';
    
            //Add the tile layer to the map.
            //Change the variable mapStyle to satelliteStyle to change the tile background used..
            L.tileLayer(mapStyle, {
                                    attribution: "Map data © here.com, GPS by <a href='http://www.trackmyride.com.au'>TrackMyRide.com.au</a>"
                                  }).addTo(mymap);
    
            //Add the map scale to the map
            L.control.scale().addTo(mymap);
    
            //The bus icon and icon config
            var busIcon = L.icon({
                iconUrl: 'bus.png',
    
                iconSize:     [64, 64], // size of the icon
                iconAnchor:   [32, 32], // point of the icon which will correspond to marker's location
                popupAnchor:  [0, -32]  // point from which the popup should open relative to the iconAnchor
            });
    
            //Load the current bus position from our API.
            getDeviceLocations(mymap, settings);
    
            //Set an interval based timer to refresh the position every 10 seconds, in milliseconds.
            setInterval(function () {
                getDeviceLocations(mymap, settings)
            }, 10000, settings, mymap); 
    
    	</script>