Cesium JS API
AppearanceArcGisMapServerImageryProviderArcGISTiledElevationTerrainProviderArcTypeAssociativeArrayAxisAxisAlignedBoundingBoxbarycentricCoordinatesBillboardBillboardCollectionBillboardGraphicsBillboardVisualizerbinarySearchbinarySearchComparatorBingMapsGeocoderServiceBingMapsImageryProviderBingMapsStyleBlendEquationBlendFunctionBlendingStateBlendOptionBoundingRectangleBoundingSphereBoxEmitterBoxGeometryBoxGeometryUpdaterBoxGraphicsBoxOutlineGeometrybuildModuleUrlCallbackPropertyCameraCameraEventAggregatorCameraEventTypeCartesian2Cartesian3Cartesian4CartographicCartographicGeocoderServiceCatmullRomSplineCesium3DTileCesium3DTileColorBlendModeCesium3DTileContentCesium3DTileFeatureCesium3DTilePointFeatureCesium3DTilesetCesium3DTilesetGraphicsCesium3DTilesetVisualizerCesium3DTileStyleCesium3DTilesVoxelProviderCesiumTerrainProviderCesiumWidgetCheckerboardMaterialPropertyCircleEmitterCircleGeometryCircleOutlineGeometryClassificationPrimitiveClassificationTypeClippingPlaneClippingPlaneCollectionClockClockRangeClockStepcloneCloudCollectionCloudTypeColorColorBlendModeColorGeometryInstanceAttributeColorMaterialPropertycombineComponentDatatypeCompositeEntityCollectionCompositeMaterialPropertyCompositePositionPropertyCompositePropertyCompressedTextureBufferConditionsExpressionConeEmitterConstantPositionPropertyConstantPropertyConstantSplineContextOptionsCoplanarPolygonGeometryCoplanarPolygonOutlineGeometryCornerTypeCorridorGeometryCorridorGeometryUpdaterCorridorGraphicsCorridorOutlineGeometrycreateElevationBandMaterialcreateElevationBandMaterialBandcreateElevationBandMaterialEntrycreateGuidcreateOsmBuildingscreateTangentSpaceDebugPrimitivecreateWorldImagerycreateWorldTerrainCreditCreditDisplayCubicRealPolynomialCullFaceCullingVolumeCumulusCloudCustomDataSourceCustomHeightmapTerrainProviderCustomShaderCustomShaderModeCustomShaderTranslucencyModeCylinderGeometryCylinderGeometryUpdaterCylinderGraphicsCylinderOutlineGeometryCzmlDataSourceDataSourceDataSourceClockDataSourceCollectionDataSourceDisplayDebugAppearanceDebugCameraPrimitiveDebugModelMatrixPrimitiveDefaultProxydefaultValuedefinedDepthFunctiondestroyObjectDeveloperErrorDirectionalLightDirectionUpDiscardEmptyTileImagePolicyDiscardMissingTileImagePolicyDistanceDisplayConditionDistanceDisplayConditionGeometryInstanceAttributeEasingFunctionEllipseGeometryEllipseGeometryUpdaterEllipseGraphicsEllipseOutlineGeometryEllipsoidEllipsoidGeodesicEllipsoidGeometryEllipsoidGeometryUpdaterEllipsoidGraphicsEllipsoidOutlineGeometryEllipsoidRhumbLineEllipsoidSurfaceAppearanceEllipsoidTangentPlaneEllipsoidTerrainProviderEntityEntityClusterEntityCollectionEntityViewEventEventHelperexcludesReverseAxisexportKmlexportKmlModelCallbackexportKmlResultKmlexportKmlResultKmzExpressionExtrapolationTypeFeatureDetectionFogformatErrorFrameRateMonitorFrustumGeometryFrustumOutlineGeometryFullscreenGeocoderServiceGeocodeTypeGeographicProjectionGeographicTilingSchemeGeoJsonDataSourceGeometryGeometryAttributeGeometryAttributesGeometryFactoryGeometryInstanceGeometryInstanceAttributeGeometryPipelineGeometryUpdaterGeometryVisualizergetAbsoluteUrigetBaseUrigetExtensionFromUriGetFeatureInfoFormatgetFilenameFromUrigetImagePixelsgetTimestampGlobeGlobeTranslucencyGoogleEarthEnterpriseImageryProviderGoogleEarthEnterpriseMapsProviderGoogleEarthEnterpriseMetadataGoogleEarthEnterpriseTerrainDataGoogleEarthEnterpriseTerrainProviderGpxDataSourceGregorianDateGridImageryProviderGridMaterialPropertyGroundGeometryUpdaterGroundPolylineGeometryGroundPolylinePrimitiveGroundPrimitiveHeadingPitchRangeHeadingPitchRollHeadingPitchRollValuesHeightmapEncodingHeightmapTerrainDataHeightReferenceHermitePolynomialApproximationHermiteSplineHilbertOrderHorizontalOriginI3SDataProviderI3SFeatureI3SFieldI3SGeometryI3SLayerI3SNodeImageBasedLightingImageMaterialPropertyImageryLayerImageryLayerCollectionImageryLayerFeatureInfoImageryProviderImageryTypesincludesReverseAxisIndexDatatypeIntersectIntersections2DIntersectionTestsIntervalIonIonGeocoderServiceIonImageryProviderIonResourceIonWorldImageryStyleisLeapYearIso8601JulianDateKeyboardEventModifierKmlCameraKmlDataSourceKmlFeatureDataKmlLookAtKmlTourKmlTourFlyToKmlTourWaitLabelLabelCollectionLabelGraphicsLabelStyleLabelVisualizerLagrangePolynomialApproximationLeapSecondLightLightingModelLinearApproximationLinearSplineMapboxImageryProviderMapboxStyleImageryProviderMapMode2DMapProjectionMaterialMaterialAppearanceMaterialSupportMaterialPropertyMathMatrix2Matrix3Matrix4mergeSortmergeSortComparatorMetadataClassMetadataClassPropertyMetadataComponentTypeMetadataEnumMetadataEnumValueMetadataSchemaMetadataTypeModelModelAnimationModelAnimationCollectionModelAnimationLoopModelFeatureModelGraphicsModelNodeModelVisualizerMoonMorphWeightSplineNearFarScalarNeverTileDiscardPolicyNodeTransformationPropertyobjectToQueryOccluderOpenCageGeocoderServiceOpenStreetMapImageryProviderOrientedBoundingBoxOrthographicFrustumOrthographicOffCenterFrustumPackableForInterpolationParticleParticleBurstParticleEmitterParticleSystemPathGraphicsPathVisualizerPeliasGeocoderServicePerInstanceColorAppearancePerspectiveFrustumPerspectiveOffCenterFrustumPinBuilderPixelDatatypePixelFormatPlanePlaneGeometryPlaneGeometryUpdaterPlaneGraphicsPlaneOutlineGeometryPointCloudShadingPointGraphicspointInsideTrianglePointPrimitivePointPrimitiveCollectionPointVisualizerPolygonGeometryPolygonGeometryUpdaterPolygonGraphicsPolygonHierarchyPolygonOutlineGeometryPolylinePolylineArrowMaterialPropertyPolylineCollectionPolylineColorAppearancePolylineDashMaterialPropertyPolylineGeometryPolylineGeometryUpdaterPolylineGlowMaterialPropertyPolylineGraphicsPolylineMaterialAppearancePolylineOutlineMaterialPropertyPolylineVisualizerPolylineVolumeGeometryPolylineVolumeGeometryUpdaterPolylineVolumeGraphicsPolylineVolumeOutlineGeometryPositionPropertyPositionPropertyArrayPostProcessStagePostProcessStageCollectionPostProcessStageCompositePostProcessStageLibraryPostProcessStageSampleModePrimitivePrimitiveCollectionPrimitiveTypePropertyPropertyArrayPropertyBagProxyQuadraticRealPolynomialQuantizedMeshTerrainDataQuarticRealPolynomialQuaternionQuaternionSplinequeryToObjectQueueRayreadyPromiseRectangleRectangleGeometryRectangleGeometryUpdaterRectangleGraphicsRectangleOutlineGeometryReferenceFrameReferencePropertyremoveExtensionRequestRequestErrorEventRequestSchedulerRequestStateRequestTypeResourceRuntimeErrorSampledPositionPropertySampledPropertysampleTerrainsampleTerrainMostDetailedSceneSceneModeSceneTransformsScreenSpaceCameraControllerScreenSpaceEventHandlerScreenSpaceEventTypeshaderDefinesshaderMaximumIntersectionsLengthshaderUniformsShadowMapShadowModeShowGeometryInstanceAttributeSimon1994PlanetaryPositionsSimplePolylineGeometrySingleTileImageryProviderSkyAtmosphereSkyBoxSphereEmitterSphereGeometrySphereOutlineGeometrySphericalSplineSplitDirectionStencilFunctionStencilOperationSteppedSplineStripeMaterialPropertyStripeOrientationStyleExpressionsubdivideArraySunSunLightTaskProcessorTerrainDataTerrainProviderTextureMagnificationFilterTextureMinificationFilterTextureUniformTileAvailabilityTileCoordinatesImageryProviderTileDiscardPolicyTileMapServiceImageryProviderTileProviderErrorTilingSchemeTimeDynamicImageryTimeDynamicPointCloudTimeIntervalTimeIntervalCollectionTimeIntervalCollectionPositionPropertyTimeIntervalCollectionPropertyTimeStandardTransformsTranslationRotationScaleTridiagonalSystemSolverTrustedServersUniformSpecifierUniformTypeUrlTemplateImageryProviderVaryingTypeVelocityOrientationPropertyVelocityVectorPropertyVertexFormatVerticalOriginVideoSynchronizerViewportQuadVisibilityVisualizerVoxelPrimitiveVoxelProviderVoxelShapeTypeVRTheWorldTerrainProviderWallGeometryWallGeometryUpdaterWallGraphicsWallOutlineGeometryWebGLConstantsWebGLOptionsWebMapServiceImageryProviderWebMapTileServiceImageryProviderWebMercatorProjectionWebMercatorTilingSchemeWindingOrderwriteTextToCanvasAnimationAnimationViewModelBaseLayerPickerBaseLayerPickerViewModelCesium3DTilesInspectorCesium3DTilesInspectorViewModelCesiumInspectorCesiumInspectorViewModelClockViewModelCommandcreateCommandFullscreenButtonFullscreenButtonViewModelGeocoderGeocoderViewModelHomeButtonHomeButtonViewModelInfoBoxInfoBoxViewModelNavigationHelpButtonNavigationHelpButtonViewModelPerformanceWatchdogPerformanceWatchdogViewModelProjectionPickerProjectionPickerViewModelProviderViewModelSceneModePickerSceneModePickerViewModelSelectionIndicatorSelectionIndicatorViewModelSvgPathBindingHandlerTimelineToggleButtonViewModelViewerviewerCesium3DTilesInspectorMixinviewerCesiumInspectorMixinviewerDragDropMixinviewerPerformanceWatchdogMixinviewerVoxelInspectorMixinVoxelInspectorVoxelInspectorViewModelVRButtonVRButtonViewModel

