Web Maps Lite API Examples

Routing

Driving around

Javascript Level: Beginner

One of the best uses for map data is getting driving/walking/cycling instructions. In this example we see how to use the CloudMade Routing service in Web Maps Lite:

Here's the JavaScript for the example:

var map = new CM.Map('cm-example', 
	new CM.Tiles.CloudMade.Web({key: 'BC9A493B41014CAABB98F0471D759707'}));
map.setCenter(new CM.LatLng(51.52119, -0.14184), 15);
		
var directions = new CM.Directions(map, 'panel', 'BC9A493B41014CAABB98F0471D759707');

var waypoints = [new CM.LatLng(51.52039, -0.1485), new CM.LatLng(51.5203, -0.135)];
directions.loadFromWaypoints(waypoints);

Lets see what's going on here:

1. We set up a new CloudMade map:

var map = new CM.Map('cm-example', 
	new CM.Tiles.CloudMade.Web({key: 'BC9A493B41014CAABB98F0471D759707'}));
map.setCenter(new CM.LatLng(51.52119, -0.14184), 15);

2. Next we create a Directions object, passing it our map, an id of the div element we want to put routing instructions in, and our API key once again:

var directions = new CM.Directions(map, 'panel', 'BC9A493B41014CAABB98F0471D759707');

3. Finally we create an array of LatLng objects our route will go through and pass it to the directions.loadFromWaypoints method:

var waypoints = [new CM.LatLng(51.52039, -0.1485), new CM.LatLng(51.5203, -0.135)];
directions.loadFromWaypoints(waypoints);

Thats it! We have pretty driving instructions displayed on your page. You can find out more about routing by checking out the CM.Directions section of our documentation. Now lets see the next example - geocoding.