The MapAPI 1.0 is deprecated. Please use the new MapAPI 1.1.





« Previous chapter 3: Mapping and Geocoding   Back to Index   Next chapter 5: Controls »

Chapter 4: Routing

4.1 Simple routing example

This example shows how to use the routing client. The procedure is very similar to the geocoding example. If you read the geocoding example already, you should have no problems understanding this code. With example 4a we will start with a very simple routing example, where start and destination are given as coordinates. In example 4b we will add more options, like interstations in our route, and in example 4c we will combine routing and geocoding.

 Routing example 4a (view example)

 Source code example 4a:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
	<head>
		<title>mapsuite Javascript API - Chapter 4: Routing example 4a</title>		
		<link type="text/css" rel="stylesheet" href="http://iw.mapandroute.de/MapAPI-1.0/css/screen.css"></link>
		<script type="text/javascript" src="http://iw.mapandroute.de/MapAPI-1.0/js/mapping.js"></script>	
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">	
	</head>
	<body class="tutorial">
		<script language="javascript">

			var client = new IWRoutingClient();			
			IWEventManager.addListener(client, 'onroute', function(event) { return showRoutingResult(event); });
			
			/**
			 * Calls the routing services.
			 *
			 * @private
			 * @param {double} x1
			 * @param {double} y1
			 * @param {double} x2
			 * @param {double} y2
			 * @return {void}
			 */
			function doRouting(x1, y1, x2, y2)
			{				
				var startAddress = new IWAddress();
				startAddress.setCoordinate(new IWCoordinate(x1, y1, IWCoordinate.WGS84));
				
				var destinationAddress = new IWAddress();
				destinationAddress.setCoordinate(new IWCoordinate(x2, y2, IWCoordinate.WGS84));
				
				client.route(startAddress, destinationAddress);		
			}
			
			/**
			 * Shows the routing result in a table.
			 *
			 * @private
			 * @param {IWRoutingEvent} event
			 * @return {void}
			 */
			function showRoutingResult(event)
			{
				var table = document.getElementById('resultTable');								

				for (var i = table.rows.length-1; i > 0; i--)
				{
					table.deleteRow(i);
				}

				var route = event.route;
					
				for(var i = 0; i < route.getSegments(); i++) 
				{					
					var entry = route.getEntry(i);	
					
					var tr = table.insertRow(i+1);
					tr.className = (i % 2 ? 'even' : 'odd');
					
					tr.insertCell(0).innerHTML = i+1;
					tr.insertCell(1).innerHTML = entry.getType();													
					tr.insertCell(2).innerHTML = entry.getStreetType();
					tr.insertCell(3).innerHTML = entry.getEntryDistance();
					tr.insertCell(4).innerHTML = entry.getTotalDistance();
					tr.insertCell(5).innerHTML = entry.getEntryTime();
					tr.insertCell(6).innerHTML = entry.getTotalTime();
					tr.insertCell(7).innerHTML = entry.getSegment();
					tr.insertCell(8).innerHTML = entry.getConnector();
					tr.insertCell(9).innerHTML = entry.getDirection();
					tr.insertCell(10).innerHTML = entry.getCoordinate().getX() + ', ' + entry.getCoordinate().getY();
					tr.insertCell(11).innerHTML = entry.getOrientation();
					tr.insertCell(12).innerHTML = entry.getRoundaboutType();
					tr.insertCell(13).innerHTML = entry.getRoundaboutNumber();
					tr.insertCell(14).innerHTML = entry.getSignPost();
					tr.insertCell(15).innerHTML = entry.getDescription();
				}						
				return true;
			}
		</script>	
		
		<h1>Chapter 4: Routing example 4a</h1>
		
		<h2>4.1 Setting the coordinates</h2>
				
		<form>
			<table>
				<tr>
					<td>Starting point</td>
					<td><input type="text" size="10" name="x1" value="267362"></td>
					<td><input type="text" size="10" name="y1" value="214497"></td>					
					<td>e.g. Köln (lat 50.922106, lon 6.951698)</td>				
				</tr>
				<tr>
					<td>Destination point</td>
					<td><input type="text" size="10" name="x2" value="277778"></td>
					<td><input type="text" size="10" name="y2" value="192791"></td>
					<td>e.g. Bonn (lat 50.732705, lon 7.096311)</td>	
				</tr>
			</table>
			<br>
			<input type="button" value="calculate route" 
				onClick="doRouting(this.form.x1.value, this.form.y1.value, this.form.x2.value, this.form.y2.value)">
		</form>
		
		<h2>4.2 Your route</h2>
		
		<table id="resultTable">
			<tr>
				<th>Pos.</th>
				<th>Type</th>
				<th>Street type</th>
				<th>Entry distance</th>										
				<th>Total distance</th>										
				<th>Entry time</th>
				<th>Total time</th>										
				<th>Segment</th>
				<th>Connector</th>										
				<th>Direction</th>
				<th>Coordinate</th>										
				<th>Orientation</th>	
				<th>Roundabout Type</th>
				<th>Roundabout Number</th>								
				<th>Signpost</th>
				<th>Description</th>
			</tr>					
		</table>
		
		<br><br>	
	</body>