Polyline

PolylineCesium 中的一种图形实体,用于绘制直线段。它可以用于绘制任意形状的线段,支持添加线的颜色、宽度、折线连接等属性。在三维场景中,Polyline 可以用于表示航线、路线、地形轮廓等。

创建 Polyline

Cesium 中,创建 Polyline 非常简单,我们只需要指定线段的坐标、颜色、宽度等属性即可。

const viewer = new Cesium.Viewer('cesiumContainer');
const positions = [
  Cesium.Cartesian3.fromDegrees(116.1, 39.9),
  Cesium.Cartesian3.fromDegrees(116.2, 39.9),
  Cesium.Cartesian3.fromDegrees(116.2, 40),
];
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 3,
    material: Cesium.Color.RED,
  },
});

在以上代码中,我们首先创建了一个 viewer 实例,然后定义了一组 positions 数组,指定了线段的起点和终点位置。接着,我们通过 viewer.entities.add 方法创建了一个 Polyline 实例,并将其添加到了场景中。在 Polyline 实例的配置中,我们指定了线段的 positionswidthmaterial 属性,分别表示线段的位置、宽度和颜色。

Polyline 属性

Polyline 支持以下属性:

positions

  • 类型:Cartesian3[]
  • 默认值:无
  • 描述:线段的坐标数组,每一对相邻的 Cartesian3 对应线段的一个端点位置。此属性是 Polyline 必须的配置项,如果未指定,则会创建一个空的线段。
