Search code examples
javascriptleafletopenstreetmappolyline

OSM polyline with markers


I have some custom polyline on OSM with this code

var polyline1 = [
        [44.772142, 17.208980],
        [44.774753, 17.207644],
        [44.773964, 17.199587],
        [44.770823, 17.199207],
        [44.771399, 17.195699],
    ];

    for (var i = 0; i < polyline1.length; i++) {
                var polyline = L.polyline(polyline1, {
                    color: 'red'
                }).addTo(map);;
            }

I need markers with popup on all this coordinates, this code cannot work with other:

for (var i = 0; i < polyline1.length; i++) {
                var marker = L.marker([polyline1[i][1],polyline1[i][2]])
                .bindPopup(polyline1[i][0])
                .addTo(map);
            }

Is there any solution for this?


Solution

  • It's much simpler than you're making it.

    // Define some custom icons
    
    var icon1 = L.icon(...);
    var icon2 = L.icon(...);
    var icon3 = L.icon(...);
    var icon4 = L.icon(...);
    var icon5 = L.icon(...);
    
    
    var icons = [ icon1, icon2, icon3, icon4, icon5];
    
    
    // Define the points
    
    var polyline1 = [
            [44.772142, 17.208980],
            [44.774753, 17.207644],
            [44.773964, 17.199587],
            [44.770823, 17.199207],
            [44.771399, 17.195699],
        ];
    
    // Add a marker at each point
    
    polyline1.forEach(function(LatLng, i) {
        L.marker(LatLng, {icon: icons[i]}).addTo(map);
    });
    
    // Add a polyline
    
    L.polyline(polyline1, { color: 'red' }).addTo(map);