</html>

In this very simple example we let the user enter (already geocoded) coordinates. Like in the geocoding example, we define two javascript methods, doRouting() and showRoutingResult(). In doRouting() we just forward the values from our form we defined in our html code. This method will be executed when the user presses the submit button.

The showRoutingResult() method writes the answer in the table resultTable that we defined at the bottom of our code.

4.1.1 Creating the router client

		var client = new IWRoutingClient();			
		IWEventManager.addListener(client, 'onroute', function(event) { return showRoutingResult(event); });

At first we need our routing client, so we instantiate the IWRoutingClient class.

Then we add a new listener to the IWEventManager object. With the IWEventManager we can add so called "listeners". Listeners can be used to determine when a request comes in. In this case, we use it to call our "showRoutingResult()" method when the routing service has sent an answer.

4.1.2 Calling the routing service

		function doRouting(x1, y1, x2, y2)
		{	
			var startAddress = new IWAddress();
			startAddress.setCoordinate(new IWCoordinate(x1, y1, IWCoordinate.WGS84));
				
			var destinationAddress = new IWAddress();
			destinationAddress.setCoordinate(new IWCoordinate(x2, y2, IWCoordinate.WGS84));
			
			client.route(startAddress, destinationAddress);			
		}

Here we just forward our request to the designated method of the API. This method takes two IWCoordinates. You can add more Options here, this will be shown in further examples.

The server will now process our request and will send an answer. This answer will then be catched by our listener.

