How to add polyline to a marker array?

I am totally new to Leaflet and i'm trying to add a polyline between markers from a database. I am using jQuery to add the markers from an ajax response (which works fine). I have read the documentation and I can't figure out how to add the polyline. This is what I have tried:

Snippet of my jQuery

    .success(function(response) {
        if(!response.errors && response.result) {
            $.each(response.result, function( index, value) {
                markerArray.push(L.marker([value[7], value[8]], {icon: greenIcon}));                
             var group = L.featureGroup(markerArray).addTo(map);
             var polyline = L.polyline(markerArray, {color: 'red'}).addTo(map); 

        } else {
            $.each(response.errors, function( index, value) {
                // add error classes
                $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')

Answers 1

  • You have to use a LatLng array in your polyline constructor (here you are using L.Marker array)

    I would suggest:

       $.each(response.result, function( index, value) {
           var latlng = L.latLng(value[7], value[8]);
           markerArray.push(L.marker(latlng, {icon: greenIcon})); 
       var group = L.featureGroup(markerArray).addTo(map);
       var polyline = L.polyline(latlngArray, {color: 'red'}).addTo(map); 

Related Articles