const positions = [
  Cesium.Cartesian3.fromDegrees(116.1, 39.9),
  Cesium.Cartesian3.fromDegrees(116.2, 39.9),
  Cesium.Cartesian3.fromDegrees(116.2, 40),
];
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 3,
    material: Cesium.Color.RED,
  },
});

width

  • 类型:Number
  • 默认值:1.0
  • 描述:线段的宽度,以像素为单位。
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 5,
    material: Cesium.Color.RED,
  },
});

material

  • 类型:MaterialProperty
  • 默认值:undefined
  • 描述:线段的颜色或纹理。支持的颜色格式为 Cesium.ColorCesium.ColorMaterialProperty,支持的纹理格式为 Image, Canvas, Video, Aperture, Checkerboard, Grid, Stripe, Wood, Brick, Leather, Marble, Stone, Water, Noise, Circle, Ellipse, Polygon, PolylineRectangle
const colorMaterial = new Cesium.ColorMaterialProperty(Cesium.Color.RED);
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 3,
    material: colorMaterial,
  },
});

distanceDisplayCondition

  • 类型:DistanceDisplayCondition
  • 默认值:undefined
  • 描述:控制距离多远时开始显示或停止显示线段。
const distanceDisplayCondition = new Cesium.DistanceDisplayCondition(0, 2000);
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 3,
    material: Cesium.Color.RED,
    distanceDisplayCondition: distanceDisplayCondition,
  },
});

