Cesium JS API
AppearanceArcGisMapServerImageryProviderArcGISTiledElevationTerrainProviderArcTypeAssociativeArrayAxisAxisAlignedBoundingBoxbarycentricCoordinatesBillboardBillboardCollectionBillboardGraphicsBillboardVisualizerbinarySearchbinarySearchComparatorBingMapsGeocoderServiceBingMapsImageryProviderBingMapsStyleBlendEquationBlendFunctionBlendingStateBlendOptionBoundingRectangleBoundingSphereBoxEmitterBoxGeometryBoxGeometryUpdaterBoxGraphicsBoxOutlineGeometrybuildModuleUrlCallbackPropertyCameraCameraEventAggregatorCameraEventTypeCartesian2Cartesian3Cartesian4CartographicCartographicGeocoderServiceCatmullRomSplineCesium3DTileCesium3DTileColorBlendModeCesium3DTileContentCesium3DTileFeatureCesium3DTilePointFeatureCesium3DTilesetCesium3DTilesetGraphicsCesium3DTilesetVisualizerCesium3DTileStyleCesium3DTilesVoxelProviderCesiumTerrainProviderCesiumWidgetCheckerboardMaterialPropertyCircleEmitterCircleGeometryCircleOutlineGeometryClassificationPrimitiveClassificationTypeClippingPlaneClippingPlaneCollectionClockClockRangeClockStepcloneCloudCollectionCloudTypeColorColorBlendModeColorGeometryInstanceAttributeColorMaterialPropertycombineComponentDatatypeCompositeEntityCollectionCompositeMaterialPropertyCompositePositionPropertyCompositePropertyCompressedTextureBufferConditionsExpressionConeEmitterConstantPositionPropertyConstantPropertyConstantSplineContextOptionsCoplanarPolygonGeometryCoplanarPolygonOutlineGeometryCornerTypeCorridorGeometryCorridorGeometryUpdaterCorridorGraphicsCorridorOutlineGeometrycreateElevationBandMaterialcreateElevationBandMaterialBandcreateElevationBandMaterialEntrycreateGuidcreateOsmBuildingscreateTangentSpaceDebugPrimitivecreateWorldImagerycreateWorldTerrainCreditCreditDisplayCubicRealPolynomialCullFaceCullingVolumeCumulusCloudCustomDataSourceCustomHeightmapTerrainProviderCustomShaderCustomShaderModeCustomShaderTranslucencyModeCylinderGeometryCylinderGeometryUpdaterCylinderGraphicsCylinderOutlineGeometryCzmlDataSourceDataSourceDataSourceClockDataSourceCollectionDataSourceDisplayDebugAppearanceDebugCameraPrimitiveDebugModelMatrixPrimitiveDefaultProxydefaultValuedefinedDepthFunctiondestroyObjectDeveloperErrorDirectionalLightDirectionUpDiscardEmptyTileImagePolicyDiscardMissingTileImagePolicyDistanceDisplayConditionDistanceDisplayConditionGeometryInstanceAttributeEasingFunctionEllipseGeometryEllipseGeometryUpdaterEllipseGraphicsEllipseOutlineGeometryEllipsoidEllipsoidGeodesicEllipsoidGeometryEllipsoidGeometryUpdaterEllipsoidGraphicsEllipsoidOutlineGeometryEllipsoidRhumbLineEllipsoidSurfaceAppearanceEllipsoidTangentPlaneEllipsoidTerrainProviderEntityEntityClusterEntityCollectionEntityViewEventEventHelperexcludesReverseAxisexportKmlexportKmlModelCallbackexportKmlResultKmlexportKmlResultKmzExpressionExtrapolationTypeFeatureDetectionFogformatErrorFrameRateMonitorFrustumGeometryFrustumOutlineGeometryFullscreenGeocoderServiceGeocodeTypeGeographicProjectionGeographicTilingSchemeGeoJsonDataSourceGeometryGeometryAttributeGeometryAttributesGeometryFactoryGeometryInstanceGeometryInstanceAttributeGeometryPipelineGeometryUpdaterGeometryVisualizergetAbsoluteUrigetBaseUrigetExtensionFromUriGetFeatureInfoFormatgetFilenameFromUrigetImagePixelsgetTimestampGlobeGlobeTranslucencyGoogleEarthEnterpriseImageryProviderGoogleEarthEnterpriseMapsProviderGoogleEarthEnterpriseMetadataGoogleEarthEnterpriseTerrainDataGoogleEarthEnterpriseTerrainProviderGpxDataSourceGregorianDateGridImageryProviderGridMaterialPropertyGroundGeometryUpdaterGroundPolylineGeometryGroundPolylinePrimitiveGroundPrimitiveHeadingPitchRangeHeadingPitchRollHeadingPitchRollValuesHeightmapEncodingHeightmapTerrainDataHeightReferenceHermitePolynomialApproximationHermiteSplineHilbertOrderHorizontalOriginI3SDataProviderI3SFeatureI3SFieldI3SGeometryI3SLayerI3SNodeImageBasedLightingImageMaterialPropertyImageryLayerImageryLayerCollectionImageryLayerFeatureInfoImageryProviderImageryTypesincludesReverseAxisIndexDatatypeIntersectIntersections2DIntersectionTestsIntervalIonIonGeocoderServiceIonImageryProviderIonResourceIonWorldImageryStyleisLeapYearIso8601JulianDateKeyboardEventModifierKmlCameraKmlDataSourceKmlFeatureDataKmlLookAtKmlTourKmlTourFlyToKmlTourWaitLabelLabelCollectionLabelGraphicsLabelStyleLabelVisualizerLagrangePolynomialApproximationLeapSecondLightLightingModelLinearApproximationLinearSplineMapboxImageryProviderMapboxStyleImageryProviderMapMode2DMapProjectionMaterialMaterialAppearanceMaterialSupportMaterialPropertyMathMatrix2Matrix3Matrix4mergeSortmergeSortComparatorMetadataClassMetadataClassPropertyMetadataComponentTypeMetadataEnumMetadataEnumValueMetadataSchemaMetadataTypeModelModelAnimationModelAnimationCollectionModelAnimationLoopModelFeatureModelGraphicsModelNodeModelVisualizerMoonMorphWeightSplineNearFarScalarNeverTileDiscardPolicyNodeTransformationPropertyobjectToQueryOccluderOpenCageGeocoderServiceOpenStreetMapImageryProviderOrientedBoundingBoxOrthographicFrustumOrthographicOffCenterFrustumPackableForInterpolationParticleParticleBurstParticleEmitterParticleSystemPathGraphicsPathVisualizerPeliasGeocoderServicePerInstanceColorAppearancePerspectiveFrustumPerspectiveOffCenterFrustumPinBuilderPixelDatatypePixelFormatPlanePlaneGeometryPlaneGeometryUpdaterPlaneGraphicsPlaneOutlineGeometryPointCloudShadingPointGraphicspointInsideTrianglePointPrimitivePointPrimitiveCollectionPointVisualizerPolygonGeometryPolygonGeometryUpdaterPolygonGraphicsPolygonHierarchyPolygonOutlineGeometryPolylinePolylineArrowMaterialPropertyPolylineCollectionPolylineColorAppearancePolylineDashMaterialPropertyPolylineGeometryPolylineGeometryUpdaterPolylineGlowMaterialPropertyPolylineGraphicsPolylineMaterialAppearancePolylineOutlineMaterialPropertyPolylineVisualizerPolylineVolumeGeometryPolylineVolumeGeometryUpdaterPolylineVolumeGraphicsPolylineVolumeOutlineGeometryPositionPropertyPositionPropertyArrayPostProcessStagePostProcessStageCollectionPostProcessStageCompositePostProcessStageLibraryPostProcessStageSampleModePrimitivePrimitiveCollectionPrimitiveTypePropertyPropertyArrayPropertyBagProxyQuadraticRealPolynomialQuantizedMeshTerrainDataQuarticRealPolynomialQuaternionQuaternionSplinequeryToObjectQueueRayreadyPromiseRectangleRectangleGeometryRectangleGeometryUpdaterRectangleGraphicsRectangleOutlineGeometryReferenceFrameReferencePropertyremoveExtensionRequestRequestErrorEventRequestSchedulerRequestStateRequestTypeResourceRuntimeErrorSampledPositionPropertySampledPropertysampleTerrainsampleTerrainMostDetailedSceneSceneModeSceneTransformsScreenSpaceCameraControllerScreenSpaceEventHandlerScreenSpaceEventTypeshaderDefinesshaderMaximumIntersectionsLengthshaderUniformsShadowMapShadowModeShowGeometryInstanceAttributeSimon1994PlanetaryPositionsSimplePolylineGeometrySingleTileImageryProviderSkyAtmosphereSkyBoxSphereEmitterSphereGeometrySphereOutlineGeometrySphericalSplineSplitDirectionStencilFunctionStencilOperationSteppedSplineStripeMaterialPropertyStripeOrientationStyleExpressionsubdivideArraySunSunLightTaskProcessorTerrainDataTerrainProviderTextureMagnificationFilterTextureMinificationFilterTextureUniformTileAvailabilityTileCoordinatesImageryProviderTileDiscardPolicyTileMapServiceImageryProviderTileProviderErrorTilingSchemeTimeDynamicImageryTimeDynamicPointCloudTimeIntervalTimeIntervalCollectionTimeIntervalCollectionPositionPropertyTimeIntervalCollectionPropertyTimeStandardTransformsTranslationRotationScaleTridiagonalSystemSolverTrustedServersUniformSpecifierUniformTypeUrlTemplateImageryProviderVaryingTypeVelocityOrientationPropertyVelocityVectorPropertyVertexFormatVerticalOriginVideoSynchronizerViewportQuadVisibilityVisualizerVoxelPrimitiveVoxelProviderVoxelShapeTypeVRTheWorldTerrainProviderWallGeometryWallGeometryUpdaterWallGraphicsWallOutlineGeometryWebGLConstantsWebGLOptionsWebMapServiceImageryProviderWebMapTileServiceImageryProviderWebMercatorProjectionWebMercatorTilingSchemeWindingOrderwriteTextToCanvasAnimationAnimationViewModelBaseLayerPickerBaseLayerPickerViewModelCesium3DTilesInspectorCesium3DTilesInspectorViewModelCesiumInspectorCesiumInspectorViewModelClockViewModelCommandcreateCommandFullscreenButtonFullscreenButtonViewModelGeocoderGeocoderViewModelHomeButtonHomeButtonViewModelInfoBoxInfoBoxViewModelNavigationHelpButtonNavigationHelpButtonViewModelPerformanceWatchdogPerformanceWatchdogViewModelProjectionPickerProjectionPickerViewModelProviderViewModelSceneModePickerSceneModePickerViewModelSelectionIndicatorSelectionIndicatorViewModelSvgPathBindingHandlerTimelineToggleButtonViewModelViewerviewerCesium3DTilesInspectorMixinviewerCesiumInspectorMixinviewerDragDropMixinviewerPerformanceWatchdogMixinviewerVoxelInspectorMixinVoxelInspectorVoxelInspectorViewModelVRButtonVRButtonViewModel

