Score:
Login to rate page
|
|
Introduction
Tutorials
Getting Started
Map Objects
Html Objects
Map Object Groups
Map Layers Geocoding
Routing
Debugging
Digitizer
Advanced Examples
Digitizer
Location Based Services
Event Handling
Others
|
|
This routing tutorial for the MapTP AJAX API 2.3 shows how to implement the following functionality:
-
Restrict the number of returned geocode results
-
Select start and destination from a list of geocode results
-
Center the map view on a route segment
In the previous routing tutorials the first result from the list of geocode results was used for the route calculation. This might not always be the desired start or destination if there is more than one alternative for the given address. For example, if the user enters “Frankfurt” as start of the route, the geocoder will find both “Frankfurt am Main” and “Frankfurt (Oder)”.
The number of returned geocode results can be restricted. In this tutorial up to five geocode results for both start and destination of the route are returned and shown in a list box. After the user has chosen the desired start and destination from the list box, the user can start the route calculation by clicking on the “Show Route” button.
In addition, this tutorial shows how to center the map view on a route segment. For this a button is displayed next to each step of the route description. When the user clicks on a button the map view will be centered on the selected segment.
Step by Step Description
View example
Executable code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Route Calculation with Selection of Geocoded Start & Destination</title>
<script type="text/javascript" language="javascript" src="http://api.maptp.map24.com/ajax?appkey=YOUR_APPLICATION_KEY_GOES_HERE"></script>
<script type="text/javascript" language="javascript">
//Declare global variables
var geocoder = null;
var router = null;
var routePoints = [];
var routeID = null;
var startPointAlternatives = new Array();
var destinationPointAlternatives = new Array();
var startLoc = null;
var destLoc = null;
function goMap24() {
Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );
}
function map24ApiLoaded(){
Map24.MapApplication.init( { NodeName: "maparea" } );
//Hide HTML elements that should not be shown initially
document.getElementById("geocodingResults").style.visibility = "hidden";
document.getElementById("button_calculate_route").style.visibility = "hidden";
}
//Geocode given start and destination points.
//This function is called when the user clicks on the button "Choose the start and destination points".
function startRouting(){
//Initialize the array for storing route points
routePoints = {};
//Create a geocoder stub
if( geocoder == null ) geocoder = new Map24.GeocoderServiceStub();
//Retrieve start and destination of the route from the input fields
var start = Map24.trim( $v('start') );
var destination = Map24.trim( $v('destination') );
//Check if the start and the destination form fields are empty.
if( start == "" ) { alert("Please enter start address!"); return; }
if( destination == "" ) { alert("Please enter destination address!"); return; }
//Geocode the start address of the route
geocoder.geocode({
SearchText: start,
//Define a maximum number of geocoding results to limit
//the number of entries that will be shown in the result lists
MaxNoOfAlternatives: 5,
CallbackFunction: printGeocodingResult,
CallbackParameters: {position: "start"}
});
//Geocode the destination address of the route.
geocoder.geocode({
SearchText: destination,
MaxNoOfAlternatives: 5,
CallbackFunction: printGeocodingResult,
CallbackParameters: {position: "destination"}
});
}
//Callback function that is called when the geocoding result for the start or destination point is available.
//This function prints all alternative geocoded addresses for the start and destination points in two lists
//and allows to select one address from each list as start or destination point for the route calculation.
//The locs array contains the geocoded addresses.
function printGeocodingResult( locs, params ){
//Declare local variables
var county = null;
var city = null;
var zip = null;
var street = null;
var houseNo = null;
var state = null;
var result = "";
//Iterate through the array of geocoded addresses
for( var i=0; i<locs.length; i++ ){
//Access the fields of the geocoded address
county = locs[i].getCounty();
city = locs[i].getCity();
zip = locs[i].getZip();
street = locs[i].getStreet();
houseNo = locs[i].getHouseNo();
state = locs[i].getState();
//If an address field is null, it is not shown in the result list.
//Otherwise, the field's value is shown together with the category,
//e.g. "City: Frankfurt".
city == null? city = "": city = "City: "+city;
zip == null? zip = "": zip = ", Zip: "+zip;
street == null? street = "": street = ", Street: "+street;
houseNo == null? houseNo = "": houseNo = " "+houseNo;
county == null? county = "": county = ", County: "+county;
state == null? state = "": state = ", State: "+state;
//Add the geocoded address to the result list
result +="<option>"+city+state+zip+street+houseNo+county+"</option>";
}
//Print alternative geocoded addresses for the start point in a list
if (params.position=="start"){
//Store alternatives for start point in an array
for( var i=0; i<locs.length; i++ ){
startPointAlternatives[i] = locs[i];
}
//Show geocoded alternatives for the start point in a list
if( Map24.Browser.IE )
//For Internet Explorer:
document.getElementById("geocodingresultsStart").outerHTML ='<select name="printGeocodingResult" id="geocodingresultsStart" style="width:350px;">'+result+'</select>';
else
document.getElementById("geocodingresultsStart").innerHTML = result;
}
//Print alternative geocoded addresses for the destination point in a list
else {
//Store alternatives for destination point in an array
for( var i=0; i<locs.length; i++ ){
destinationPointAlternatives[i] = locs[i];
}
//Show geocoded alternatives for the destination point in a list
if( Map24.Browser.IE )
//For Internet Explorer:
document.getElementById("geocodingresultsDestination").outerHTML ='<select name="printGeocodingResult" id="geocodingresultsDestination" style="width:350px;">'+result+'</select>';
else
document.getElementById("geocodingresultsDestination").innerHTML = result;
//Enable and disable buttons
document.getElementById("print").disabled = true;
document.getElementById("geocodingresultsStart").style.visibility = "visible";
document.getElementById("geocodingresultsDestination").style.visibility = "visible";
document.getElementById("geocodingResults").style.visibility = "visible";
document.getElementById("button_calculate_route").style.visibility = "visible";
document.getElementById("button_calculate_route").disabled = false;
}
}
//This function is called after the user has pressed the "Show Route" button.
//It accesses the selected start and destination from the list boxes and
//initiates the route calculation.
function setRoutePoints(){
//Get the index of the selected start and destination
var start = document.forms["start"]["geocodingresultsStart"].selectedIndex;
var dest = document.forms["dest"]["geocodingresultsDestination"].selectedIndex;
//Store the selected route points in the routePoints array
routePoints["start"] = startPointAlternatives[start];
routePoints["destination"] = destinationPointAlternatives[dest];
//Start route calculation
calculateRoute();
document.getElementById("button_show_list").disabled = true;
}
//Calculate the route.
function calculateRoute() {
//Create a routing service stub
if( router == null ) router = new Map24.RoutingServiceStub();
//Calculate the route.
router.calculateRoute({
Start: routePoints["start"],
Destination: routePoints["destination"],
CallbackFunction: displayRoute,
//The ShowRoute parameter is set to false, the route is not shown automatically.
//This is necessary if you want to change the default color used for showing the route.
//To show the route call the Map24.RoutingServiceStub.showRoute() function in the callback function.
ShowRoute: false
});
document.getElementById("print").disabled = true;
document.getElementById("button_calculate_route").disabled = true;
}
//Callback function used to access the calculated route of type Map24.WebServices.Route.
//This function shows the route on the map, adds locations at the position of the start and
//destination points to the map, prints a detailed route description, and provides
//a button next to each entry in the route description that allows to center on a route segment.
function displayRoute( route ){
//Remember the routeId. It is used e.g. to hide the route.
routeID = route.RouteID;
//Show the route with blue color and transparency.
//The transparency can be set to a value between 0 (completely transparent) and 255 (opaque).
router.showRoute( {
RouteId: routeID,
Color: ['#00F', 150]
});
//Add a location at the position of the route's start point.
startLoc = new Map24.Location({
Longitude: routePoints["start"].getLongitude(),
Latitude: routePoints["start"].getLatitude(),
Description: "Start Point",
SymbolId: 20950
});
startLoc.commit();
//Add a location at the position of the route's destination point.
destLoc = new Map24.Location({
Longitude: routePoints["destination"].getLongitude(),
Latitude: routePoints["destination"].getLatitude(),
Description: "Destination Point",
SymbolId: 20958
});
destLoc.commit();
//Access the assumed time needed for traversing the route in hours
var totalTime = ((route.TotalTime)/(60*60) ).toPrecision(3)
//Access the total lenght of the route in kilometers
var totalLength = (route.TotalLength/1000)
//Create table with description of the route
var div_content = "Total Time: " + totalTime + " h<br>" ;
div_content += "Total Length: "+ totalLength +" km<br>";
div_content += "<br>";
//Iterate through the route segments and output the step-by-step textual description of the route
for(var i = 0; i < route.Segments.length; i++){
if( typeof route.Segments[i].Coordinates != "undefined" ) {
//Access the longitudes and latitudes of the route segment's coordinates array
var longitudes = route.Segments[i].Coordinates.Longitudes.toString().split("|");
var latitudes = route.Segments[i].Coordinates.Latitudes.toString().split("|");
//Get the longitude and latitude in the center of the route segment.
//These values are needed for centering on a route segment.
var centerLon = longitudes[parseInt(longitudes.length / 2)];
var centerLat = latitudes[parseInt(latitudes.length / 2)];
}
//For each route segment add the route description and the button for centering on the segment
for(var j = 0; j < route.Segments[i].Descriptions.length; j++){
//The route description contains tags for further evaluation. For example, the [M24_STREET] tag is used
//to denote a street in the description. Add the following line of code to replace these tags by a blank:
div_content += (i+1) + ". " + route.Segments[i].Descriptions[j].Text.replace(/(\[|\[\/)[0-9A-Z_]+\]/g, '' )
+ "<img src=\"/images/ms/centerabove_std.gif\" alt=\"Center\" onclick=\"centerOnSegment("+centerLon+", "+centerLat+");\"/><br>"
}
}
document.getElementById('routeDescription').innerHTML = div_content;
document.getElementById("button_hide_route").disabled = false;
document.getElementById("button_remove_route").disabled = false;
document.getElementById("print").disabled = false;
}
//This function is called after the user has selected a route segment to center on.
function centerOnSegment (centerLon, centerLat){
//Center on the given variable
Map24.MapApplication.center( { Coordinate:new Map24.Coordinate(centerLon, centerLat), MinimumWidth: 3034 } );
}
function showRoute() {
//Show the route.
router.showRoute( {RouteId: routeID} );
startLoc.show();
destLoc.show();
document.getElementById("button_show_route").disabled = true;
document.getElementById("button_hide_route").disabled = false;
document.getElementById("button_remove_route").disabled = false;
}
function hideRoute() {
//Hide the route.
router.hideRoute( {RouteId: routeID} );
startLoc.hide();
destLoc.hide();
document.getElementById("button_show_route").disabled = false;
document.getElementById("button_hide_route").disabled = true;
document.getElementById("button_remove_route").disabled = true;
}
//Removes a route. After the route is removed, a new route can be calculated.
function removeRoute(routeID) {
//Remove route
router.removeRoute({RouteId: routeID});
//Remove locations that show start and destination of the route
startLoc.remove();
destLoc.remove();
//Delete route description
document.getElementById("routeDescription").innerHTML = "";
//Reset buttons
document.getElementById("button_show_route").disabled = true;
document.getElementById("button_hide_route").disabled = true;
document.getElementById("button_remove_route").disabled = true;
document.getElementById("button_calculate_route").style.visibility = "visible";
document.getElementById("button_calculate_route").disabled = false;
document.getElementById("button_show_list").style.visibility = "visible";
document.getElementById("button_show_list").disabled = false;
document.getElementById("print").disabled = true;
}
//Print Description function.
//The function opens a print preview window of the route description and one can choose the printer.
function printRouteDescription(){
var printContent = document.getElementById("routeDescription");
var windowPrint = window.open('','','left=0,top=0,width=0,height=0,toolbar=0,scrollbars=0,status=0');
windowPrint.document.write(printContent.innerHTML);
windowPrint.document.close();
windowPrint.focus();
windowPrint.print();
windowPrint.close();
}
//Helper function for accessing the div specified in the id parameter.
//The function checks first if the div contains content.
function $v( id ) {
return (document.getElementById( id ).value != "undefined") ?
document.getElementById( id ).value : "";
}
</script>
</head>
<body onload="goMap24();">
<div id="maparea" style="width:700px;height:500px;background-color:#E0E0E0;"></div>
<br />
<div style="width:700px;border-width:0px;border-style:solid">
<input type="button" id="button_show_route" value="Show Route" onclick="showRoute( routeID )" disabled="disabled" />
<input type="button" id="button_hide_route" value="Hide Route" onclick="hideRoute( routeID )" disabled="disabled" />
<input type="button" id="button_remove_route" value="Remove Route" onclick="removeRoute( routeID )" disabled="disabled" />
<input type="button" id="print" value="Print Description" onClick="printRouteDescription()" disabled="disabled" />
<input type="button" id="reload" value="Refresh" onClick="history.go(0)" />
<br />
<br />
<div style="width:410px;border-width:0px;border-style:solid">
<table id="selection" class="selection" cellpadding="1" cellspacing="1">
<tbody>
<tr>
<td width="276px">Start:</td>
<td width="424px"><input type='text' id='start' style="width:350px;" value='Frankfurt' /></td>
</tr>
<tr>
<td width="276px">Destination:</td>
<td width="424px"><input type='text' id='destination' style="width:350px;" value='Muenster' /></td>
<td></td><td><input type="button" id="button_show_list" value="Route" onclick="startRouting()" /></td>
</tr>
</tbody>
</table>
</div>
<div id="geocodingResults" style="width:440px;border-width:0px;border-style:solid">
<table cellpadding="1" cellspacing="1">
<tbody>
<br />
Choose from Geocoded Results:
<tr><br />
<td width="276px">Start:</td>
<form name="start">
<td width="424px">
<select name="printGeocodingResult" id="geocodingresultsStart" style="width:350px;">
</td>
</select>
</form>
</tr>
<td width="300px">Destination:</td>
<form name="dest">
<td width="424px"><select name="printGeocodingResult" id="geocodingresultsDestination" style="width:350px;"></td>
<td></td><td><input type="button" id="button_calculate_route" value="Show Route" onclick="setRoutePoints()" />
</td>
</select>
</form>
</td>
</tr>
</table>
</div>
<br />
<div id="routeID"></div>
<div id="result" style="text-align:left;width:700px;"> </div><br />
<div id="routeDescription" style="text-align:left;width:700px;"></div>
</body>
</html>
|
|