clampToGround

  • 类型:Boolean
  • 默认值:false
  • 描述:指定是否将线段贴在地表上。
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 3,
    material: Cesium.Color.RED,
    clampToGround: true,
  },
});

followSurface

  • 类型:Boolean
  • 默认值:true
  • 描述:控制线段是否沿着地球表面弯曲。如果 clampToGround 属性为 true,则此属性无效。
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 3,
    material: Cesium.Color.RED,
    followSurface: false,
  },
});

granularity

  • 类型:Number
  • 默认值:Math.PI / 180.0
  • 描述:指定线段在球面上的采样间隔,以弧度为单位。值越小,精度越高,但性能越差。如果 clampToGround 属性为 true,则此属性无效。
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 3,
    material: Cesium.Color.RED,
    granularity: 0.1,
  },
});

shadows

  • 类型:ShadowMode
  • 默认值:ShadowMode.ENABLED
  • 描述:指定线段是否接收阴影。
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 3,
    material: Cesium.Color.RED,
    shadows: Cesium.ShadowMode.DISABLED,
  },
});

zIndex

  • 类型:Number
  • 默认值:0.0
  • 描述:指定线段的绘制顺序。
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 3,
    material: Cesium.Color.RED,
    zIndex: 1,
  },
});

Polyline 事件

Polyline 支持以下事件:

onDoubleClick

  • 类型:Event
  • 描述:双击事件。
polyline.onDoubleClick.addEventListener(() => {
  console.log('双击');
});

onMouseEnter

  • 类型:Event
  • 描述:鼠标进入事件。
polyline.onMouseEnter.addEventListener(() => {
  console.log('进入');
});

onMouseLeave

  • 类型:Event
  • 描述:鼠标离开事件。
polyline.onMouseLeave.addEventListener(() => {
  console.log('离开');
});

onMouseMove

  • 类型:Event
  • 描述:鼠标移动事件。
polyline.onMouseMove.addEventListener((e) => {
  console.log('坐标:', e.endPosition);
});

onMouseUp

  • 类型:Event
  • 描述:鼠标松开事件。
polyline.onMouseUp.addEventListener(() => {
  console.log('松开');
});

onMouseDown

  • 类型:Event
  • 描述:鼠标按下事件。
polyline.onMouseDown.addEventListener(() => {
  console.log('按下');
});

Polyline 方法

Polyline 支持以下方法:

isDestroyed()

  • 返回值:Boolean
  • 描述:判断 Polyline 是否被销毁。
console.log(polyline.isDestroyed());

pick()

  • 返回值:Cesium.Entity
  • 描述:获取当前鼠标位置处的 Polyline 实体。
const pickedEntity = viewer.scene.pick(position);
if (Cesium.defined(pickedEntity)) {
  const entity = pickedEntity.id;
  if (entity.polyline) {
    console.log('选中了线段:', entity.polyline);
  }
}

Polyline 示例

下面是一个绘制航线的示例代码:

const viewer = new Cesium.Viewer('cesiumContainer');
const positions = [
  Cesium.Cartesian3.fromDegrees(116.1, 39.9),
  Cesium.Cartesian3.fromDegrees(116.2, 39.9),
  Cesium.Cartesian3.fromDegrees(116.2, 40),
];
const polyline = viewer.entities.add({
  polyline: {
    positions: positions,
    width: 3,
    material: Cesium.Color.BLUE,
  },
});

const distanceDisplayCondition = new Cesium.DistanceDisplayCondition(0, 2000);
polyline.polyline.distanceDisplayCondition = distanceDisplayCondition;
polyline.polyline.followSurface = false;
polyline.polyline.granularity = 0.1;

const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction((event) => {
  const pickedEntity = viewer.scene.pick(event.position);
  if (Cesium.defined(pickedEntity)) {
    const entity = pickedEntity.id;
    if (entity.polyline) {
      alert('选中了线段');
    }
  }
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

在以上示例中,我们首先创建了一个 viewer 实例,然后定义了一组 positions 数组,指定了航线的起点和终点位置。接着,我们通过 viewer.entities.add 方法创建了一个 Polyline 实例,并将其添加到了场景中。在 Polyline 实例的配置中,我们指定了线段的 positionswidthmaterial 属性。

接下来,我们在 Polyline 实例上设置了一些属性和方法,包括:

  • distanceDisplayCondition 属性,用于控制距离多远时开始显示或停止显示线段。

  • followSurface 属性,用于控制线段是否沿着地球表面弯曲。

  • granularity 属性,用于指定线段在球面上的采样间隔。

  • onMouseClick 事件,用于监听鼠标点击事件,并在点击到 Polyline 实体时弹出提示框。

最终的效果如下图所示:

Polyline 示例