Viewer

CesiumJS 的 Viewer 是一个可视化的三维地图浏览器,提供了一些基础的功能和界面交互。它包含了一个场景(Scene)、相机(Camera)、渲染器(Renderer)、影像层(ImageryLayer)等组件,可以方便地设置地图的基础功能,如视角、渲染方式、分层显示等。

创建 Viewer

创建 Viewer 很简单,只需要引入 Cesium 库,然后使用 new Cesium.Viewer 构造函数即可:

// 引入 Cesium 库
import Cesium from 'cesium/Cesium';

// 创建 Viewer
const viewer = new Cesium.Viewer('cesiumContainer');

其中的 'cesiumContainer' 是容器的 ID,用于在 HTML 页面上定位 Viewer 的位置。

创建 Viewer 后,就可以设置其一些基础属性,例如:

地球表面

设置 TerrainProvider 可以加载地球表面实体,其中可选的 url 参数指示加载 Cesium ion 或其他地形数据的 URL:

viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
   url : '//assets.agi.com/stk-terrain/world',
   requestWaterMask : false, // 不加载水位数据
   requestVertexNormals : true // 高程法线
});

地图样式

通过设置 ImageryProvider 以加载影像数据,可自由选择使用 Cesium ion、地图服务商提供的贴图服务或自定义的贴图:

// 使用 Cesium ion 影像服务提供商
viewer.imageryLayers.addImageryProvider(new Cesium.IonImageryProvider({ assetId: 3845 }));

// 加载自定义贴图
viewer.imageryLayers.addImageryProvider(new Cesium.SingleTileImageryProvider({
    url : 'https://assets.cesium.com/83/6976/clouds.png',
    rectangle : Cesium.Rectangle.fromDegrees(-85.0, 60.0, -75.0, 70.0)
}));

相机位置

定位相机位置,即为 Viewer 要显示的区域:

viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(-123.0744619, 44.0503706, 10000.0), // 目的地经纬度,高度为 10000 米
    orientation: {
        heading: Cesium.Math.toRadians(20.0), // 方向,单位弧度
        pitch: Cesium.Math.toRadians(-35.0), // 俯仰角,单位弧度
        roll: 0.0 // 侧翻角,单位弧度
    }
});

Viewer 交互

Viewer 已经实现了一些交互功能,例如:

鼠标左键

默认情况下,鼠标左键用于控制双击飞行之后的相机视角。支持如下交互:

  • 左键单击并拖动平移
  • 鼠标滚轮缩放
  • 左键单击选中地形实体
  • 双击飞行到相机拍摄的位置

鼠标右键

鼠标右键用于旋转相机视角。支持如下交互:

  • 右键单击并拖动进行视角旋转(默认)
  • 按住 Alt 键再右键单击并拖动进行平移
  • 右键单击选中地形实体

