preface

In development, we usually need a clean 3d earth instance. This article will introduce Cesium how to initialize an earth, including the display and hiding of map controls and the loading of some common images and annotations

Preview the Demo

Cesium is a 3d earth and map oriented, world-class JavaScript open source products, it provides a development package based on JavaScript language, convenient for users to quickly build a zero plug-in virtual Earth Web application, and in performance, accuracy, rendering quality and multi-platform, Ease of use is guaranteed by high quality

For more information on Cesium, see 👉 making GIS 3D Visualization easy – Getting to know Cesium

Environment set up

The startup environment of this article and subsequent articles is based on VUE-CLI3.x +

Use the CLI plug-in vue-cli-plugin-cesium written by myself to build cesium environment with zero configuration

Specific environment construction can be seen at 👉 make GIS 3D visualization easy – Cesium integration in Vue project

Earth initialization

Apply for Token

Before development, we need to sign up for a free Cesium ion account

Complete the following steps

First, open cesium.com/ion/ and sign up for a new account

Once registered, log in and click on Access Tokens to go to the Access Tokens Page

As shown above, select the Default Access token of Default to copy into the content

Cesium.Ion.defaultAccessToken = '<YOUR ACCESS TOKEN HERE>'
Copy the code

Of course, if you’re just writing demos, you can do without tokens

Default initialization

Once the environment is ready, we can initialize the Cesium instance, that is, load the Earth

<template>
  <div class="map-box">
    <div id="cesiumContainer"></div>
  </div>
</template>

<script>
var viewer = null
export default {
  name: "No01Init".data() {
    return{}},mounted() {
    Cesium.Ion.defaultAccessToken = '<YOUR ACCESS TOKEN HERE>'
    // viewer = new Cesium.CesiumWidget('cesiumContainer')
    viewer = new Cesium.Viewer("cesiumContainer")

    console.log(viewer)
  },
}
</script>
<style scoped>
.map-box {
  width: 100%;
  height: 100%;
}
#cesiumContainer {
  width: 100%;
  height: 100%;
}
</style>

Copy the code

As shown above, we can use the new Cesium.CesiumWidget or the new Cesium.Viewer method to initialize the widget

If you are careful, you may have noticed that the viewer instance we initialized is not written in data. This is because Vue does data hijacking for attributes in data. If the attribute is an object, data hijacking will be carried out recursively. If you put it in data… There’s only one thing. The browser crashes

We can avoid this problem by placing a viewer variable on the component that declares it directly, or by mounting the viewer to the window using window.viewer

In Vue + Cesium development, you should be careful not to put any data related to the instance in data

Controls the hidden

As you can see above, there are a lot of controls on the page in default initialization that we don’t really use in development, but let’s start by explaining what they do

When creating a Cesium instance, the new Cesium.Viewer constructor takes two arguments

  • The element to which the instance is mounted is mandatory
  • Options Initializing the configuration object Is optional

In the Options object, we can configure some initialization controls to show hide and some render configurations. Here are some common configurations

viewer = new Cesium.Viewer("cesiumContainer", {
  animation: false.// Hide the animation control
  baseLayerPicker: false.// Hide the Layer selection control
  fullscreenButton: false.// Hide the full-screen button
  vrButton: false.// Hide the VR button, default false
  geocoder: false.// Hide the place name lookup control
  homeButton: false.// Hide the Home button
  infoBox: false.// Hide the message window after clicking the element
  sceneModePicker: false.// Hide the scene mode selection control
  selectionIndicator: true.// Displays the entity object selection box, true by default
  timeline: false.// Hide the timeline control
  navigationHelpButton: false.// Hide the help button
  scene3DOnly: true.// Each geometry instance will only be rendered in 3D to save GPU memory
  shouldAnimate: true.// Enable the animation to play automatically
  sceneMode: 3.// Initial scene mode 1:2d 2:2d loop 3:3d, default 3
  requestRenderMode: true.// Reduce the total time it takes for Cesium to render new frames and reduce the total CPU usage of Cesium in your application
  // if elements in the scene do not change with simulation time, consider setting maximumRenderTimeChange to a high value, such as Infinity
  maximumRenderTimeChange: Infinity
})
Copy the code

We can use the above options configuration to hide all the controls on the page, as shown in the figure below

As you can see, although the control is gone, there is still the Cesium logo information at the bottom of the screen, and we need to make it undisplayed as well

// Hide the Cesium logo below
viewer.cesiumWidget.creditContainer.style.display = "none"
Copy the code

As shown above, just one extra line of configuration hidden logo information is needed to get a clean earth instance, as shown below

Load the image

