'Removing Polyline in cesium js

How to remove a polyline in cesiumjs,

var p = this.viewer.entities.add({
    polyline: {
        material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.7,
            color: Cesium.Color.ORANGE.withAlpha(0.7)
        }),
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(points),
        width: 15,
    }
});

I used entities.removeAll(), but it is deleting entire data from the cesium conatiner(including models,etc). I want to delete only Polyline.



Solution 1:[1]

Save the return value from entities.add, this is a reference to the newly created entity.

var polylineEntity = viewer.entities.add({
    //...
});

Later, you can remove a specific entity by reference.

viewer.entities.remove(polylineEntity);

Solution 2:[2]

var pathDone; //Store dataSource so later can be removed.
viewer.dataSources.remove(pathDone,true); // Removing old data.

Cesium.GeoJsonDataSource.load(data, { // Data contains geojson, linestring z.
    stroke: Cesium.Color.HOTPINK,
    fill: Cesium.Color.PINK.withAlpha(0.5),
    strokeWidth: 2
}).then(function(geoData){
     viewer.dataSources.add(geoData); //Adding new one.
     pathDone=geoData;//Storing new reference.
});

This worked for me.

Solution 3:[3]

you can also remove entity by giving entity an id. check cesium api doc here. https://cesium.com/learn/cesiumjs/ref-doc/EntityCollection.html?classFilter=entity#id

var p = this.viewer.entities.add({
    id: "polylinId", // this is where you should add. give entity an id you can use.
    polyline: {
        material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.7,
            color: Cesium.Color.ORANGE.withAlpha(0.7)
        }),
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(points),
        width: 15,
    }
});

// then remove entity by id you've given
viewer.entity.removeById("polylinId")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 emackey
Solution 2 sharmag
Solution 3 sozerodev