fbpx

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.

From within your Track My Ride account you can generate your unique ‘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://app.trackmyride.com.au/v2/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 some of our own TMR vehicles. Clicking on the vehicle icons 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 OpenStreetMap 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. Please see OpenStreetMap Tile Servers for usage guidelines on using these map tiles.

  1. First, create a div on your website to place the map into. This div is set to be 600x400px in size.

    <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 will initialise the map div created above with the leaflet map and populate the map with the current location of the vehicles in the data feed. There is a 30 second timeout to re-poll the API and update the position of the vehicle markers on the map.
<script>
	//Your unique Track My Ride API and user key pair. These are required to access your data feed.
	//Create your API key pair from your account at https://app.trackmyride.com.au
	//under Account Settings -> API
	//You can also use the API key pair associated with a subaccount under Account Settings -> Subaccounts
	//Click the row of the subaccount to expand the record and view the keys.
	var api_key  = 'GF83FDSa72hds82jfFD82js123j3284mw8223';
	var user_key = 'gtr873ns2eDSf111';

	//Disable jquery from caching out API requests.
	jQuery.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
		jQuery.ajax({
			type: "GET",
			url: "https://app.trackmyride.com.au/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.
				jQuery(xml).find('data').children().each(function () {

					var xmlData = jQuery(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>"+vehicle.name+"</b><br/>Recorded 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);
				
				if(settings.runs == 0) {
					mymap.fitBounds(bounds, {maxZoom : 17});
					mymap.zoomOut();
				}
				
				//Increment the number of times we've updated the map
				settings.runs++;
			}

		});
	}

	//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. Geographical point (longitude and latitude)
									zoom: 10
						});

	//Utilising the Open Street Map tile servers. 
	//Please see https://operations.osmfoundation.org/policies/tiles/ for usage guidance.
	var mapStyle       = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';

	//Add the tile layer to the map.
	L.tileLayer(mapStyle, {
							attribution: "&copy; <a href='https://www.openstreetmap.org/copyright'>OpenStreetMap</a> contributors, <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 map marker icon and icon config
	//Change this to an icon of your choice of size 64x64 px
	var busIcon = L.icon({
		iconUrl: 'https://www.trackmyride.com.au/wp-content/uploads/2019/07/icon_car_256.png',

		iconSize:     [64, 64], // size of the icon
		iconAnchor:   [32, 64], // 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 30 seconds, in milliseconds.
	setInterval(function () {
		getDeviceLocations(mymap, settings)
	}, 30000, settings, mymap); 

</script>