Sergey
Sergey

Reputation: 7682

Leaflet multi-color polyline

Is there an option in Leaflet to make ONE polyline with different path colors?

In google you can use path object with color property, however I haven't found similar option in Leaflet.

Upvotes: 2

Views: 2470

Answers (1)

Falke Design
Falke Design

Reputation: 11348

There a few libraries like https://github.com/Oliv/leaflet-polycolor But you don't need a library for this.

You have your "main" polyline and from this you generate new lines segments.

   var poly = L.polyline([
       [51.509, -0.08],
       [51.503, -0.06],
       [51.51, -0.047],
       [51.51, -0.06],
   ]);
//.addTo(map); Don't add the main line to the map

 setPolylineColors(poly,['#f00','#ff0','#000'])


 function setPolylineColors(line,colors){

   var latlngs = line.getLatLngs();

   latlngs.forEach(function(latlng, idx){
           if(idx+1 < latlngs.length ){
           var poly =  L.polyline([latlng,latlngs[idx+1]],{color: colors[idx]}).addTo(map);
        }
   })
 }

Example: https://jsfiddle.net/falkedesign/2b8t3v6f/

Upvotes: 2

Related Questions