Cesium Intermediate Course 4 - Visualization of Spatial Data

Keywords: Javascript Attribute

Entity function in Viewer

Let's look at the functions that Viewer provides for operating entities.

Select and describe

Clicking entity in Viewer will render the Selection Indicator control at entity location, providing an InfoBox for presenting more information. We can set the name to define the title of InfoBox. We also provide Entity.description attributes in HTML style.

wyoming.name = 'wyoming';
wyoming.description = '\
<img\
  width="50%"\
  style="float:left; margin: 0 1em 1em 0;"\
  src="//cesium.com/docs/tutorials/creating-entities/Flag_of_Wyoming.svg"/>\
<p>\
  Wyoming is a state in the mountain region of the Western \
  United States.\
</p>\
<p>\
  Wyoming is the 10th most extensive, but the least populous \
  and the second least densely populated of the 50 United \
  States. The western two thirds of the state is covered mostly \
  with the mountain ranges and rangelands in the foothills of \
  the eastern Rocky Mountains, while the eastern third of the \
  state is high elevation prairie known as the High Plains. \
  Cheyenne is the capital and the most populous city in Wyoming, \
  with a population estimate of 63,624 in 2017.\
</p>\
<p>\
  Source: \
  <a style="color: WHITE"\
    target="_blank"\
    href="http://en.wikipedia.org/wiki/Wyoming">Wikpedia</a>\
</p>';

All HTML shown in InfoBox is sandbox. This organizes malicious injection of external data sources into Cesium applications. To run JavaScript or browser plug-ins in the description, access iframe in the sandbox through the viewer.infoBox.frame property. Reference resources This article More information can be obtained to control sandboxes in iframe.

Camera control

Use the iewer.zoomto command to view a specific Entity. There is also a viewer.flyto method for performing animated Camera flights on Entity. Both methods can be passed to Entity, EntityCollection, DataSource, or entity arrays.

Any method calculates the views of all provided entities. By default, Camera faces north and looks down at 45 degrees. Customize this by passing in the Heading Pitchrange.

var heading = Cesium.Math.toRadians(90);
var pitch = Cesium.Math.toRadians(-30);
viewer.zoomTo(wyoming, new Cesium.HeadingPitchRange(heading, pitch));

zoomTo and flyTo are asynchronous functions; that is, they cannot guarantee completion before returning. For example, flying to Entity takes place after many animation frames. Both functions are returned Promises It can be used for planned flight or functions to be performed after zooming is completed. Replace zoomTo in the example with the following code snippet. The plane flew to Wyoming and selected it after the flight.

viewer.flyTo(wyoming).then(function(result){
    if (result) {
        viewer.selectedEntity = wyoming;
    }
});

If the flight is successfully completed, the result parameter passed to the callback function will be true; if the flight is cancelled, the result parameter will be false, that is, before the flight is completed, the user initiates another flight or zoom; or, because the target has no corresponding visual effect, there is no zoom object.

Sometimes, especially when dealing with time-dynamic data, we want Camera to focus on following an entity rather than the center of the Earth. You can do this by setting viewer.trackedEntity. Tracking entities need to set position.

wyoming.position = Cesium.Cartesian3.fromDegrees(-107.724, 42.68);
viewer.trackedEntity = wyoming;

To stop tracking, you need to set viewer.trackedEntity to undefined or double-click the screen away from entity. Calling zoomTo or flyTo can also cancel tracing.

Managing Entities

EntityCollection is an associative array for managing and monitoring a set of entities. viewer.entities is EntityCollection. EntityCollection includes methods for managing entities, such as add, remove, and remove All.

Sometimes we need to update the entities we created before. All entity instances have a unique ID that can be used to retrieve entities from collections. We can specify an ID for the entity, otherwise an ID will be generated automatically.

viewer.entities.add({
    id : 'uniqueId'
});

Use getByiId to retrieve entities. If there is no entity with the provided ID, undefined is returned.

