Adding Dimension: Lines, Shapes, and Video
Point
You've already learned to create LatLngs, which you then made into clickable markers, including some with custom icons: http://p2pu.org/en/groups/online-maps-with-leaflet/content/clickable-icons-in-leafletjs/
The LatLng is also the basis for Leaflet's lines and shapes (technically called Polylines and Polygons). This lesson will explain creating and styling these objects.
Line
Leaflet's official class name for a line is L.Polyline: http://leaflet.cloudmade.com/reference.html#polyline
The first section on that page, a constructor, explains that to create an L.Polyline, you need to send it an array (a list) of L.LatLngs. There are multiple ways to do this:
- An easy way to set up a list is to create each point, then surround them with square brackets:
pointA = new L.LatLng( 0, 4 );
pointB = new L.LatLng( 10, 10 );
pointList = [ pointA, pointB ];
line = new L.Polyline( pointList, { color: "purple" } );
map.addLayer(line);
- Someone with prior programming experience might use a for loop
// array of [ lat, lng ] arrays
var linePts = [
[ 31.811628, 24.904771 ],
[ 31.810856, 24.91096 ],
[ 31.817636, 24.911855 ],
[ 31.831133, 24.907477 ],
[ 31.841497, 24.898679 ],
[ 31.841025, 24.895312 ],
[ 31.837935, 24.891225 ],
[ 31.842356, 24.889006 ],
[ 31.853814, 24.888626 ]
];
// a FOR loop operates on each item in a list
for( i=0; i < linePts.length; i=i+1 ) {
// turn this coordinate into a LatLng
linePts[ i ] = new L.LatLng( linePts[ i ][ 0 ], linePts[ i ][ 1 ] );
}
Then we create the actual line, and add it to the map with some options.
line = new L.Polyline( linePts, { color: "purple" } );
map.addLayer(line);
Try this out here: http://jsfiddle.net/8QHFe/153/
Shape
Lines simply aren't enough. To highlight buildings, properties, districts and any other area, you advance. Leaflet officially calls these Polygons, but if it's been awhile since you were in geometry class, you probably think of them as shapes: http://leaflet.cloudmade.com/reference.html#polygon
For my example, I decided to outline some buildings in Boston, and play a related video when someone clicks on them:
This is some useful code if you were looking to add YouTube to your maps ( or open video ).
http://jsfiddle.net/8QHFe/154/
If you have a donut hole ( like a map with Vatican City within Italy ), you can send multiple arrays as another array: italy = new L.Polygon( [ italyborders, vaticanborders ] , { color: "red" });
http://jsfiddle.net/8QHFe/154/
If you have a donut hole ( like a map with Vatican City within Italy ), you can send multiple arrays as another array: italy = new L.Polygon( [ italyborders, vaticanborders ] , { color: "red" });