Cesium supports loading and rendering of high resolution image data from a variety of sources. Layers can be sorted and transparent mixed with brightness, Contrast, gamma, Hue. Saturation can be dynamically modified

We’ll skip the details here and briefly introduce a few image-related classes, then directly write code to add some different commonly used image layers

PS: Cesium is a constructor, and on that constructor there are an infinite number of static properties. They are constructors with different functions. Understood in OOP terms, Cesium is a parent class, and it has a number of subclasses that do different things

Cesium. ImageryProvider class

When it comes to images, first of all, we need to understand the class imageryProvider. Imagery can be translated into images and images, which are collectively called images here

The ImageryProvider class and its subclasses encapsulate methods for loading various image layers. The Cesium.ImageryProvider class is abstract, base, or interface, and cannot be instantiated directly

We can think of ImageryProvider as the data source of the image layer. We can load the image layer data or service with the corresponding ImageryProvider type

The type contained in the ImageryProvider class

  • ArcGisMapServerImageryProvider
    • ArcGIS Online and Server related services
  • BinaMapsImageryProvider
    • Bing map image, you can specify mapStyle, see BingMapsStyle class
  • GoogleEarthEnterpriselmageryProvider
    • Enterprise service
  • GridImageryProvider
    • Render the inner grid of each tile to understand the fineness of each tile
  • IonImageryProvider
    • The Cesium ion REST API provides imaging services
  • MapboxImageryProvider
    • Mapbox image service, specify map style according to mapId
  • MapboxStyleImageryProvider
    • Mapbox image service, specify map style according to styleId
  • createOpenStreetMapImageryProvider
    • Video services provided by OpenStreetMap
  • SingleTilelmageryProvider
    • Single image image service, suitable for offline data or image data requirements are not high scene
  • TileCoordinatesImageryProvider
    • Render the perimeter of each tile for easy debugging
  • TileMapServicelmageryProvider
    • According to MapTiler specifications, tiles can be downloaded and services can be released, similar to the process of ArcGIS image service
  • UrlTemplateImageryProvider
    • Specify the FORMAT template of url to facilitate users to implement their own providers, such as domestic autonavi, Tencent and other video services. Url is a fixed specification, which can be easily implemented through the Provider. OSM is also implemented through this class
  • WebMapServiceImageryProvider
    • All image services conforming to WMS specification can be encapsulated by this class and realized by specifying specific parameters
  • WebMapTileServicelmageryProvider
    • Service WMTS1.0.0 standard image services, can be achieved through this class, such as the domestic map of heaven and earth

Cesium. ImageryLayer class

It should be known that a GIS data will be organized into layers for symbolization and rendering. Data is equivalent to internal blood and viscera with rich information, while layers are equivalent to external fur and clothes for presentation to the outside world

Cesium also organizes data sources into layers for symbolization and rendering. Cesium.ImageryLayer class is used to represent image layers in Cesium, which is equivalent to fur and clothes, and wraps data sources. It needs data sources to provide rich internal geospatial information and attribute information

Cesium. ImageryLayerCollection class

Cesium ImageryLayerCollection class is ImageryLayer instance container, it can place multiple ImageryLayer instance, loading, and placed it inside ImageryLayer instance is ordered

The imageryLayers property contained in the Cesium.Viewer object is an instance of the ImageryLayerCollection class, which contains all the ImageryLayer objects of the current Cesium application. That is, all image layers currently loaded on earth

Now that we know the basic architecture of image layers, image loading is easy. As we can see above, there are a lot of ImageryProvider classes. They are listed to show you what images it can load, but it is not practical to demonstrate one by one, so let’s look at a few common image loading classes

Loading image sample

Load map of heaven and Earth image

Cesium Earth loads the Bing map image by default, so we need to delete the default image from the container

viewer.imageryLayers.remove(viewer.imageryLayers.get(0))
Copy the code

Next, we load the data source for the image layer

let tianditu = new Cesium.WebMapTileServiceImageryProvider({
  url:"Http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix= {tiles Matrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=ebf64362215c081f8317203220f133eb".layer: "tdtBasicLayer".style: "default".format: "image/jpeg".tileMatrixSetID: "GoogleMapsCompatible".show: false,})Copy the code

Tk in the URL field is the service token of Map Heaven and Earth. You can register and apply for one on the official website of Map Heaven and Earth

We then add the data source to the ImageryLayer class container for symbolization and rendering

There are two ways to add a data source to the ImageryLayer class container for symbolization and rendering. The first is in the Options configuration when initializing the Viewer instance. You can simply place the data source in the imageryProvider property of the Options object

new Cesium.Viewer("cesiumContainer", {imageryProvider: tianditu
})
Copy the code

