Using xServer with JavaScript

Bundled clients

Framework agnostic JavaScript clients are bundled with PTV xServer, supporting moderately modern browsers. If you want to support Internet Explorer before version 8, you should include the json2.js script from JSON.org as well ensuring there is a JSONJSON (JavaScript Object Notation) is an open standard format for which human-readable text is used to transmit information consisting of attribute–value pairs. It is the first-address data format used for asynchronous browser/server communication (AJAX). parser and serializer object.

All clients of PTV xServer can be downloaded or can be found in the subdirectory client-bundle of the PTV xServer's installation directory. The clients are backward compatible but we recommend using the client-bundle with the same version as your PTV xServer. The clients also contain the experimental features. For experimental features it is required to use the xserver-client-bundle-<version>.zip with the same version as the PTV xServer.

Unpack the zipfile into your project directory and point to the JavaScript file:

<script src="mycompanyDirectory/javascript/xroute-client.js"></script>

Another possibility is to load the JavaScript client for each xServer service from the main entry point. For example:

<script src="http://mycompany.com:50000/services/xroute-client.js"></script>

But we recommend using the client-bundle.

Setup JavaScript client

To setup the JavaScript client, call the constructor in your applications script:

<script>
...
var xRoute = new XRouteClient();
...
</script>

If you call the constructor without arguments, the client code will retrieve the primary end point URL from the script location. You may also provide an argument with the base URL of the server (before the rs/... ). This is useful if you are planning to bundle multiple JavaScript files into one big file and do not want to load scripts from their individual origins, or if you have no browser context. The client will figure out whether a cross domain request will be needed, and will automatically switch to the best available solution (Internet Explorer is, as usual, very special).

The client object offers functions that handle the complete communication. These functions are named after the XService operations they call. The first argument of the client functions is the request object from the API.

Callback handler

Following the request argument you should provide a callback handler that will be called when a reply has arrived from the server. The callback handler is called with three arguments:

  1. responseObject - the returned response from the server, as a JavaScript object, or null in case of errors
  2. exceptionObject - the returned exception from the server, also modeled as a JavaScript object, or null in case of a success
  3. xhr - the XMLHttpRequest object, which you can query for details such as status codes. In case of CORS and Internet Explorer, the object may also be a XDomainRequest object which offers far fewer options.

The function will immediately return with the XMLHttpRequest (or XDomainRequest ) object after the send request command has been triggered. This object could be used to abort sending or to receive more status information, but can usually be ignored.

If you leave out the callback handler, the client object will attempt a synchronous communication and will immediately return with a response, or throw an exception object. Although this seems more convenient, you should refrain from using the synchronous mode as this will lock your user interface.

Optional argument timeout

After the callback handler, you can provide a further optional argument, the timeout . If you set the timeout to a positive value, the request will automatically terminate after the specified amount of milliseconds at the most. This does not stop the server processing, but allows you to react on an overly busy server situation. In case of a client timeout, the callback handler will be called with null values for both response and exception object. You can also provide default timeouts on a per-function basis. To do so, set a timeout property on the function objects themselves:

xRoute.calculateRoute.timeout = 10000;

HTTP request header

The client object also offers a setRequestHeader ( fieldName , fieldValue ) function which you can use to set an HTTP request header to be used for every call.

Below is a complete (and yet very short!) example for PTV xRoute service. It calculates a simple two-waypoint routeClosed A route corresponds to a path of a vehicle through the underlying transport network. The main attributes of a route are the distance and the time that the vehicle travels along the path.:

<html>
	<head>
		<title>xRoute Sample</title>
		<script src="http://yourserver:50000/services/xroute-client.js"></script>
		<script>
			var a = { "$type": "OffRoadWaypoint", "location": { "offRoadCoordinate": { "x": 6.1256572, "y": 49.5983745 } } };
			var b = { "$type": "OffRoadWaypoint", "location": { "offRoadCoordinate": { "x": 6.1256572, "y": 49.4816576 } } };
            
			var xroute = new XRouteClient();
			xroute.calculateRoute({ "waypoints": [ a, b ] }, routed);
            
			function routed(route, exc) {
				var resultDiv = document.getElementById("result");
				resultDiv.innerHTML  = route.distance + "m in " + route.travelTime + "s";
			}
		
		</script>
	</head>
	<body>
		<h1>xRoute Sample</h1>
		<p>Calculating route from location 6.1256572, 49.5983745 to 6.1256572, 49.4816576.</p>
		<p>Result: <div id="result">0</div></p>
	</body>
</html>

Generating clients

JavaScript developers do not need specific client classes to encapsulate object types: there are simply no strict object types. Communication is kept simple and convenient using several alternative mature Ajax frameworks. Any of these will do. Below is an example using JQuery:


var request = {
	"waypoints": [
		{
			"$type": "OffRoadWaypoint",
		    "location": {
			   "offRoadCoordinate": {
				   "x": 6.22029,
				   "y": 49.61513
			   }
			}
		},
		{
			"$type": "OffRoadWaypoint",
			"location": {
			   "offRoadCoordinate": {
				   "x": 6.06479,
				   "y": 49.62127
			   }
			}
		}
	],
	"resultFields": {
		"polyline": true
	}
}
	
$.ajax({
  type: 'POST',
  url: "http://localhost:50000/services/rs/XRoute/calculateRoute",
  contentType:"application/json; charset=utf-8",
  data: JSON.stringify(request),
  success: function(data) { 
				alert(data.distance); 
  		   }
});