4.1.3 Receiving the routing answer

		function showRoutingResult(event)
		{
			var route = event.route;
If our listener (that we created at step one) catches an answer, it calls our function with the event it receives as parameter. We know that this event is our route, so we save it in a new variable.
		var table = document.getElementById('resultTable');								
	
		for (var i = table.rows.length-1; i > 0; i--)
		{
			table.deleteRow(i);
		}

While we have our route now, we want to present it to our user. Therefore we take our resultTable that we will create at step five, and delete all rows from possible previous requests.

We can now go through our route and print the details in our table:

		for(var i = 0; i < route.getSegments(); i++)   
		{                     
			var entry = route.getEntry(i);

If the route exists, we print a new table row for each route entry.

		tr.insertCell(0).innerHTML = i+1;

The first field is just for counting the results.

	
		tr.insertCell(1).innerHTML = entry.getType();

The method getType() returns one of the following values:

No Type
1 normal
2 interstation
		tr.insertCell(2).innerHTML = entry.getStreetType();		
		

The method getStreetType() returns one of the following values:

No. Street type
1 highway
2 interstate
3 ferry
4 railway
5 other
	
		tr.insertCell(3).innerHTML = entry.getEntryDistance();
		

The method getEntryDistance() returns the distance for this entry in meters.

	
		tr.insertCell(4).innerHTML = entry.getTotalDistance();
		

The method getTotalDistance() returns the distance to this entry in meters.

	
		tr.insertCell(5).innerHTML = entry.getEntryTime();
		

The method getEntryTime() returns the driving time for this entry in seconds.

	
		tr.insertCell(6).innerHTML = entry.getTotalTime();
		

The method getTotalTime() returns the driving time to this entry in seconds.

	
		tr.insertCell(7).innerHTML = entry.getSegment();
		

The method getSegment() returns the segment name of this entry.

	
		tr.insertCell(8).innerHTML = entry.getConnector();
		

The method getConnector() returns the connector name to the next segment.

	
		tr.insertCell(9).innerHTML = entry.getDirection();
		

The method getDirection() returns the next direction. The directions are encoded in numbers. Here is the listing:

No. Meaning
-3 sharp left (scharf links abbiegen)
-2 left (links abbiegen)
-1 half left (halblinks abbiegen)
0 straight ahead (folgen dem Straßenverlauf)
1 half right (halbrechts abbiegen)
2 right (rechts abbiegen)
3 sharp right (scharf rechts abbiegen)
10 start and destination (Start- und Zielpunkt)
11 roundabout (in Kreisverkehr einordnen)
	
		tr.insertCell(10).innerHTML = entry.getCoordinate().getX() + ', ' + entry.getCoordinate().getY();	
		

The method getCoordinate() returns the coordinate of this entry.

	
		tr.insertCell(11).innerHTML = entry.getOrientation();
		

The method getOrientation() returns the driving orientation in "Grad Celcius" (0-359).

	
		tr.insertCell(12).innerHTML = entry.getRoundaboutType();
		

The method getRoundaboutType() returns the string "in" if the entry is part of an roundabout, otherwise it returns an empty string.

	
		tr.insertCell(13).innerHTML = entry.getRoundaboutNumber();
		

The method getRoundaboutNumber() returns the exit number if the entry is part of an roundabout, otherwise it returns an empty string.

	
		tr.insertCell(14).innerHTML = entry.getSignPost();
		

The method getSignPost() returns driving directions and sign information.

	
		tr.insertCell(15).innerHTML = entry.getDescription();
		

The method getDescription() returns a description for this entry.

4.1.4 Setting the routing coordinates

		<form>
			<table>
				<tr>
					<td>Starting point</td>
					<td><input type="text" size="10" name="x1" value="6.951698"></td>
					<td><input type="text" size="10" name="y1" value="50.922106"></td>
					<td>e.g. Köln (lat 50.922106, lon 6.951698)</td>						
				</tr>
				<tr>
					<td>Destination point</td>
					<td><input type="text" size="10" name="x2" value="7.096311"></td>
					<td><input type="text" size="10" name="y2" value="50.732705"></td>
					<td>e.g. Bonn (lat 50.732705, lon 7.096311)</td>		
				</tr>
			</table>
			<br>
			<input type="button" value="submit" onClick="doRouting(this.form.x1.value, this.form.y1.value, this.form.x2.value, this.form.y2.value)">
		</form>
		

This is a simple html form, the only interesting line is the input tag at the bottom, where we send our form content to our doRouting() method.

4.1.5 Displaying the route description

		<h2>4.2 Your route</h2>
		
		<table id="resultTable">
			<tr>
				<th>Pos.</th>
				<th>Type</th>
				<th>Street type</th>
				<th>Entry distance</th>										
				<th>Total distance</th>										
				<th>Entry time</th>
				<th>Total time</th>										
				<th>Segment</th>
				<th>Connector</th>										
				<th>Direction</th>
				<th>Coordinate</th>										
				<th>Orientation</th>	
				<th>Roundabout Type</th>
				<th>Roundabout Number</th>								
				<th>Signpost</th>
			</tr>					
		</table>
		

In this table we want to present the results. We just define the "hull" here, the main part is done by the showRoutingResult() method. Therefore it is important that the table id here matches with the id we use in that method.

4.2 Setting the routing options

You can customize the routing with several options. These options are presented in the next example. As this example is only a modified version from example 4a, we'll just discuss the changes here.

 Show example 4b

4.2.1 Routing options for infoware-router client

	function doRouting()
	{
		var form = document.getElementById("routingform");
		var routeOptions = new IWRouteOptions();
		
		routeOptions.setLanguage(form.language.value);
		routeOptions.setType(form.routingMode.value);
		routeOptions.setCitySpeed(form.citySpeed.value);
		routeOptions.setCountryRoadSpeed(form.countryRoadSpeed.value);
		routeOptions.setHighwaySpeed(form.highwaySpeed.value);
		
		client.setRouteOptions(routeOptions);

To configure the options we have to initialize the IWRouteOptions object. With setType() we can change the default setting for routing type. It takes one of the following string values: "SPEED": fastest route "LENGTH": shortest route "ECONOMY": most economic

With setCitySpeed(), setCountryRoadSpeed() and setHighwaySpeed() you can change the average speed, which will be assumed when the route is calculated.

		
		//********************************************************************
		//* Create the start, destination and interstation addresses
		//********************************************************************				

		var startAddress = new IWAddress();
		startAddress.setCoordinate(new IWCoordinate(form.x1.value, form.y1.value, IWCoordinate.WGS84));
						
		var destinationAddress = new IWAddress();
		destinationAddress.setCoordinate(new IWCoordinate(form.x2.value, form.y2.value, IWCoordinate.WGS84));
						
		var interstations = new Array();
		if (form.ix1.value != '' && form.iy1.value != '')
		{
			var interstationAddress = new IWAddress();
			interstationAddress.setCoordinate(new IWCoordinate(form.ix1.value, form.iy1.value, IWCoordinate.WGS84));
					
			interstations.push(interstationAddress);
		}
						
		if (form.ix2.value != '' && form.iy2.value != '')
		{
			var interstationAddress = new IWAddress();
			interstationAddress.setCoordinate(new IWCoordinate(form.ix2.value, form.iy2.value, IWCoordinate.WGS84));
						
			interstations.push(interstationAddress);
		}

The routing client needs at least two parameters to calculate a route between the start and destination coordinates. A route can although be based on more than two coordinates. These additional coordinates are called interstations. You can pass them through the routing algorithm by specifying them as an optional parameter. In this simple example we used no more than two interstations. But there is no limit of interstations.

		
		client.route(start, destination, interstations);									
	}

Last we are calling the method route on the routing client with three parameters. Remember that the third parameter is optional. After the route has been calculated by the routing service the listener method showRoutingResult will be called.

4.3 Routing and Geocoding

This example shows how to combine routing and geocoding. Most of the code is explained in previous examples, head back to them if you have problems in understanding the code. This implementation doesn't pay much attention to the usability, as the main intention is not to show you how to make a nice user interface, but to show how to work with the API.

 Show example 4c

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
	<head>
		<title>mapsuite Javascript API - Chapter 4: Routing example 4c</title>		
		<link type="text/css" rel="stylesheet" href="http://iw.mapandroute.de/MapAPI-1.0/css/screen.css"></link>
		<script type="text/javascript" src="http://iw.mapandroute.de/MapAPI-1.0/js/mapping.js"></script>	
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">			
	</head>
	<body class="tutorial">
		<script language="javascript">
			
			//********************************************************************
			//* Creates a new routing client and registers a callback event 
			//* handler for onroute-events.
			//********************************************************************
						
			var routingClient = new IWRoutingClient();			
			IWEventManager.addListener(routingClient, 'onroute', function(event) {	return showRoutingResult(event); });

			//********************************************************************
			//* Creates a new geocoding client and registers a callback event 
			//* handler for ongeocode-events.
			//********************************************************************
			
			var geocoderClient = new IWGeocoderClient();
			IWEventManager.addListener(geocoderClient, 'ongeocode', function(event)	{ return showGeocodingResults(event, true); });
			
			/**
			 * Calls the geocoding services with a limit of 10 addresses.
			 *
			 * @private
			 * @return {void}
			 */						
			function doGeocoding()
			{				
				var startAddress = document.getElementById('form1').start.value;
				var startCountry = document.getElementById('form1').country_start.value;
				
				geocoderClient.geocodeAddressString(startAddress, startCountry, 10, 'startAddress');
				
				var destAddress = document.getElementById('form1').destination.value;
				var destCountry = document.getElementById('form1').country_destination.value;
				
				geocoderClient.geocodeAddressString(destAddress, destCountry, 10, 'destAddress');
			}	
						
			/**
			 * Shows the geocoded address.
			 * 
			 * @private
			 * @param {IWGecodingEvent} event
			 * @param {boolean} start
			 * @return {void}
			 */
			function showGeocodingResults(event, start)
			{
				var results = event.results;
				var selectField = null;

				//********************************************************************
				//* The first listener calls showGeocodingResults with start = true,
				//* so we know that we have our results for the start request.
				//********************************************************************						
								
				if (event.parameterObject == 'startAddress') 
				{
					selectField = document.getElementById("form2").selectStartAddress;
				} 
				else if (event.parameterObject == 'destAddress')
				{
					selectField = document.getElementById("form2").selectDestinationAddress;
				}
				else
				{
					alert('Unknown parameterObject: ' + event.parameterObject);
				}

				//********************************************************************
				//* Removes existing options fields
				//********************************************************************	

				selectField.options.length = 0;
				
				//********************************************************************
				//* Writes all results to the select list...
				//********************************************************************	

				for(var i = 0; i < results.length; i++) 
				{
					var text = '';
					var result = results[i];	
					var address = result.getAddress();
					
					//********************************************************************
					//* We create a option field for each geocoded address. The reference
					//* is stored in the address attribute of the option field.
					//********************************************************************	

					var optionField = document.createElement('option');
					optionField.value = i;
					optionField.address = address;
										
					if (address.getStreet())
					{
						text = address.getStreet();
					}
					if (address.getHouseNumber()) 
					{
						text += ' ' + address.getHouseNumber();
					}
					if (address.getZipCode())
					{
						text += ' ' + address.getZipCode();
					}
					if (address.getCity())
					{
						text += ' ' + address.getCity();
					}
					if (address.getCountryCode())
					{
						text += ' ' + address.getCountryCode();
				 	}
				 		
					optionField.appendChild(document.createTextNode(text));
					selectField.appendChild(optionField);
				}
			}
			
			/**
			 * Calls the routing service.
			 * 
			 * @private
			 * @return {void}
			 */
			function doRouting()
			{
				var selectStartAddress = document.getElementById('form2').selectStartAddress;
				var selectDestinationAddress = document.getElementById('form2').selectDestinationAddress;

				//********************************************************************
				//* Check parameters
				//********************************************************************	
				if (selectStartAddress.length == 0 || selectDestinationAddress.length == 0)
				{
					alert("Please geocode your start and destination address.");
					return;	
				}
				
				if (selectStartAddress.value == '' || selectDestinationAddress.value == '')
				{
					alert("Please chose your start and destination address.");
					return;	
				}
				
				//********************************************************************
				//* Parse the start and destination coordinates ... 
				//********************************************************************	
				var fromXY = selectStartAddress.value.split(';');
				var fromCoordinate = new IWCoordinate(fromXY[0], fromXY[1]);
				var toXY = selectDestinationAddress.value.split(';');
				var toCoordinate = new IWCoordinate(toXY[0], toXY[1]);

				//********************************************************************
				//* ... and call the routing service
				//********************************************************************	
				routingClient.route(fromCoordinate, toCoordinate);
			}
			
			/**
			 * Shows the routing result in a table.
			 *
			 * @private
			 * @param {IWRoutingEvent} event
			 * @return {void}
			 */				
			function showRoutingResult(event)
			{
				var table = document.getElementById("resultTable");								

				for (var i = table.rows.length-1; i > 0; i--)
				{
					table.deleteRow(i);
				}

				var route = event.route;
					
				for(var i = 0; i < route.getSegments(); i++) 
				{					
					var entry = route.getEntry(i);	
					
					var tr = table.insertRow(i+1);
					tr.className = (i % 2 ? 'even' : 'odd');
					
					tr.insertCell(0).innerHTML = i+1;
					tr.insertCell(1).innerHTML = entry.getType();													
					tr.insertCell(2).innerHTML = entry.getStreetType();
					tr.insertCell(3).innerHTML = entry.getEntryDistance();
					tr.insertCell(4).innerHTML = entry.getTotalDistance();
					tr.insertCell(5).innerHTML = entry.getEntryTime();
					tr.insertCell(6).innerHTML = entry.getTotalTime();
					tr.insertCell(7).innerHTML = entry.getSegment();
					tr.insertCell(8).innerHTML = entry.getConnector();
					tr.insertCell(9).innerHTML = entry.getDirection();
					tr.insertCell(10).innerHTML = entry.getCoordinate().getX() + ', ' + entry.getCoordinate().getY();
					tr.insertCell(11).innerHTML = entry.getOrientation();
					tr.insertCell(12).innerHTML = entry.getRoundaboutType();
					tr.insertCell(13).innerHTML = entry.getRoundaboutNumber();
					tr.insertCell(14).innerHTML = entry.getSignPost();
				}						
				return true;
			}
		</script>	
		
		<h1>Chapter 4: Routing example 4c</h1>  
          
		<h2>4.1 Enter your start and destination address</h2>  
		
		<form id="form1">
			<table id="geocode">
				<tr>
					<td>Start address</td>
					<td><input type="text" size="30" name="start" value="Berlin"></td>
					<td>
						<select name="country_start">
							<option value="AND">Andorra</option>
							<option value="B">Belgium</option>
							<option value="DK">Denmark</option>
							<option value="D" selected>Germany</option>		
							<option value="FIN">Finnland</option>		
							<option value="F">France</option>		
							<option value="GR">Greece</option>				
							<option value="GB">Great Britain</option>						
							<option value="IRL">Ireland</option>
							<option value="I">Italy</option>
							<option value="L">Luxembourg</option>
							<option value="NL">Netherlands</option>
							<option value="A">Austria</option>
							<option value="N">Norway</option>		
							<option value="PL">Poland</option>		
							<option value="P">Portugal</option>
							<option value="RSM">San Marino</option>
							<option value="S">Sweden</option>
							<option value="CH">Switzerland</option>
							<option value="SK">Slovakia</option>
							<option value="E">Spain</option>
							<option value="CZ">Czech Republic</option>
							<option value="H">Hungary</option>
						</select>
					</td>
				</tr>
				<tr>
					<td>Destination address</td>
					<td><input type="text" size="30" name="destination" value="Köln"></td>
					<td>
						<select name="country_destination">
							<option value="AND">Andorra</option>
							<option value="B">Belgium</option>
							<option value="DK">Denmark</option>
							<option value="D" selected>Germany</option>		
							<option value="FIN">Finnland</option>		
							<option value="F">France</option>		
							<option value="GR">Greece</option>				
							<option value="GB">Great Britain</option>						
							<option value="IRL">Ireland</option>
							<option value="I">Italy</option>
							<option value="L">Luxembourg</option>
							<option value="NL">Netherlands</option>
							<option value="A">Austria</option>
							<option value="N">Norway</option>		
							<option value="PL">Poland</option>		
							<option value="P">Portugal</option>
							<option value="RSM">San Marino</option>
							<option value="S">Sweden</option>
							<option value="CH">Switzerland</option>
							<option value="SK">Slovakia</option>
							<option value="E">Spain</option>
							<option value="CZ">Czech Republic</option>
							<option value="H">Hungary</option>
						</select>
					</td>
				</tr>
				<tr>
			</table>
			<br>
			<input id="button" type="button" value="geocode address" onClick="doGeocoding()">
		</form>
		
		<h2>4.2 Select your start and destination address</h2>
		
		<form id="form2">
			<table id="geocode">
				<tr>
					<td>Start address</td>
					<td>
						<select name="selectStartAddress" size="10"></select>
					</td>
					<td>Destination address</td>
					<td>
						<select name="selectDestinationAddress" size="10"></select>
					</td>
				</tr>
				<tr>
			</table>
			<br>
			<input id="button" type="button" value="calculate route" onClick="doRouting()">
		</form>		
		
		<h2>4.3 Your route</h2>
		
		<table id="resultTable">
			<tr>
				<th>Pos.</th>
				<th>Type</th>
				<th>Street type</th>
				<th>Entry distance</th>										
				<th>Total distance</th>										
				<th>Entry time</th>
				<th>Total time</th>										
				<th>Segment</th>
				<th>Connector</th>										
				<th>Direction</th>
				<th>Coordinate</th>										
				<th>Orientation</th>	
				<th>Roundabout Type</th>
				<th>Roundabout Number</th>
				<th>Signpost</th>
			</tr>					
		</table>
		
		<br><br>		
	</body>
</html>

4.4 Drawing the route on the map

The following examples are drawing the calculated route on the map.

 Show example 4d

4.5 Creating the driving instructions

The following example uses a formatter class to create readable driving instructions.

 Show example 4e:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
	<head>
		<title>mapsuite Javascript API - Chapter 4: Routing example 4e</title>		
		<link type="text/css" rel="stylesheet" href="http://iw.mapandroute.de/MapAPI-1.0/css/screen.css"></link>
		<script type="text/javascript" src="http://iw.mapandroute.de/MapAPI-1.0/js/mapping.js"></script>	
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">			
	</head>
	<body class="tutorial" onload="initialize()">
		<script language="javascript">
			
			var map = null;
			
			//********************************************************************
			//* Layer to display the route. 
			//********************************************************************
			var routeLayer = null;
			
			function initialize()
			{
				map = new IWMap(document.getElementById('mapContainer'));
				map.setCenter(new IWCoordinate(7.1408879, 50.70150837, IWCoordinate.WGS84));
			}
			
			//********************************************************************
			//* Creates a new routing client and registers a callback event 
			//* handler for onroute-events.
			//********************************************************************
						
			var routingClient = new IWRoutingClient();			
			IWEventManager.addListener(routingClient, 'onroute', function(event) {	return showRoutingResult(event); });

			//********************************************************************
			//* Creates a new geocoding client and registers a callback event 
			//* handler for ongeocode-events.
			//********************************************************************
			
			var geocoderClient = new IWGeocoderClient();
			IWEventManager.addListener(geocoderClient, 'ongeocode', function(event)	{ return showGeocodingResults(event, true); });
			
			
			
			/**
			 * Calls the geocoding services with a limit of 10 addresses.
			 *
			 * @private
			 * @return {void}
			 */						
			function doGeocoding()
			{				
				var startAddress = document.getElementById('form1').start.value;
				var startCountry = document.getElementById('form1').country_start.value;
				
				geocoderClient.geocodeAddressString(startAddress, startCountry, 10, 'startAddress');
				
				var destAddress = document.getElementById('form1').destination.value;
				var destCountry = document.getElementById('form1').country_destination.value;
				
				geocoderClient.geocodeAddressString(destAddress, destCountry, 10, 'destAddress');
			}	
						
			/**
			 * Shows the geocoded address.
			 * 
			 * @private
			 * @param {IWGecodingEvent} event
			 * @param {boolean} start
			 * @return {void}
			 */
			function showGeocodingResults(event, start)
			{
				var results = event.results;
				var selectField = null;

				//********************************************************************
				//* The first listener calls showGeocodingResults with start = true,
				//* so we know that we have our results for the start request.
				//********************************************************************						
								
				if (event.parameterObject == 'startAddress') 
				{
					selectField = document.getElementById("form2").selectStartAddress;
				} 
				else if (event.parameterObject == 'destAddress')
				{
					selectField = document.getElementById("form2").selectDestinationAddress;
				}
				else
				{
					alert('Unknown parameterObject: ' + event.parameterObject);
				}

				//********************************************************************
				//* Removes existing options fields
				//********************************************************************	

				selectField.options.length = 0;
				
				//********************************************************************
				//* Writes all results to the select list...
				//********************************************************************	

				for(var i = 0; i < results.length; i++) 
				{
					var text = '';
					var result = results[i];
					var address = result.getAddress();					

					//********************************************************************
					//* We create a option field for each geocoded address. The reference
					//* is stored in the address attribute of the option field.
					//********************************************************************	

					var optionField = document.createElement('option');
					optionField.value = i;
					optionField.address = address;

					if (address.getStreet())
					{
						text = address.getStreet()
					}
					if (address.getHouseNumber()) 
					{
						text += ' ' + address.getHouseNumber();
					}
					if (address.getZipCode())
					{
						text += ' ' + address.getZipCode();
					}
					if (address.getCity())
					{
						text += ' ' + address.getCity();
					}
					if (address.getCountryCode())
					{
						text += ' ' + address.getCountryCode();
				 	}
				 		
					optionField.appendChild(document.createTextNode(text));
					selectField.appendChild(optionField);
				}
			}
			
			/**
			 * Calls the routing service.
			 * 
			 * @private
			 * @return {void}
			 */
			function doRouting()
			{
				var selectStartAddress = document.getElementById('form2').selectStartAddress;
				var selectDestinationAddress = document.getElementById('form2').selectDestinationAddress;

				//********************************************************************
				//* Check parameters
				//********************************************************************	
				if (selectStartAddress.length == 0 || selectDestinationAddress.length == 0)
				{
					alert('Please geocode your start and destination address.');
					return;	
				}
				
				if (selectStartAddress.value == '' || selectDestinationAddress.value == '')
				{
					alert('Please chose your start and destination address.');
					return;	
				}
				
				//********************************************************************
				//* Get the start and destination address 
				//********************************************************************
				
				var startAddress = selectStartAddress.options[selectStartAddress.selectedIndex].address;
				var destinationAddress = selectDestinationAddress.options[selectDestinationAddress.selectedIndex].address;

				//********************************************************************
				//* ... and call the routing service
				//********************************************************************	
				routingClient.route(startAddress, destinationAddress);
			}
			
			/**
			 * Shows the routing result in a table.
			 *
			 * @private
			 * @param {IWRoutingEvent} event
			 * @return {void}
			 */				
			function showRoutingResult(event)
			{
				var route = event.route;

				//********************************************************************
				//* Formats the driving instructions 
				//********************************************************************
				var formatter = new IWRouteFormatter(route);
				formatter.setLanguage('de');
			
				var span = document.getElementById('headerRoute');
				span.innerHTML = formatter.createSummaryAsHTML();			
			
				var table = document.getElementById('resultTable');								

				for (var i = table.rows.length-1; i > 0; i--)
				{
					table.deleteRow(i);
				}
				
				var formatter = new IWRouteFormatter(route);
				formatter.setLanguage('de');
				
				for(var i = 0; i < route.getSegments(); i++) 
				{					
					var tr = table.insertRow(i+1);
					tr.className = (i % 2 ? 'even' : 'odd');
					
					var td = tr.insertCell(0);
					td.innerHTML = i+1;

					var td = tr.insertCell(1);
					td.style.textAlign = 'center';			
					td.innerHTML = formatter.createImageAsHTML(i);									

					tr.insertCell(2).innerHTML = formatter.createDescriptionAsHTML(i);													
					tr.insertCell(3).innerHTML = formatter.createDistanceAsHTML(i);
				}			
				
				//********************************************************************
				//* Puts the routing layer on the map
				//********************************************************************	
				
				// if the routeLayer does not exist we create one.
				if (routeLayer == null)
				{
					routeLayer = new IWLayer(map, 'route', 'ROUTE');
					// the geometrie of a route is stored in a shape file.		
					routeLayer.addShape(new IWShape(route.getShape()));
					// add the route layer to the map.
					map.addLayer(routeLayer);					
				}
				else
				{
					// sets the name of the shapefile for the new route.
					routeLayer.getShapes()[0].setShapeName(route.getShape());
				}
				// set the new center and zooming level to show the whole route on the map.
				map.setCenter(route.getBounds().getCenter(), map.getBoundsZoomlevel(route.getBounds()));
							
				return true;
			}
		</script>	
		
		<h1>Chapter 4: Routing example 4e</h1>  
          
        <div id="mapContainer" style="position: absolute; top: 120px; left: 620px; background-color: #dddddd; width: 450px; height: 300px"></div>  
          
		<h2>4.1 Enter your start and destination address</h2>  
		
		<form id="form1">
			<table id="geocode">
				<tr>
					<td>Start address</td>
					<td><input type="text" size="30" name="start" value="Berlin"></td>
					<td>
						<select name="country_start">
							<option value="ALB">Albanien</option>
							<option value="AND">Andorra</option>
							<option value="B">Belgien</option>
							<option value="BIH">Bosnien-Herzegowina</option>	
							<option value="BGR">Bulgarien</option>						
							<option value="DK">Dänemark</option>
							<option value="D" selected>Deutschland</option>
							<option value="EST">Estland</option>
							<option value="FIN">Finnland</option>
							<option value="F">Frankreich</option>
							<option value="GRC">Griechenland</option>							
							<option value="GB">Großbritannien</option>	
							<option value="IRL">Irland</option>							
							<option value="I">Italien</option>
							<option value="HRV">Kroatien</option>
							<option value="LVA">Lettland</option>
							<option value="LTU">Litauen</option>
							<option value="L">Luxemburg</option>
							<option value="MKD">Makedonien</option>
							<option value="MLT">Malta</option>
							<option value="MDA">Moldawien</option>
							<option value="MNE">Montenegro</option>							
							<option value="NL">Niederlande</option>							
							<option value="N">Norwegen</option>
							<option value="PL">Polen</option>	
							<option value="P">Portugal</option>
							<option value="A">Österreich</option>
							<option value="ROU">Rumänien</option>							
							<option value="RUS">Russland</option>
							<option value="RSM">San Marino</option>							
							<option value="S">Schweden</option>							
							<option value="CH">Schweiz</option>
							<option value="SRB">Serbien</option>
							<option value="SVK">Slowakei</option>
							<option value="SVN">Slowenien</option>
							<option value="E">Spanien</option>
							<option value="CZ">Tschechien</option>
							<option value="TUR">Türkei</option>
							<option value="UKR">Ukraine</option>
							<option value="HUN">Ungarn</option>
							<option value="BLR">Weißrussland</option>
						</select>
					</td>
				</tr>
				<tr>
					<td>Destination address</td>
					<td><input type="text" size="30" name="destination" value="Köln"></td>
					<td>
						<select name="country_destination">
							<option value="ALB">Albanien</option>
							<option value="AND">Andorra</option>
							<option value="B">Belgien</option>
							<option value="BIH">Bosnien-Herzegowina</option>	
							<option value="BGR">Bulgarien</option>						
							<option value="DK">Dänemark</option>
							<option value="D" selected>Deutschland</option>
							<option value="EST">Estland</option>
							<option value="FIN">Finnland</option>
							<option value="F">Frankreich</option>
							<option value="GRC">Griechenland</option>							
							<option value="GB">Großbritannien</option>	
							<option value="IRL">Irland</option>							
							<option value="I">Italien</option>
							<option value="HRV">Kroatien</option>
							<option value="LVA">Lettland</option>
							<option value="LTU">Litauen</option>
							<option value="L">Luxemburg</option>
							<option value="MKD">Makedonien</option>
							<option value="MLT">Malta</option>
							<option value="MDA">Moldawien</option>
							<option value="MNE">Montenegro</option>							
							<option value="NL">Niederlande</option>							
							<option value="N">Norwegen</option>
							<option value="PL">Polen</option>	
							<option value="P">Portugal</option>
							<option value="A">Österreich</option>
							<option value="ROU">Rumänien</option>							
							<option value="RUS">Russland</option>
							<option value="RSM">San Marino</option>							
							<option value="S">Schweden</option>							
							<option value="CH">Schweiz</option>
							<option value="SRB">Serbien</option>
							<option value="SVK">Slowakei</option>
							<option value="SVN">Slowenien</option>
							<option value="E">Spanien</option>
							<option value="CZ">Tschechien</option>
							<option value="TUR">Türkei</option>
							<option value="UKR">Ukraine</option>
							<option value="HUN">Ungarn</option>
							<option value="BLR">Weißrussland</option>
						</select>
					</td>
				</tr>
				<tr>
			</table>
			<br>
			<input id="button" type="button" value="geocode address" onClick="doGeocoding()">
		</form>
		
		<h2>4.2 Select your start and destination address</h2>
		
		<form id="form2">
			<table id="geocode">
				<tr>
					<td>Start address</td>
					<td>
						<select name="selectStartAddress" size="7" style="width:180px"></select>
					</td>
					<td>Destination address</td>
					<td>
						<select name="selectDestinationAddress" size="7" style="width:180px"></select>
					</td>
				</tr>
				<tr>
			</table>
			<br>
			<input id="button" type="button" value="calculate route" onClick="doRouting()">
		</form>		
		
		<h2>4.3 Your route</h2>
		
		<span id="headerRoute"></span>
		
		<table id="resultTable" width="450px">
			<tr>
				<th width="0px">No.</th>
				<th width="450px" colspan=2>Description</th>
				<th width="0px">Distance</th>										
			</tr>					
		</table>
		
		<br><br>		
	</body>
</html>
		

4.6 Routing images

Name Direction Code Image
img/controls/routing/blue_sharp_left.gif -3
img/controls/routing/blue_left.gif -2
img/controls/routing/blue_half_left.gif -1
img/controls/routing/blue_straight_ahead.gif 0
img/controls/routing/blue_half_right.gif 1
img/controls/routing/blue_right.gif 2
img/controls/routing/blue_sharp_right.gif 3
img/controls/routing/blue_roundabout.gif 11
img/controls/routing/blue_highway.gif  
img/controls/routing/blue_highway_exit.gif  
img/controls/routing/blue_highway_junction.gif  
img/controls/routing/blue_destination.gif  

« Previous chapter 3: Mapping and Geocoding   Back to Index   Next chapter 5: Controls »