[GIS] Add custom variables to leaflet polyline

leafletline

I'm drawing a route on a map with leaflet. I'd like to click on any point in the line and display the speed and time at that point in a popup ($speed[$i]).

latlngs = [<?php for ($i=0;$i<count($latts);$i++){echo '['. $latts[$i] .', '. $longs[$i]     .']';if($i!=count($latts)-1){echo ',';}} ?>],
itinerary = L.polyline(latlngs, {color: 'red'});
itinerary.addEventListener('click dblclick', function(e) {
    console.log(e);
    var res = e.latlng; // that's nice but I'd like to be able to get e.speed, etc...
});
map.addLayer(itinerary);

EDIT: I'm building the polyline with an array of Latitudes and Longitudes. I've got a Speed array of the same length. When the user clicks on a point on the line, I'd like to get the closest recorded Latitude and Longitude, and display the corresponding speed for that point (in a popup or in an other div).
Eventually the user can slide his mouse along the line and see the speed .

Best Answer

building from this answer, you can extend L.Polyline to include any number of variables as options

customPolyline = L.Polyline.extend({
    options: {
        // default values, you can override these when constructing a new customPolyline
        speed: '25',
        bearing: '140'
    }
});

now create your polylines, and add to the map:

latlngs = [<?php for ($i=0;$i<count($latts);$i++){echo '['. $latts[$i] .', '. $longs[$i];  
var polyline = new customPolyline(latlngs,{
    color: 'red',  
    speed: '143',
    bearing: '38'
});

polyline.on('click', function() { 
    alert(this.options.speed) 
});

polyline.addTo(map);

See this fiddle for a complete example with polyline

UPDATE

Following up on your comment, you can also attach custom data to L.markers, as shown below and in this fiddle:

customMarker = L.Marker.extend({
   options: { 
      speed: '111',
      bearing: '111'
   }
});

for (var i = 0, len = latlngs.length; i < len; i++) {
    var m = new customMarker(latlngs[i], {
        // get the actual speed for this lat-long
        // if speeds are in an array in the same exact order as the lat-longs
        // it could be as easy as speed: speed[i]
        speed: '123'
    });
    m.on('click', function() {
        alert(this.options.speed)
    })
    m.addTo(map);
}

var polyline = L.polyline(latlngs,{});
polyline.addTo(map);

I don't know how your speed data are associated with each point. But assuming you can get a javascript array or object of lat-longs and speeds, you just need to edit the marker loop, above, to add the speed to each marker when it is constructed.