键盘

键盘用于控制相机视角和功能开关。支持如下交互:

  • 键盘 W/S/A/D/Q/E 分别控制相机前后/left/right/up/down 移动
  • 键盘 Shift + W/S 控制相机向上/向下移动
  • 键盘 C 控制相机聚焦到当前视角下的物体
  • 键盘 T 切换地形是否可见
  • 键盘 Alt + Enter 全屏

视角控制

可以通过 Camera 控件设置视角,展示 Viewer 其他区域:

// 定义视角
const view = {
    destination: Cesium.Cartesian3.fromDegrees(-86.0, 39.0, 10000.0),
    orientation: {
        heading : Cesium.Math.toRadians(0.0),
        pitch : Cesium.Math.toRadians(-90.0),
        roll : 0.0
    }
};

// 相机飞行,到达指定位置
viewer.camera.flyTo(view);

分屏显示

viewer 支持 双屏、三屏、四屏 等分屏显示或按照不同数量进行排列,同时每个屏幕的镜头视角也可以设置。

const { ScreenSpaceEventType, ScreenSpaceEventHandler, Cartesian2 } = Cesium;

// 分屏事件处理程序
const screenSpaceEventHandler = new ScreenSpaceEventHandler(viewer.scene.canvas);

// 单个屏幕
const screen1 = viewer.scene.globe.ellipsoid.cartographicToCartesian(...);

// 分屏显示
const screen2 = viewer.scene.globe.ellipsoid.cartographicToCartesian(...);

// /\形排列
viewer.scene.preRender.addEventListener(() => {
    // 单屏模式
    screenSpaceEventHandler.setInputAction((event) => {
        viewer.camera.lookAt(screen1, new Cartesian3(0, 0, 5000000.0));
    }, ScreenSpaceEventType.LEFT_CLICK);

    // 双屏模式
    screenSpaceEventHandler.setInputAction((event) => {
       viewer.camera.lookAt(screen1, new Cartesian3(0, 0, 5000000.0));
       viewer.extend(GlobeSplitDirection.LEFT);
       viewer.camera.lookAt(screen2, new Cartesian3(0, 0, 5000000.0));
    }, ScreenSpaceEventType.RIGHT_CLICK);
});

Viewer 控件

CesiumJS 提供了一些常用的控制器,可以用来实现功能:

  • NavigationBar - 在 Viewer 上下文菜单打开时显示的导航工具栏
  • Timeline - 显示时间轴的控件,可以向用户显示时间变化
  • HomeButton - 在 Viewer 中添加一个回到“Home”视图的按钮
  • BaseLayerPicker - 单击后弹出 Base Layer 组的选择菜单
  • Geocoder - 执行地理编码/地理逆编码的控件
  • SceneModePicker - 单击后以 SceneMode 为组的形式选择列表
// 导航栏控件
const ctrl1 = new Cesium.NavigationBar(viewer._toolbar, viewer.scene);
ctrl1.shouldAnimate = false;

// 时间轴控件
const ctrl2 = new Cesium.Timeline(viewer.timeline.container, viewer.clock);

// 地址编码/反编码控件
const ctrl3 = new Cesium.Geocoder(viewer.container, 'http://localhost:8080/', {
    scene : viewer.scene
});

// 底图选择器控件
const ctrl4 = new Cesium.BaseLayerPicker(viewer.container, options);

// 场景模式选择器控件
const modePicker = new Cesium.SceneModePicker(viewer.container, {
    scene : viewer.scene,
    buttonTooltip: 'Toggle scene mode'
});

除以上库提供的控制器,您还可以自定义一些控制器,例如:附加/移除自定义工具条,控制相机位置,还可以组合自定义工具栏。

总结

Viewer 作为 CesiumJS 的核心组件,用于创建和展示具有交互和可视化效果的三维地图。本文介绍了如何创建和配置 Viewer,以及通过交互和控制器进行定位视角和增强交互体验。读者应该对 Viewer 有了更全面的理解,并且可以在此基础上进行更丰富的应用程序设计和开发。