Leaflet Lines

by abenrob

HTML

<script src="http://cdn.leafletjs.com/leaflet-0.4.5/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.4.5/leaflet.css">
<div id="mymap" style="width:600px;height:430px;"></div>

CSS

html, body{ width:100%; height: 100%, margin:0; padding:0; }
#mymap{ width:100%; height:100%; }

JavaScript

// create a map
mapoptions = {
    zoomControl: false,
    dragging: false,
    scrollWheelZoom: false,
    doubleClickZoom: false,
    boxZoom: false,
    keyboard: false
}
map = new L.Map('mymap', mapoptions);

// create the Esri Gray layer
var grayMapUrl = 'http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}';
var grayMapLayer = new L.TileLayer(grayMapUrl, { maxZoom: 19, attribution: 'Tiles: &copy; Esri' });
map.addLayer(grayMapLayer);
// set the map's starting view
var center = [44.12308489306967, -120.684814453125];

map.setView( new L.LatLng(center[0], center[1]), 6 );

var lines = [
    {
        name: "A line",
        coords: [
            [44.941473,-123.037537], //Salem
            [45.529441,-122.674988] // Portland
        ],
        info:"Salem to Portland",
        style: {color: 'green', weight: 2, dashArray: '4,8'}
    },
    {
        name: "Another line",
        coords: [
            [44.941473,-123.037537], //Salem
            [44.063907,-121.323669] //Bend
        ],
        info: "Salem to Bend",
        style: {color: 'red', weight: 2}
    } 
];

var grp = [];

for(i=0;i<lines.length;i=i+1){
    // inside of this loop - runs for each line
    var latlngs = [ ];
    for(j=0;j<=lines[i].coords.length-1;j=j+1){
        //inside of this loop, convert coords to L.LatLng
        //runs for each point in each line
        latlngs.push( new L.LatLng(lines[i].coords[j][0], lines[i].coords[j][1]) );
    }
    // create lines from points
    polyLine = new L.Polyline(latlngs, lines[i].style);
    grp.push(polyLine);
}

newGroup = L.featureGroup(grp)
newGroup.addTo(map);
var newBounds = newGroup.getBounds();
var nbZoom = map.getBoundsZoom(newBounds);
var newCenter = newBounds.getCenter();
map.setView(newCenter, nbZoom-1,true);


// create a special icon
baseIcon = L.icon( {
    iconUrl: "http://goo.gl/zisZS",
    iconSize: [16, 16],
    shadowSize: [21,16],
    iconAnchor: [8, 8],
   ...