Search code examples
cesiumjs

How to set width to SimplePolylineGeometry primitive in CesiumJS


I have this code, which adds polyline primitive to scene.

function createPolyline(startPosition, endPosition) {
        Cesium.SimplePolylineGeometry({
            positions : [startPosition, endPosition]
        });

        var geometry = Cesium.SimplePolylineGeometry.createGeometry(polyline);
        return scene.primitives.add(new Cesium.Primitive({
            geometryInstances : new Cesium.GeometryInstance({
                geometry   : geometry,
                attributes : {
                    color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.SPRINGGREEN)
                }
            }),
            appearance        : new Cesium.PerInstanceColorAppearance()
        }));
    }

How do I set width of this polyline?


Solution

  • The recommended way to add a polyline is with the Entity API, like this

    var greenLine = viewer.entities.add({
        polyline : {
            positions : [startPosition, endPosition],
            width : 5,
            material : Cesium.Color.SPRINGGREEN
        }
    });
    

    But, if you want to skip the Entity layer and use the Primitive Graphics layer directly, you can do that too. Your sample code above has some issues. First, you're calling the Cesium.SimplePolylineGeometry constructor without the new keyword, and without saving the result, and this is not the correct use pattern for this kind of code. Second, the SimplePolylineGeometry class itself does not support line widths greater than what the WebGL implementation supports, which on Windows machines running ANGLE, is only 1 pixel wide. To get around this limitation, use the normal (non-simple) polylines, like this:

    var polylines = scene.primitives.add(new Cesium.PolylineCollection());
    var polyline = polylines.add({
        positions : Cesium.PolylinePipeline.generateCartesianArc({
            positions : [startPosition, endPosition]
        }),
        material : Cesium.Material.fromType('Color', {
            color : Cesium.Color.SPRINGGREEN
        }),
        width: 5
    });