var entity = viewer.entities.getById('uniqueId');

To get an entity or create a new entity (if it does not exist), use getOrCreateEntity.

var entity = viewer.entities.getOrCreateEntity('uniqueId');

Create a new entity manually, and then add it to the collection using add. If an entity with an id already exists in the collection, this method throws an exception.

var entity = new Entity({
    id : 'uniqueId'
});
viewer.entities.add(entity);

The EntityCollection function uses CollectionChanged events to emit light. The listener is notified when entities are added, deleted, or updated in the collection.

Use [Geometry Showcase] in Sandcastle
(https://cesiumjs.org/Cesium/B... Example. Paste the following code after creating the viewer line.

function onChanged(collection, added, removed, changed){
  var msg = 'Added ids';
  for(var i = 0; i < added.length; i++) {
    msg += '\n' + added[i].id;
  }
  console.log(msg);
}
viewer.entities.collectionChanged.addEventListener(onChanged);

When running this example, you should see about 65 messages in the console, one message each time you call viewer.entities.add.

When a large number of entities are updated at a time, queue updates are completed and an overall event is sent at the end, which is more performance. This allows Cesium to handle the required changes in a single pass. At the end of the example, before viewer.entities.add, call viewer.entities.suspendEvents and call viewer.entities.resumeEvents. When we run the demo again, we now get a single event that contains all 65 entities. These calls are reference counted, so you can nest multiple pending and recovery calls.

Picking up

Selecting (clicking on an object) is one of the areas where we need to interact briefly with the basic API. Use scene.pick and scene.drillpick to retrieve entities.

/**
 * Returns the top-most entity at the provided window coordinates
 * or undefined if no entity is at that location.
 *
 * @param {Cartesian2} windowPosition The window coordinates.
 * @returns {Entity} The picked entity or undefined.
 */
function pickEntity(viewer, windowPosition) {
  var picked = viewer.scene.pick(windowPosition);
  if (defined(picked)) {
    var id = Cesium.defaultValue(picked.id, picked.primitive.id);
    if (id instanceof Cesium.Entity) {
      return id;
    }
  }
  return undefined;
};

/**
 * Returns the list of entities at the provided window coordinates.
 * The entities are sorted front to back by their visual order.
 *
 * @param {Cartesian2} windowPosition The window coordinates.
 * @returns {Entity[]} The picked entities or undefined.
 */
function drillPickEntities(viewer, windowPosition) {
  var i;
  var entity;
  var picked;
  var pickedPrimitives = viewer.scene.drillPick(windowPosition);
  var length = pickedPrimitives.length;
  var result = [];
  var hash = {};

  for (i = 0; i < length; i++) {
    picked = pickedPrimitives[i];
    entity = Cesium.defaultValue(picked.id, picked.primitive.id);
    if (entity instanceof Cesium.Entity &&
        !Cesium.defined(hash[entity.id])) {
      result.push(entity);
      hash[entity.id] = true;
    }
  }
  return result;
};

Points, billboards, and labels (dots, billboards and labels)

Create graphic points or labels by setting position, point, and label. For example, place a spot on the main stadium of our favorite sports team.

var viewer = new Cesium.Viewer('cesiumContainer');

var citizensBankPark = viewer.entities.add({
    name : 'Citizens Bank Park',
    position : Cesium.Cartesian3.fromDegrees(-75.166493, 39.9060534),
    point : {
        pixelSize : 5,
        color : Cesium.Color.RED,
        outlineColor : Cesium.Color.WHITE,
        outlineWidth : 2
    },
    label : {
        text : 'Citizens Bank Park',
        font : '14pt monospace',
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        outlineWidth : 2,
        verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
        pixelOffset : new Cesium.Cartesian2(0, -9)
    }
});

viewer.zoomTo(viewer.entities);

By default, the label is centered horizontally and vertically. Because tags and points share the same location, they overlap on the screen. To avoid this, specify the label source Verticalorigin.BOTTOM and set the pixel offset to (0, -9).
Replace this point with a billboard, which is always user-oriented.

var citizensBankPark = viewer.entities.add({
  position : Cesium.Cartesian3.fromDegrees(-75.166493, 39.9060534),
  billboard : {
    image : '//cesiumjs.org/tutorials/Visualizing-Spatial-Data/images/Philadelphia_Phillies.png',
    width : 64,
    height : 64
  },
  label : {
    text : 'Citizens Bank Park',
    font : '14pt monospace',
    style: Cesium.LabelStyle.FILL_AND_OUTLINE,
    outlineWidth : 2,
    verticalOrigin : Cesium.VerticalOrigin.TOP,
    pixelOffset : new Cesium.Cartesian2(0, 32)
  }
});

For more customization options, see Sandcastle tags and billboard examples.

3D models

Cesium JS supports the creation of 3D models through glTF (runtime asset format). You can do this in the 3D models Sample models are found in Sandcastle.

Set the location and URI to the glTF model to create the model entity.

var viewer = new Cesium.Viewer('cesiumContainer');
var entity = viewer.entities.add({
    position : Cesium.Cartesian3.fromDegrees(-123.0744619, 44.0503706),
    model : {
        uri : '../../../../Apps/SampleData/models/GroundVehicle/GroundVehicle.glb'
    }
});
viewer.trackedEntity = entity;

By default, the model is vertical and east-oriented. The direction of the model is controlled by specifying Quaternion for the Entity.Orientation attribute. This will control the heading, pitch and roll of the model.

var viewer = new Cesium.Viewer('cesiumContainer');
var position = Cesium.Cartesian3.fromDegrees(-123.0744619, 44.0503706);
var heading = Cesium.Math.toRadians(45.0);
var pitch = Cesium.Math.toRadians(15.0);
var roll = Cesium.Math.toRadians(0.0);
var orientation = Cesium.Transforms.headingPitchRollQuaternion(position, new Cesium.HeadingPitchRoll(heading, pitch, roll));

var entity = viewer.entities.add({
    position : position,
    orientation : orientation,
    model : {
        uri : '../../../../Apps/SampleData/models/GroundVehicle/GroundVehicle.glb'
    }
});
viewer.trackedEntity = entity;

For more advanced model functionality, see 3D Modeling Course . If you create your own model, be sure to see what we have about it. glTF Tips for Artists Tips for posts.

The property system

All values we define for entities are stored as property objects. For example, see Wyoming outline values:

console.log(typeof wyoming.polygon.outline);

outline is an example of Constant Property. This tutorial uses a shorthand form called implicit property conversion, which automatically gets the original value and creates the corresponding Property under the hood. Without this shorthand, we would have to write a longer version of the initial example:

var wyoming = new Cesium.Entity();
wyoming.name = 'Wyoming';

var polygon = new Cesium.PolygonGraphics();
polygon.material = new Cesium.ColorMaterialProperty(Cesium.Color.RED.withAlpha(0.5));
polygon.outline = new Cesium.ConstantProperty(true);
polygon.outlineColor = new Cesium.ConstantProperty(Cesium.Color.BLACK);
wyoming.polygon = polygon;

viewer.entities.add(wyoming);

Attributes are used because entity API s can represent not only constant values, but also values that change over time. see also Callback Property and Interpolation Sandcastle example to learn about some temporal dynamic properties.

Resources

For an example of how to use GeoJSON and CZML to set styles and create entities, see Cesium Workshop Tutorial.

Cesium Chinese Communication QQ Group: 807482793

This article is based on admin Creation, adoption Knowledge Sharing Signature 3.0 Mainland China Licensing Agreement License.
It can be reproduced and quoted freely, but the author should be signed and the source of the article should be indicated.

Posted by yogicasey on Wed, 04 Sep 2019 22:00:24 -0700