Search code examples
leafletturfjs

Leaflet plus turf.js - color of line before & after point


I have a basic leaflet plus turf.js polyline - i'd like to be able to style the line before and after a given point. So for example - from the start to the point marker (along) (color : red). Basically, showing the portion of the route(line) that has been completed.

        //path coords
        var coords = [
                [-3.535,55.62],
                [-3.54,55.61],
                [-3.547,55.6],
                [-3.55,55.59],
                [-3.57,55.58]
                ];

        var features = turf.points(coords );
        var center = turf.center(features);

        var map = L.map('map');  
    
        L.tileLayer(
            'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://openstreetmap.org" target=blank>OpenStreetMap</a> Contributors',
            maxZoom: 18,
        }).addTo(map);
          

        var line = turf.lineString(coords);     
        var options = {units: 'miles'}; 


        L.geoJSON(line).addTo(map);
        
        var along = turf.along(line, 1.25, options);
            L.geoJSON(along).addTo(map).bindTooltip("my tooltip text");

            // get center x/y
            var features = turf.points(coords);
            var center = turf.center(features);
            var centroid_xy = center.geometry.coordinates;
            var x = centroid_xy[0];
            var y = centroid_xy[1];

            
            // get bounds 
                var bbox = turf.bbox(line);
                var b0 = bbox[0];
                var b1 = bbox[1];
                var b2 = bbox[2];
                var b3 = bbox[3];                           


            L.marker([55.62, -3.535]).bindPopup("Test marker").addTo(map);
                var mapMarker2 = L.icon({
                iconSize:     [16, 16],
                iconAnchor:   [8, 8],
            });

                                            
            map.setView([y, x], 13);
            map.fitBounds([[b1, b0],[b3, b2]]);

Solution

  • You can use your along point to split the line with TurfJS:

    split = turf.lineSplit(line, along)

    This gives you a FeatureCollection of 2 features, which you can use to show the two segments on the map.

    https://observablehq.com/d/f379582399e8089d