Search code examples
leafletgeojson

leaftletjs-adding points dynamically and draw line string


I am trying to draw the path of a flight using leafletjs and geojson. I'll be getting the geometry from a stream. this is what I have done so far:

    let index = 0;
    let geoJsonLayer;
    let intervalFn = setInterval(function () {
        let point = trackData.features[index++];

        if(point) {

            let coords = point.geometry.coordinates;
            coords.pop();
            coords.reverse();

            geoFeature.geometry.coordinates.push(coords);
            if(map.hasLayer(geoJsonLayer)) map.removeLayer(geoJsonLayer);

            geoJsonLayer = L.geoJson(geoFeature, {
                onEachFeature: (feature, layer) => {
                    const content = feature.properties.title;
                    layer.bindPopup(content);
                }
            });
            geoJsonLayer.addTo(map);
            // console.log(coords);

        } else {
            clearInterval(intervalFn);
        }
    }, 100);

setInterval is to simulate the part whereby I get the geometry from a stream.

now when a user clicks on the path I need to show some properties of the path, and I am trying to use the onEachFeature for that, but its not working correctly. I suspect its because I am removing the layers (I did this to improve the performance)

Is there any other better ways to do what I am trying to achieve ?


Solution

  • You should probably try addLatLng()

    Adds a given point to the polyline.

    Your geoFeature sounds to be a single Feature, so your geoJsonLayer will contain a single layer (polyline):

    let myPolyline;
    
    geoJsonLayer.eachLayer(function (layer) {
        myPolyline = layer; // Will be done only once actually.
    });
    
    // When you receive a new point…
    myPolyline.addLatLng([lat, lng]);
    

    With this you should not have to remove your layers every time.

    The popup should therefore stay open, if it is shown.

    Demo: https://jsfiddle.net/3v7hd2vx/265/ (click on the button to add new points)