Web Maps Lite API Examples

Polylines and Polygons

Now for some vector stuff

Javascript Level: Beginner

You can display simple vector data like polylines and polygons over the map in Web Maps Lite. This often comes in handy when you want to outline a particular area or a route on the map. In this example we see how to outline the President's Park South in Washington with a polygon:

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(38.89384, -77.03635), 16);
	
var polygon = new CM.Polygon([
	new CM.LatLng(38.8953, -77.0394),
	new CM.LatLng(38.89546, -77.0337),
	new CM.LatLng(38.8922, -77.0337),
	new CM.LatLng(38.8922, -77.0393)
]);
map.addOverlay(polygon);

It's that simple! But lets see in detail what's going on here:

1. We set up a new CloudMade map as usual, pointing at the President's Park South:

var cloudmade = new CM.Tiles.CloudMade.Web({key: 'BC9A493B41014CAABB98F0471D759707'});
var map = new CM.Map('cm-example', cloudmade);
map.setCenter(new CM.LatLng(38.89384, -77.03635), 16);

2. Next we create a new Polygon object with the LatLng points it will go through:

var polygon = new CM.Polygon([
	new CM.LatLng(38.8953, -77.0394),
	new CM.LatLng(38.89546, -77.0337),
	new CM.LatLng(38.8922, -77.0337),
	new CM.LatLng(38.8922, -77.0393)
]);

(If you wanted polylines, you could just use CM.Polyline in place of CM.Polygo the same way.)

3. Finally we add it as an overlay to the map:

map.addOverlay(polygon);

Now we have the park outlined with a nice blue polygon. You can find out more about polylines and polygons by checking out the Polygon and Polyline sections of our documentation. Now lets dive into a really exciting example - Routing.