The second method is to add it using the addImageryProvider method of the imageryLayers property in the Viewer instance

let imagery = viewer.imageryLayers.addImageryProvider(tianditu)
Copy the code

Map of heaven and Earth image preview below

Load Google Image

The above steps have been known, we will not describe, the following directly look at the code

viewer.imageryLayers.remove(viewer.imageryLayers.get(0))
let imagery = viewer.imageryLayers.addImageryProvider(
  new Cesium.UrlTemplateImageryProvider({
    url: "http://mt1.google.cn/vt/lyrs=s&hl=zh-CN&x={x}&y={y}&z={z}&s=Gali".baseLayerPicker : false}))Copy the code

Google Image preview below

Load ArcGIS image
viewer.imageryLayers.remove(viewer.imageryLayers.get(0))
let imagery = viewer.imageryLayers.addImageryProvider(
  new Cesium.ArcGisMapServerImageryProvider({
    url:'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'.baseLayerPicker : false}))Copy the code

ArcGIS image preview below

Load gord image
viewer.imageryLayers.remove(viewer.imageryLayers.get(0))
let imagery = viewer.imageryLayers.addImageryProvider(
  new Cesium.UrlTemplateImageryProvider({
    maximumLevel:18.// Maximum zoom level
    url : 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'.style: "default".format: "image/png".tileMatrixSetID: "GoogleMapsCompatible"}))Copy the code

Autonavi image preview below

Load map annotation

To load the image above, you can see that there are no labels on the map, so we need to load the extra pillar, which is also a layer

let label = viewer.imageryLayers.addImageryProvider(
  new Cesium.WebMapTileServiceImageryProvider({
    url: "Http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix= {tiles Matrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg"+"&tk="+"19b72f6cde5c8b49cf21ea2bb4c5b21e".layer: "tdtAnnoLayer".style: "default".maximumLevel: 18.// Maximum zoom level of the map
    format: "image/jpeg".tileMatrixSetID: "GoogleMapsCompatible".show: false,}))Copy the code

Also, as with map of heaven and Earth images, don’t forget to replace TK

Map of heaven and Earth annotation preview below

Image brightness adjustment

The brightness can be changed with its Brightness attribute. The value is 0 ~ 1. Default is 1

imagery.brightness = 0.9
Copy the code

Video summary

The ImageryProvider class we listed above supports many subclasses, whereas in the example above

When loading gold imaging services, we use the format of the specified url template to realize your Provider, so using the UrlTemplateImageryProvider class to load the data source

In loading ArcGIS images with the help of ArcGIS Server services so USES the ArcGisMapServerImageryProvider class to load the data source

When loading SPAR image, because we loaded is a Web Map Tile Service also is the WMTS Service, so we use the WebMapTileServiceImageryProvider class

This is a few simple examples to show what kind of data source we use, just use the corresponding ImageryProvider to load

Images to load this because this paper mainly describes the initialization, so how to load, and there is no corresponding data service related knowledge, Get a new skill, the first is to use, the next stage is the buckle details and then cooked it, then is extended, the last is to learn the principle, the subsequent through something used to expand the conceptual slowly

The last

Review this article, Cesium instance initialization, around the loading of a clean THREE-DIMENSIONAL earth instance, this article we mainly introduce the Cesium control reality hide and image loading, generally in order to beautify the interface, we are to write their own controls or directly hidden away. , of course, if the initial control Cesium in happens to have what you need, but also feel the space of the default style not too good, in fact, we can change their style, because controls more than ordinary element nodes, can directly in the console selected elements, by the name of the class to modify the style of the corresponding control to achieve their desired effect, Believe this isn’t too hard for a front end

In fact, this is only done to load out the earth and load the image, for Cesium it is only a start, more fun is still behind, in fact, not only do Cesium development crowd, do the front of the students to learn these or some useful, can add color to your page or project, the follow-up will write a Cesium series

Cesium domestic little tutorial, the document is in English, not so good, so this series is simply introduction and some effects (ie, introduces some examples of simple use and some fun), each article is introduced a point, it’s really hard to involve the core principle of Cesium, because I also in learning, see late personal learning situation, I just want to learn what I think is fun…

There is no professional GIS basic knowledge accumulation really good difficult, this series update irregularly, temporarily arranged so much, irregularly inserted, irregularly updated, please look forward to

The end of the

Original is not easy, after reading the praise, form a habit, this article is included in GitHub, more wonderful see 👉 isboyjc/blog/issues

If there are mistakes please point out, learn from each other, thank you first, a front-end Cesium learning process of accumulation sharing, self-aware depth is not enough, do not like spray

🏆 technology project phase iii | data visualization of those things…