diff --git a/.eslintrc b/.eslintrc index 87c921c4d..214bed610 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,5 +1,8 @@ { - "extends": "openlayers", + "extends": [ + "openlayers", + ".eslintrc-es6.yaml" + ], "rules": { "no-console": 0, "no-extra-boolean-cast": 0, diff --git a/.eslintrc-es6.yaml b/.eslintrc-es6.yaml new file mode 100644 index 000000000..1a873b979 --- /dev/null +++ b/.eslintrc-es6.yaml @@ -0,0 +1,153 @@ +{ + env: { + es6: true + }, + parserOptions: { + ecmaVersion: 6, + sourceType: 'module', + ecmaFeatures: { + generators: false, + objectLiteralDuplicateProperties: false + } + }, + + rules: { + # enforces no braces where they can be omitted + # http://eslint.org/docs/rules/arrow-body-style + 'arrow-body-style': ['error', 'as-needed', { + requireReturnForObjectLiteral: true, + }], + + # require parens in arrow function arguments + # http://eslint.org/docs/rules/arrow-parens + 'arrow-parens': ['error', 'as-needed', { + requireForBlockBody: true, + }], + + # require space before/after arrow function's arrow + # http://eslint.org/docs/rules/arrow-spacing + 'arrow-spacing': ['error', { before: true, after: true }], + + # verify super() callings in constructors + 'constructor-super': 'error', + + # enforce the spacing around the * in generator functions + # http://eslint.org/docs/rules/generator-star-spacing + 'generator-star-spacing': ['error', { before: false, after: true }], + + # disallow modifying variables of class declarations + # http://eslint.org/docs/rules/no-class-assign + 'no-class-assign': 'error', + + # disallow arrow functions where they could be confused with comparisons + # http://eslint.org/docs/rules/no-confusing-arrow + 'no-confusing-arrow': ['error', { + allowParens: true, + }], + + # disallow modifying variables that are declared using const + 'no-const-assign': 'error', + + # disallow duplicate class members + # http://eslint.org/docs/rules/no-dupe-class-members + 'no-dupe-class-members': 'error', + + # disallow importing from the same path more than once + # http://eslint.org/docs/rules/no-duplicate-imports + 'no-duplicate-imports': 'error', + + # disallow symbol constructor + # http://eslint.org/docs/rules/no-new-symbol + 'no-new-symbol': 'error', + + # disallow specific imports + # http://eslint.org/docs/rules/no-restricted-imports + 'no-restricted-imports': 'off', + + # disallow to use this/super before super() calling in constructors. + # http://eslint.org/docs/rules/no-this-before-super + 'no-this-before-super': 'error', + + # disallow useless computed property keys + # http://eslint.org/docs/rules/no-useless-computed-key + 'no-useless-computed-key': 'error', + + # disallow unnecessary constructor + # http://eslint.org/docs/rules/no-useless-constructor + 'no-useless-constructor': 'error', + + # disallow renaming import, export, and destructured assignments to the same name + # http://eslint.org/docs/rules/no-useless-rename + 'no-useless-rename': ['error', { + ignoreDestructuring: false, + ignoreImport: false, + ignoreExport: false, + }], + + # require let or const instead of var + 'no-var': 'error', + + # require method and property shorthand syntax for object literals + # http://eslint.org/docs/rules/object-shorthand + 'object-shorthand': ['error', 'always', { + ignoreConstructors: false, + avoidQuotes: true, + }], + + # suggest using arrow functions as callbacks + 'prefer-arrow-callback': ['error', { + allowNamedFunctions: false, + allowUnboundThis: true, + }], + + # suggest using of const declaration for variables that are never modified after declared + 'prefer-const': ['error', { + destructuring: 'any', + ignoreReadBeforeAssign: true, + }], + + # disallow parseInt() in favor of binary, octal, and hexadecimal literals + # http://eslint.org/docs/rules/prefer-numeric-literals + 'prefer-numeric-literals': 'error', + + # use rest parameters instead of arguments + # http://eslint.org/docs/rules/prefer-rest-params + 'prefer-rest-params': 'error', + + # suggest using the spread operator instead of .apply() + # http://eslint.org/docs/rules/prefer-spread + 'prefer-spread': 'error', + + # suggest using template literals instead of string concatenation + # http://eslint.org/docs/rules/prefer-template + 'prefer-template': 'error', + + # disallow generator functions that do not have yield + # http://eslint.org/docs/rules/require-yield + 'require-yield': 'error', + + # enforce spacing between object rest-spread + # http://eslint.org/docs/rules/rest-spread-spacing + 'rest-spread-spacing': ['error', 'never'], + + # import sorting + # http://eslint.org/docs/rules/sort-imports + 'sort-imports': ['off', { + ignoreCase: false, + ignoreMemberSort: false, + memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'], + }], + + # require a Symbol description + # http://eslint.org/docs/rules/symbol-description + 'symbol-description': 'error', + + # enforce usage of spacing in template strings + # http://eslint.org/docs/rules/template-curly-spacing + 'template-curly-spacing': 'error', + + # enforce spacing around the * in yield* expressions + # http://eslint.org/docs/rules/yield-star-spacing + 'yield-star-spacing': ['error', 'after'] + } +} diff --git a/CHANGES.md b/CHANGES.md index 5827c0385..cd11f7f28 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -8,6 +8,7 @@ * Changes * Port to Cesium 1.31. * Add example rotate.html about animating rotation of the Cesium globe. + * Convert source to Ecmascript 6. Continue to output Ecmascript 5.1. # v 1.24.3 - 2017-02-17 diff --git a/build/olcesium.json b/build/olcesium.json index db61bd178..12cd858b6 100644 --- a/build/olcesium.json +++ b/build/olcesium.json @@ -33,7 +33,7 @@ "api", "observable" ], "compilation_level": "ADVANCED_OPTIMIZATIONS", - "language_in": "ECMASCRIPT5_STRICT", + "language_in": "ECMASCRIPT6_STRICT", "language_out": "ECMASCRIPT5_STRICT", "warning_level": "VERBOSE", "generate_exports": true, diff --git a/package.json b/package.json index 021649432..311279e92 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "@mapbox/geojsonhint": "2.0.1", "fs-extra": "2.0.0", "jsdoc": "~3.4.0", - "eslint": "3.16.1", + "eslint": "3.17.0", "eslint-config-openlayers": "7.0.0", "nomnom": "1.8.1", "temp": "0.8.3", diff --git a/src/abstractsynchronizer.js b/src/abstractsynchronizer.js index f16b5cf77..32bb1a5b9 100644 --- a/src/abstractsynchronizer.js +++ b/src/abstractsynchronizer.js @@ -99,18 +99,18 @@ olcs.AbstractSynchronizer.prototype.orderLayers = function() { */ olcs.AbstractSynchronizer.prototype.addLayers_ = function(root) { /** @type {Array.} */ - var fifo = [root]; + const fifo = [root]; while (fifo.length > 0) { - var olLayer = fifo.splice(0, 1)[0]; - var olLayerId = ol.getUid(olLayer).toString(); + const olLayer = fifo.splice(0, 1)[0]; + const olLayerId = ol.getUid(olLayer).toString(); goog.asserts.assert(!this.layerMap[olLayerId]); - var cesiumObjects = null; + let cesiumObjects = null; if (olLayer instanceof ol.layer.Group) { this.listenForGroupChanges_(olLayer); cesiumObjects = this.createSingleLayerCounterparts(olLayer); if (!cesiumObjects) { - olLayer.getLayers().forEach(function(l) { + olLayer.getLayers().forEach((l) => { if (l) { fifo.push(l); } @@ -142,8 +142,8 @@ olcs.AbstractSynchronizer.prototype.addLayers_ = function(root) { * @private */ olcs.AbstractSynchronizer.prototype.removeAndDestroySingleLayer_ = function(layer) { - var uid = ol.getUid(layer).toString(); - var counterparts = this.layerMap[uid]; + const uid = ol.getUid(layer).toString(); + const counterparts = this.layerMap[uid]; if (!!counterparts) { counterparts.forEach(function(counterpart) { this.removeSingleCesiumObject(counterpart, false); @@ -166,9 +166,9 @@ olcs.AbstractSynchronizer.prototype.unlistenSingleGroup_ = function(group) { if (group === this.mapLayerGroup) { return; } - var uid = ol.getUid(group).toString(); - var keys = this.olGroupListenKeys_[uid]; - keys.forEach(function(key) { + const uid = ol.getUid(group).toString(); + const keys = this.olGroupListenKeys_[uid]; + keys.forEach((key) => { ol.Observable.unByKey(key); }); delete this.olGroupListenKeys_[uid]; @@ -183,16 +183,16 @@ olcs.AbstractSynchronizer.prototype.unlistenSingleGroup_ = function(group) { */ olcs.AbstractSynchronizer.prototype.removeLayer_ = function(root) { if (!!root) { - var fifo = [root]; + const fifo = [root]; while (fifo.length > 0) { - var olLayer = fifo.splice(0, 1)[0]; - var done = this.removeAndDestroySingleLayer_(olLayer); + const olLayer = fifo.splice(0, 1)[0]; + const done = this.removeAndDestroySingleLayer_(olLayer); if (olLayer instanceof ol.layer.Group) { this.unlistenSingleGroup_(olLayer); if (!done) { // No counterpart for the group itself so removing // each of the child layers. - olLayer.getLayers().forEach(function(l) { + olLayer.getLayers().forEach((l) => { fifo.push(l); }); } @@ -208,17 +208,17 @@ olcs.AbstractSynchronizer.prototype.removeLayer_ = function(root) { * @private */ olcs.AbstractSynchronizer.prototype.listenForGroupChanges_ = function(group) { - var uuid = ol.getUid(group).toString(); + const uuid = ol.getUid(group).toString(); goog.asserts.assert(this.olGroupListenKeys_[uuid] === undefined); - var listenKeyArray = []; + const listenKeyArray = []; this.olGroupListenKeys_[uuid] = listenKeyArray; // only the keys that need to be relistened when collection changes - var contentKeys = []; - var listenAddRemove = (function() { - var collection = group.getLayers(); + let contentKeys = []; + const listenAddRemove = (function() { + const collection = group.getLayers(); if (collection) { contentKeys = [ collection.on('add', function(event) { @@ -228,15 +228,15 @@ olcs.AbstractSynchronizer.prototype.listenForGroupChanges_ = function(group) { this.removeLayer_(event.element); }, this) ]; - listenKeyArray.push.apply(listenKeyArray, contentKeys); + listenKeyArray.push(...contentKeys); } }).bind(this); listenAddRemove(); - listenKeyArray.push(group.on('change:layers', function(e) { - contentKeys.forEach(function(el) { - var i = listenKeyArray.indexOf(el); + listenKeyArray.push(group.on('change:layers', (e) => { + contentKeys.forEach((el) => { + const i = listenKeyArray.indexOf(el); if (i >= 0) { listenKeyArray.splice(i, 1); } @@ -253,13 +253,13 @@ olcs.AbstractSynchronizer.prototype.listenForGroupChanges_ = function(group) { */ olcs.AbstractSynchronizer.prototype.destroyAll = function() { this.removeAllCesiumObjects(true); // destroy - var objKey; + let objKey; for (objKey in this.olGroupListenKeys_) { - var keys = this.olGroupListenKeys_[objKey]; + const keys = this.olGroupListenKeys_[objKey]; keys.forEach(ol.Observable.unByKey); } for (objKey in this.olLayerListenKeys_) { - var key = this.olLayerListenKeys_[objKey]; + const key = this.olLayerListenKeys_[objKey]; ol.Observable.unByKey(key); } this.olGroupListenKeys_ = {}; diff --git a/src/autorenderloop.js b/src/autorenderloop.js index 4e43f2e96..75248e9f4 100644 --- a/src/autorenderloop.js +++ b/src/autorenderloop.js @@ -58,7 +58,7 @@ olcs.AutoRenderLoop = function(ol3d, debug) { * @private */ olcs.AutoRenderLoop.prototype.repaintOn_ = function(key, capture) { - var canvas = this.scene_.canvas; + const canvas = this.scene_.canvas; canvas.addEventListener(key, this._boundNotifyRepaintRequired, capture); }; @@ -69,7 +69,7 @@ olcs.AutoRenderLoop.prototype.repaintOn_ = function(key, capture) { * @private */ olcs.AutoRenderLoop.prototype.removeRepaintOn_ = function(key, capture) { - var canvas = this.scene_.canvas; + const canvas = this.scene_.canvas; canvas.removeEventListener(key, this._boundNotifyRepaintRequired, capture); }; @@ -96,7 +96,7 @@ olcs.AutoRenderLoop.prototype.enable = function() { window.addEventListener('resize', this._boundNotifyRepaintRequired, false); // Hacky way to force a repaint when an async load request completes - var that = this; + const that = this; Cesium.loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType, preferText, timeout) { deferred['promise']['always'](that._boundNotifyRepaintRequired); @@ -106,12 +106,12 @@ olcs.AutoRenderLoop.prototype.enable = function() { // Hacky way to force a repaint when a web worker sends something back. Cesium.TaskProcessor.prototype.scheduleTask = function(parameters, transferableObjects) { - var result = that._originalScheduleTask.call(this, parameters, + const result = that._originalScheduleTask.call(this, parameters, transferableObjects); - var taskProcessor = this; + const taskProcessor = this; if (!taskProcessor._originalWorkerMessageSinkRepaint) { - var worker = taskProcessor['_worker']; + const worker = taskProcessor['_worker']; taskProcessor._originalWorkerMessageSinkRepaint = worker.onmessage; worker.onmessage = function(event) { taskProcessor._originalWorkerMessageSinkRepaint(event); @@ -122,24 +122,24 @@ olcs.AutoRenderLoop.prototype.enable = function() { return result; }; - Cesium.Camera.prototype.setView = function() { - that._originalCameraSetView.apply(this, arguments); + Cesium.Camera.prototype.setView = function(...args) { + that._originalCameraSetView.apply(this, args); that.notifyRepaintRequired(); }; - Cesium.Camera.prototype.move = function() { - that._originalCameraMove.apply(this, arguments); + Cesium.Camera.prototype.move = function(...args) { + that._originalCameraMove.apply(this, args); that.notifyRepaintRequired(); }; - Cesium.Camera.prototype.rotate = function() { - that._originalCameraRotate.apply(this, arguments); + Cesium.Camera.prototype.rotate = function(...args) { + that._originalCameraRotate.apply(this, args); that.notifyRepaintRequired(); }; - Cesium.Camera.prototype.lookAt = function() { - that._originalCameraLookAt.apply(this, arguments); + Cesium.Camera.prototype.lookAt = function(...args) { + that._originalCameraLookAt.apply(this, args); that.notifyRepaintRequired(); }; - Cesium.Camera.prototype.flyTo = function() { - that._originalCameraFlyTo.apply(this, arguments); + Cesium.Camera.prototype.flyTo = function(...args) { + that._originalCameraFlyTo.apply(this, args); that.notifyRepaintRequired(); }; @@ -198,29 +198,29 @@ olcs.AutoRenderLoop.prototype.postRender = function(date) { // - the clock is not animating // - there are no tweens in progress - var now = Date.now(); + const now = Date.now(); - var scene = this.scene_; - var camera = scene.camera; + const scene = this.scene_; + const camera = scene.camera; if (!Cesium.Matrix4.equalsEpsilon(this.lastCameraViewMatrix_, camera.viewMatrix, 1e-5)) { this.lastCameraMoveTime_ = now; } - var cameraMovedInLastSecond = now - this.lastCameraMoveTime_ < 1000; + const cameraMovedInLastSecond = now - this.lastCameraMoveTime_ < 1000; - var surface = scene.globe['_surface']; - var tilesWaiting = !surface['tileProvider'].ready || + const surface = scene.globe['_surface']; + const tilesWaiting = !surface['tileProvider'].ready || surface['_tileLoadQueueHigh'].length > 0 || surface['_tileLoadQueueMedium'].length > 0 || surface['_tileLoadQueueLow'].length > 0 || surface['_debug']['tilesWaitingForChildren'] > 0; - var tweens = scene['tweens']; + const tweens = scene['tweens']; if (!cameraMovedInLastSecond && !tilesWaiting && tweens.length == 0) { if (this.verboseRendering) { - console.log('stopping rendering @ ' + Date.now()); + console.log(`stopping rendering @ ${Date.now()}`); } this.ol3d.setBlockCesiumRendering(true); this.stoppedRendering = true; @@ -245,7 +245,7 @@ olcs.AutoRenderLoop.prototype.restartRenderLoop = function() { */ olcs.AutoRenderLoop.prototype.notifyRepaintRequired = function() { if (this.verboseRendering && this.stoppedRendering) { - console.log('starting rendering @ ' + Date.now()); + console.log(`starting rendering @ ${Date.now()}`); } this.lastCameraMoveTime_ = Date.now(); // TODO: do not unblock if not blocked by us diff --git a/src/camera.js b/src/camera.js index e8b5801c8..c2482e10e 100644 --- a/src/camera.js +++ b/src/camera.js @@ -101,9 +101,9 @@ olcs.Camera = function(scene, map) { * @return {Array.} Input coordinate array (same array as input). */ olcs.Camera.identityProjection = function(input, opt_output, opt_dimension) { - var dim = opt_dimension || input.length; + const dim = opt_dimension || input.length; if (opt_output) { - for (var i = 0; i < dim; ++i) { + for (let i = 0; i < dim; ++i) { opt_output[i] = input[i]; } } @@ -123,8 +123,8 @@ olcs.Camera.prototype.setView_ = function(view) { this.view_ = view; if (view) { - var toLonLat = ol.proj.getTransform(view.getProjection(), 'EPSG:4326'); - var fromLonLat = ol.proj.getTransform('EPSG:4326', view.getProjection()); + const toLonLat = ol.proj.getTransform(view.getProjection(), 'EPSG:4326'); + const fromLonLat = ol.proj.getTransform('EPSG:4326', view.getProjection()); goog.asserts.assert(toLonLat && fromLonLat); this.toLonLat_ = toLonLat; @@ -173,7 +173,7 @@ olcs.Camera.prototype.getHeading = function() { if (!this.view_) { return undefined; } - var rotation = this.view_.getRotation(); + const rotation = this.view_.getRotation(); return rotation || 0; }; @@ -252,10 +252,10 @@ olcs.Camera.prototype.setPosition = function(position) { if (!this.toLonLat_) { return; } - var ll = this.toLonLat_(position); + const ll = this.toLonLat_(position); goog.asserts.assert(ll); - var carto = new Cesium.Cartographic(ol.math.toRadians(ll[0]), + const carto = new Cesium.Cartographic(ol.math.toRadians(ll[0]), ol.math.toRadians(ll[1]), this.getAltitude()); @@ -273,10 +273,10 @@ olcs.Camera.prototype.getPosition = function() { if (!this.fromLonLat_) { return undefined; } - var carto = Cesium.Ellipsoid.WGS84.cartesianToCartographic( + const carto = Cesium.Ellipsoid.WGS84.cartesianToCartographic( this.cam_.position); - var pos = this.fromLonLat_([ + const pos = this.fromLonLat_([ ol.math.toDegrees(carto.longitude), ol.math.toDegrees(carto.latitude) ]); @@ -290,7 +290,7 @@ olcs.Camera.prototype.getPosition = function() { * @api */ olcs.Camera.prototype.setAltitude = function(altitude) { - var carto = Cesium.Ellipsoid.WGS84.cartesianToCartographic( + const carto = Cesium.Ellipsoid.WGS84.cartesianToCartographic( this.cam_.position); carto.height = altitude; this.cam_.position = Cesium.Ellipsoid.WGS84.cartographicToCartesian(carto); @@ -304,7 +304,7 @@ olcs.Camera.prototype.setAltitude = function(altitude) { * @api */ olcs.Camera.prototype.getAltitude = function() { - var carto = Cesium.Ellipsoid.WGS84.cartesianToCartographic( + const carto = Cesium.Ellipsoid.WGS84.cartesianToCartographic( this.cam_.position); return carto.height; @@ -320,10 +320,10 @@ olcs.Camera.prototype.lookAt = function(position) { if (!this.toLonLat_) { return; } - var ll = this.toLonLat_(position); + const ll = this.toLonLat_(position); goog.asserts.assert(ll); - var carto = Cesium.Cartographic.fromDegrees(ll[0], ll[1]); + const carto = Cesium.Cartographic.fromDegrees(ll[0], ll[1]); olcs.core.lookAt(this.cam_, carto, this.scene_.globe); this.updateView(); @@ -339,31 +339,31 @@ olcs.Camera.prototype.updateCamera_ = function() { if (!this.view_ || !this.toLonLat_) { return; } - var center = this.view_.getCenter(); + const center = this.view_.getCenter(); if (!center) { return; } - var ll = this.toLonLat_(center); + const ll = this.toLonLat_(center); goog.asserts.assert(ll); - var carto = new Cesium.Cartographic(ol.math.toRadians(ll[0]), + const carto = new Cesium.Cartographic(ol.math.toRadians(ll[0]), ol.math.toRadians(ll[1])); if (this.scene_.globe) { - var height = this.scene_.globe.getHeight(carto); + const height = this.scene_.globe.getHeight(carto); carto.height = height || 0; } - var destination = Cesium.Ellipsoid.WGS84.cartographicToCartesian(carto); + const destination = Cesium.Ellipsoid.WGS84.cartographicToCartesian(carto); /** @type {Cesium.optionsOrientation} */ - var orientation = { + const orientation = { pitch: this.tilt_ - Cesium.Math.PI_OVER_TWO, heading: -this.view_.getRotation(), roll: undefined }; this.cam_.setView({ - destination: destination, - orientation: orientation + destination, + orientation }); this.cam_.moveBackward(this.distance_); @@ -380,14 +380,14 @@ olcs.Camera.prototype.readFromView = function() { if (!this.view_ || !this.toLonLat_) { return; } - var center = this.view_.getCenter(); + const center = this.view_.getCenter(); if (center === undefined || center === null) { return; } - var ll = this.toLonLat_(center); + const ll = this.toLonLat_(center); goog.asserts.assert(ll); - var resolution = this.view_.getResolution(); + const resolution = this.view_.getResolution(); this.distance_ = this.calcDistanceForResolution_( resolution || 0, ol.math.toRadians(ll[1])); @@ -407,21 +407,21 @@ olcs.Camera.prototype.updateView = function() { this.viewUpdateInProgress_ = true; // target & distance - var ellipsoid = Cesium.Ellipsoid.WGS84; - var scene = this.scene_; - var target = olcs.core.pickCenterPoint(scene); + const ellipsoid = Cesium.Ellipsoid.WGS84; + const scene = this.scene_; + const target = olcs.core.pickCenterPoint(scene); - var bestTarget = target; + let bestTarget = target; if (!bestTarget) { //TODO: how to handle this properly ? - var globe = scene.globe; - var carto = this.cam_.positionCartographic.clone(); - var height = globe.getHeight(carto); + const globe = scene.globe; + const carto = this.cam_.positionCartographic.clone(); + const height = globe.getHeight(carto); carto.height = height || 0; bestTarget = Cesium.Ellipsoid.WGS84.cartographicToCartesian(carto); } this.distance_ = Cesium.Cartesian3.distance(bestTarget, this.cam_.position); - var bestTargetCartographic = ellipsoid.cartesianToCartographic(bestTarget); + const bestTargetCartographic = ellipsoid.cartesianToCartographic(bestTarget); this.view_.setCenter(this.fromLonLat_([ ol.math.toDegrees(bestTargetCartographic.longitude), ol.math.toDegrees(bestTargetCartographic.latitude)])); @@ -437,30 +437,30 @@ olcs.Camera.prototype.updateView = function() { * need to be calculated _at the target_. */ if (target) { - var pos = this.cam_.position; + const pos = this.cam_.position; // normal to the ellipsoid at the target - var targetNormal = new Cesium.Cartesian3(); + const targetNormal = new Cesium.Cartesian3(); ellipsoid.geocentricSurfaceNormal(target, targetNormal); // vector from the target to the camera - var targetToCamera = new Cesium.Cartesian3(); + const targetToCamera = new Cesium.Cartesian3(); Cesium.Cartesian3.subtract(pos, target, targetToCamera); Cesium.Cartesian3.normalize(targetToCamera, targetToCamera); // HEADING - var up = this.cam_.up; - var right = this.cam_.right; - var normal = new Cesium.Cartesian3(-target.y, target.x, 0); // what is it? - var heading = Cesium.Cartesian3.angleBetween(right, normal); - var cross = Cesium.Cartesian3.cross(target, up, new Cesium.Cartesian3()); - var orientation = cross.z; + const up = this.cam_.up; + const right = this.cam_.right; + const normal = new Cesium.Cartesian3(-target.y, target.x, 0); // what is it? + const heading = Cesium.Cartesian3.angleBetween(right, normal); + const cross = Cesium.Cartesian3.cross(target, up, new Cesium.Cartesian3()); + const orientation = cross.z; this.view_.setRotation((orientation < 0 ? heading : -heading)); // TILT - var tiltAngle = Math.acos( + const tiltAngle = Math.acos( Cesium.Cartesian3.dot(targetNormal, targetToCamera)); this.tilt_ = isNaN(tiltAngle) ? 0 : tiltAngle; } else { @@ -478,8 +478,8 @@ olcs.Camera.prototype.updateView = function() { * @param {boolean=} opt_dontSync Do not synchronize the view. */ olcs.Camera.prototype.checkCameraChange = function(opt_dontSync) { - var old = this.lastCameraViewMatrix_; - var current = this.cam_.viewMatrix; + const old = this.lastCameraViewMatrix_; + const current = this.cam_.viewMatrix; if (!old || !Cesium.Matrix4.equalsEpsilon(old, current, 1e-5)) { this.lastCameraViewMatrix_ = current.clone(); @@ -498,22 +498,22 @@ olcs.Camera.prototype.checkCameraChange = function(opt_dontSync) { */ olcs.Camera.prototype.calcDistanceForResolution_ = function(resolution, latitude) { - var canvas = this.scene_.canvas; - var fovy = this.cam_.frustum.fovy; // vertical field of view + const canvas = this.scene_.canvas; + const fovy = this.cam_.frustum.fovy; // vertical field of view goog.asserts.assert(!isNaN(fovy)); - var metersPerUnit = this.view_.getProjection().getMetersPerUnit(); + const metersPerUnit = this.view_.getProjection().getMetersPerUnit(); // number of "map units" visible in 2D (vertically) - var visibleMapUnits = resolution * canvas.clientHeight; + const visibleMapUnits = resolution * canvas.clientHeight; // The metersPerUnit does not take latitude into account, but it should // be lower with increasing latitude -- we have to compensate. // In 3D it is not possible to maintain the resolution at more than one point, // so it only makes sense to use the latitude of the "target" point. - var relativeCircumference = Math.cos(Math.abs(latitude)); + const relativeCircumference = Math.cos(Math.abs(latitude)); // how many meters should be visible in 3D - var visibleMeters = visibleMapUnits * metersPerUnit * relativeCircumference; + const visibleMeters = visibleMapUnits * metersPerUnit * relativeCircumference; // distance required to view the calculated length in meters // @@ -522,7 +522,7 @@ olcs.Camera.prototype.calcDistanceForResolution_ = function(resolution, // x | \ // |--\ // visibleMeters/2 - var requiredDistance = (visibleMeters / 2) / Math.tan(fovy / 2); + const requiredDistance = (visibleMeters / 2) / Math.tan(fovy / 2); // NOTE: This calculation is not absolutely precise, because metersPerUnit // is a great simplification. It does not take ellipsoid/terrain into account. @@ -540,14 +540,14 @@ olcs.Camera.prototype.calcDistanceForResolution_ = function(resolution, olcs.Camera.prototype.calcResolutionForDistance_ = function(distance, latitude) { // See the reverse calculation (calcDistanceForResolution_) for details - var canvas = this.scene_.canvas; - var fovy = this.cam_.frustum.fovy; - var metersPerUnit = this.view_.getProjection().getMetersPerUnit(); - - var visibleMeters = 2 * distance * Math.tan(fovy / 2); - var relativeCircumference = Math.cos(Math.abs(latitude)); - var visibleMapUnits = visibleMeters / metersPerUnit / relativeCircumference; - var resolution = visibleMapUnits / canvas.clientHeight; + const canvas = this.scene_.canvas; + const fovy = this.cam_.frustum.fovy; + const metersPerUnit = this.view_.getProjection().getMetersPerUnit(); + + const visibleMeters = 2 * distance * Math.tan(fovy / 2); + const relativeCircumference = Math.cos(Math.abs(latitude)); + const visibleMapUnits = visibleMeters / metersPerUnit / relativeCircumference; + const resolution = visibleMapUnits / canvas.clientHeight; return resolution; }; diff --git a/src/core.js b/src/core.js index fe9717e61..09c09c7b4 100644 --- a/src/core.js +++ b/src/core.js @@ -17,12 +17,12 @@ goog.require('olcs.core.OLImageryProvider'); * @api */ olcs.core.computePixelSizeAtCoordinate = function(scene, target) { - var camera = scene.camera; - var canvas = scene.canvas; - var frustum = camera.frustum; - var distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract( + const camera = scene.camera; + const canvas = scene.canvas; + const frustum = camera.frustum; + const distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract( camera.position, target, new Cesium.Cartesian3())); - var pixelSize = new Cesium.Cartesian2(); + const pixelSize = new Cesium.Cartesian2(); return frustum.getPixelDimensions(canvas.clientWidth, canvas.clientHeight, distance, pixelSize); }; @@ -37,15 +37,15 @@ olcs.core.computePixelSizeAtCoordinate = function(scene, target) { * coordinates of the box */ olcs.core.computeBoundingBoxAtTarget = function(scene, target, amount) { - var pixelSize = olcs.core.computePixelSizeAtCoordinate(scene, target); - var transform = Cesium.Transforms.eastNorthUpToFixedFrame(target); + const pixelSize = olcs.core.computePixelSizeAtCoordinate(scene, target); + const transform = Cesium.Transforms.eastNorthUpToFixedFrame(target); - var bottomLeft = Cesium.Matrix4.multiplyByPoint( + const bottomLeft = Cesium.Matrix4.multiplyByPoint( transform, new Cesium.Cartesian3(-pixelSize.x * amount, -pixelSize.y * amount, 0), new Cesium.Cartesian3()); - var topRight = Cesium.Matrix4.multiplyByPoint( + const topRight = Cesium.Matrix4.multiplyByPoint( transform, new Cesium.Cartesian3(pixelSize.x * amount, pixelSize.y * amount, 0), new Cesium.Cartesian3()); @@ -62,10 +62,10 @@ olcs.core.computeBoundingBoxAtTarget = function(scene, target, amount) { * @api */ olcs.core.applyHeightOffsetToGeometry = function(geometry, height) { - geometry.applyTransform(function(input, output, stride) { + geometry.applyTransform((input, output, stride) => { goog.asserts.assert(input === output); if (stride !== undefined && stride >= 3) { - for (var i = 0; i < output.length; i += stride) { + for (let i = 0; i < output.length; i += stride) { output[i + 2] = output[i + 2] + height; } } @@ -84,26 +84,26 @@ olcs.core.applyHeightOffsetToGeometry = function(geometry, height) { */ olcs.core.rotateAroundAxis = function(camera, angle, axis, transform, opt_options) { - var clamp = Cesium.Math.clamp; - var defaultValue = Cesium.defaultValue; - - var options = opt_options || {}; - var duration = defaultValue(options.duration, 500); // ms - var easing = defaultValue(options.easing, ol.easing.linear); - var callback = options.callback; - - var lastProgress = 0; - var oldTransform = new Cesium.Matrix4(); - - var start = Date.now(); - var step = function() { - var timestamp = Date.now(); - var timeDifference = timestamp - start; - var progress = easing(clamp(timeDifference / duration, 0, 1)); + const clamp = Cesium.Math.clamp; + const defaultValue = Cesium.defaultValue; + + const options = opt_options || {}; + const duration = defaultValue(options.duration, 500); // ms + const easing = defaultValue(options.easing, ol.easing.linear); + const callback = options.callback; + + let lastProgress = 0; + const oldTransform = new Cesium.Matrix4(); + + const start = Date.now(); + const step = function() { + const timestamp = Date.now(); + const timeDifference = timestamp - start; + const progress = easing(clamp(timeDifference / duration, 0, 1)); goog.asserts.assert(progress >= lastProgress); camera.transform.clone(oldTransform); - var stepAngle = (progress - lastProgress) * angle; + const stepAngle = (progress - lastProgress) * angle; lastProgress = progress; camera.lookAtTransform(transform); camera.rotate(axis, stepAngle); @@ -130,23 +130,23 @@ olcs.core.rotateAroundAxis = function(camera, angle, axis, transform, */ olcs.core.setHeadingUsingBottomCenter = function(scene, heading, bottomCenter, opt_options) { - var camera = scene.camera; + const camera = scene.camera; // Compute the camera position to zenith quaternion - var angleToZenith = olcs.core.computeAngleToZenith(scene, bottomCenter); - var axis = camera.right; - var quaternion = Cesium.Quaternion.fromAxisAngle(axis, angleToZenith); - var rotation = Cesium.Matrix3.fromQuaternion(quaternion); + const angleToZenith = olcs.core.computeAngleToZenith(scene, bottomCenter); + const axis = camera.right; + const quaternion = Cesium.Quaternion.fromAxisAngle(axis, angleToZenith); + const rotation = Cesium.Matrix3.fromQuaternion(quaternion); // Get the zenith point from the rotation of the position vector - var vector = new Cesium.Cartesian3(); + const vector = new Cesium.Cartesian3(); Cesium.Cartesian3.subtract(camera.position, bottomCenter, vector); - var zenith = new Cesium.Cartesian3(); + const zenith = new Cesium.Cartesian3(); Cesium.Matrix3.multiplyByVector(rotation, vector, zenith); Cesium.Cartesian3.add(zenith, bottomCenter, zenith); // Actually rotate around the zenith normal - var transform = Cesium.Matrix4.fromTranslation(zenith); - var rotateAroundAxis = olcs.core.rotateAroundAxis; + const transform = Cesium.Matrix4.fromTranslation(zenith); + const rotateAroundAxis = olcs.core.rotateAroundAxis; rotateAroundAxis(camera, heading, zenith, transform, opt_options); }; @@ -159,8 +159,8 @@ olcs.core.setHeadingUsingBottomCenter = function(scene, heading, * @api */ olcs.core.pickOnTerrainOrEllipsoid = function(scene, pixel) { - var ray = scene.camera.getPickRay(pixel); - var target = scene.globe.pick(ray, scene); + const ray = scene.camera.getPickRay(pixel); + const target = scene.globe.pick(ray, scene); return target || scene.camera.pickEllipsoid(pixel); }; @@ -172,8 +172,8 @@ olcs.core.pickOnTerrainOrEllipsoid = function(scene, pixel) { * @api */ olcs.core.pickBottomPoint = function(scene) { - var canvas = scene.canvas; - var bottom = new Cesium.Cartesian2( + const canvas = scene.canvas; + const bottom = new Cesium.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight); return olcs.core.pickOnTerrainOrEllipsoid(scene, bottom); }; @@ -186,8 +186,8 @@ olcs.core.pickBottomPoint = function(scene) { * @api */ olcs.core.pickCenterPoint = function(scene) { - var canvas = scene.canvas; - var center = new Cesium.Cartesian2( + const canvas = scene.canvas; + const center = new Cesium.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2); return olcs.core.pickOnTerrainOrEllipsoid(scene, center); @@ -203,14 +203,14 @@ olcs.core.pickCenterPoint = function(scene) { * @api */ olcs.core.computeSignedTiltAngleOnGlobe = function(scene) { - var camera = scene.camera; - var ray = new Cesium.Ray(camera.position, camera.direction); - var target = scene.globe.pick(ray, scene); + const camera = scene.camera; + const ray = new Cesium.Ray(camera.position, camera.direction); + let target = scene.globe.pick(ray, scene); if (!target) { // no tiles in the area were loaded? - var ellipsoid = Cesium.Ellipsoid.WGS84; - var obj = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid); + const ellipsoid = Cesium.Ellipsoid.WGS84; + const obj = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid); if (obj) { target = Cesium.Ray.getPoint(ray, obj.start); } @@ -220,11 +220,11 @@ olcs.core.computeSignedTiltAngleOnGlobe = function(scene) { return undefined; } - var normal = new Cesium.Cartesian3(); + const normal = new Cesium.Cartesian3(); Cesium.Ellipsoid.WGS84.geocentricSurfaceNormal(target, normal); - var angleBetween = olcs.core.signedAngleBetween; - var angle = angleBetween(camera.direction, normal, camera.right) - Math.PI; + const angleBetween = olcs.core.signedAngleBetween; + const angle = angleBetween(camera.direction, normal, camera.right) - Math.PI; return Cesium.Math.convertLongitudeRange(angle); }; @@ -235,12 +235,12 @@ olcs.core.computeSignedTiltAngleOnGlobe = function(scene) { * @return {!Cesium.Ray} */ olcs.core.bottomFovRay = function(scene) { - var camera = scene.camera; - var fovy2 = camera.frustum.fovy / 2; - var direction = camera.direction; - var rotation = Cesium.Quaternion.fromAxisAngle(camera.right, fovy2); - var matrix = Cesium.Matrix3.fromQuaternion(rotation); - var vector = new Cesium.Cartesian3(); + const camera = scene.camera; + const fovy2 = camera.frustum.fovy / 2; + const direction = camera.direction; + const rotation = Cesium.Quaternion.fromAxisAngle(camera.right, fovy2); + const matrix = Cesium.Matrix3.fromQuaternion(rotation); + const vector = new Cesium.Cartesian3(); Cesium.Matrix3.multiplyByVector(matrix, direction, vector); return new Cesium.Ray(camera.position, vector); }; @@ -256,19 +256,19 @@ olcs.core.bottomFovRay = function(scene) { olcs.core.signedAngleBetween = function(first, second, normal) { // We are using the dot for the angle. // Then the cross and the dot for the sign. - var a = new Cesium.Cartesian3(); - var b = new Cesium.Cartesian3(); - var c = new Cesium.Cartesian3(); + const a = new Cesium.Cartesian3(); + const b = new Cesium.Cartesian3(); + const c = new Cesium.Cartesian3(); Cesium.Cartesian3.normalize(first, a); Cesium.Cartesian3.normalize(second, b); Cesium.Cartesian3.cross(a, b, c); - var cosine = Cesium.Cartesian3.dot(a, b); - var sine = Cesium.Cartesian3.magnitude(c); + const cosine = Cesium.Cartesian3.dot(a, b); + const sine = Cesium.Cartesian3.magnitude(c); // Sign of the vector product and the orientation normal - var sign = Cesium.Cartesian3.dot(normal, c); - var angle = Math.atan2(sine, cosine); + const sign = Cesium.Cartesian3.dot(normal, c); + const angle = Math.atan2(sine, cosine); return sign >= 0 ? angle : -angle; }; @@ -293,19 +293,19 @@ olcs.core.computeAngleToZenith = function(scene, pivot) { // \fy| / // \ |a/ // \|/pivot - var camera = scene.camera; - var fy = camera.frustum.fovy / 2; - var ray = olcs.core.bottomFovRay(scene); - var direction = Cesium.Cartesian3.clone(ray.direction); + const camera = scene.camera; + const fy = camera.frustum.fovy / 2; + const ray = olcs.core.bottomFovRay(scene); + const direction = Cesium.Cartesian3.clone(ray.direction); Cesium.Cartesian3.negate(direction, direction); - var normal = new Cesium.Cartesian3(); + const normal = new Cesium.Cartesian3(); Cesium.Ellipsoid.WGS84.geocentricSurfaceNormal(pivot, normal); - var left = new Cesium.Cartesian3(); + const left = new Cesium.Cartesian3(); Cesium.Cartesian3.negate(camera.right, left); - var a = olcs.core.signedAngleBetween(normal, direction, left); + const a = olcs.core.signedAngleBetween(normal, direction, left); return a + fy; }; @@ -320,15 +320,15 @@ olcs.core.computeAngleToZenith = function(scene, pivot) { */ olcs.core.lookAt = function(camera, target, opt_globe) { if (opt_globe) { - var height = opt_globe.getHeight(target); + const height = opt_globe.getHeight(target); target.height = height || 0; } - var ellipsoid = Cesium.Ellipsoid.WGS84; - var targetb = ellipsoid.cartographicToCartesian(target); + const ellipsoid = Cesium.Ellipsoid.WGS84; + const targetb = ellipsoid.cartographicToCartesian(target); - var position = camera.position; - var up = new Cesium.Cartesian3(); + const position = camera.position; + const up = new Cesium.Cartesian3(); ellipsoid.geocentricSurfaceNormal(position, up); camera.lookAt(position, targetb, up); @@ -344,7 +344,7 @@ olcs.core.lookAt = function(camera, target, opt_globe) { */ olcs.core.extentToRectangle = function(extent, projection) { if (extent && projection) { - var ext = ol.proj.transformExtent(extent, projection, 'EPSG:4326'); + const ext = ol.proj.transformExtent(extent, projection, 'EPSG:4326'); return Cesium.Rectangle.fromDegrees(ext[0], ext[1], ext[2], ext[3]); } else { return null; @@ -365,16 +365,16 @@ olcs.core.tileLayerToImageryLayer = function(olLayer, viewProj) { return null; } - var provider = null; + let provider = null; - var source = olLayer.getSource(); + const source = olLayer.getSource(); // handle special cases before the general synchronization if (source instanceof ol.source.WMTS) { // WMTS uses different TileGrid which is not currently supported return null; } if (source instanceof ol.source.TileImage) { - var projection = source.getProjection(); + let projection = source.getProjection(); if (!projection) { // if not explicit, assume the same projection as view @@ -383,8 +383,8 @@ olcs.core.tileLayerToImageryLayer = function(olLayer, viewProj) { return null; // do not sync layers with projections different than view } - var is3857 = projection === ol.proj.get('EPSG:3857'); - var is4326 = projection === ol.proj.get('EPSG:4326'); + const is3857 = projection === ol.proj.get('EPSG:3857'); + const is4326 = projection === ol.proj.get('EPSG:4326'); if (is3857 || is4326) { provider = new olcs.core.OLImageryProvider(source, viewProj); } else { @@ -397,14 +397,14 @@ olcs.core.tileLayerToImageryLayer = function(olLayer, viewProj) { // the provider is always non-null if we got this far - var layerOptions = {}; + const layerOptions = {}; - var ext = olLayer.getExtent(); + const ext = olLayer.getExtent(); if (ext && viewProj) { layerOptions.rectangle = olcs.core.extentToRectangle(ext, viewProj); } - var cesiumLayer = new Cesium.ImageryLayer(provider, layerOptions); + const cesiumLayer = new Cesium.ImageryLayer(provider, layerOptions); return cesiumLayer; }; @@ -417,11 +417,11 @@ olcs.core.tileLayerToImageryLayer = function(olLayer, viewProj) { * @api */ olcs.core.updateCesiumLayerProperties = function(olLayer, csLayer) { - var opacity = olLayer.getOpacity(); + const opacity = olLayer.getOpacity(); if (opacity !== undefined) { csLayer.alpha = opacity; } - var visible = olLayer.getVisible(); + const visible = olLayer.getVisible(); if (visible !== undefined) { csLayer.show = visible; } @@ -435,7 +435,7 @@ olcs.core.updateCesiumLayerProperties = function(olLayer, csLayer) { * @api */ olcs.core.ol4326CoordinateToCesiumCartesian = function(coordinate) { - var coo = coordinate; + const coo = coordinate; return coo.length > 2 ? Cesium.Cartesian3.fromDegrees(coo[0], coo[1], coo[2]) : Cesium.Cartesian3.fromDegrees(coo[0], coo[1]); @@ -450,9 +450,9 @@ olcs.core.ol4326CoordinateToCesiumCartesian = function(coordinate) { */ olcs.core.ol4326CoordinateArrayToCsCartesians = function(coordinates) { goog.asserts.assert(coordinates !== null); - var toCartesian = olcs.core.ol4326CoordinateToCesiumCartesian; - var cartesians = []; - for (var i = 0; i < coordinates.length; ++i) { + const toCartesian = olcs.core.ol4326CoordinateToCesiumCartesian; + const cartesians = []; + for (let i = 0; i < coordinates.length; ++i) { cartesians.push(toCartesian(coordinates[i])); } return cartesians; @@ -472,10 +472,10 @@ olcs.core.ol4326CoordinateArrayToCsCartesians = function(coordinates) { olcs.core.olGeometryCloneTo4326 = function(geometry, projection) { goog.asserts.assert(projection); - var proj4326 = ol.proj.get('EPSG:4326'); - var proj = ol.proj.get(projection); + const proj4326 = ol.proj.get('EPSG:4326'); + const proj = ol.proj.get(projection); if (proj !== proj4326) { - var properties = geometry.getProperties(); + const properties = geometry.getProperties(); geometry = geometry.clone(); geometry.transform(proj, proj4326); geometry.setProperties(properties); @@ -513,20 +513,20 @@ olcs.core.convertColorToCesium = function(olColor) { * @api */ olcs.core.convertUrlToCesium = function(url) { - var subdomains = ''; - var re = /\{(\d|[a-z])-(\d|[a-z])\}/; - var match = re.exec(url); + let subdomains = ''; + const re = /\{(\d|[a-z])-(\d|[a-z])\}/; + const match = re.exec(url); if (match) { url = url.replace(re, '{s}'); - var startCharCode = match[1].charCodeAt(0); - var stopCharCode = match[2].charCodeAt(0); - var charCode; + const startCharCode = match[1].charCodeAt(0); + const stopCharCode = match[2].charCodeAt(0); + let charCode; for (charCode = startCharCode; charCode <= stopCharCode; ++charCode) { subdomains += String.fromCharCode(charCode); } } return { - url: url, - subdomains: subdomains + url, + subdomains }; }; diff --git a/src/core/olimageryprovider.js b/src/core/olimageryprovider.js index 88a7e5f34..542b6f37b 100644 --- a/src/core/olimageryprovider.js +++ b/src/core/olimageryprovider.js @@ -40,7 +40,7 @@ olcs.core.OLImageryProvider = function(source, opt_fallbackProj) { this.ready_ = false; - var proxy = this.source_.get('olcs.proxy'); + const proxy = this.source_.get('olcs.proxy'); if (proxy) { if (typeof proxy === 'function') { this.proxy_ = { @@ -80,7 +80,7 @@ Object.defineProperties(olcs.core.OLImageryProvider.prototype, { 'tileWidth': { 'get': /** @this {olcs.core.OLImageryProvider} */ function() { - var tg = this.source_.getTileGrid(); + const tg = this.source_.getTileGrid(); return tg ? tg.getTileSize(0) : 256; } }, @@ -93,7 +93,7 @@ Object.defineProperties(olcs.core.OLImageryProvider.prototype, { 'maximumLevel': { 'get': /** @this {olcs.core.OLImageryProvider} */ function() { - var tg = this.source_.getTileGrid(); + const tg = this.source_.getTileGrid(); return tg ? tg.getMaxZoom() : 18; } }, @@ -151,7 +151,7 @@ Object.defineProperties(olcs.core.OLImageryProvider.prototype, { */ olcs.core.OLImageryProvider.prototype.handleSourceChanged_ = function() { if (!this.ready_ && this.source_.getState() == 'ready') { - var proj = this.source_.getProjection(); + const proj = this.source_.getProjection(); this.projection_ = proj ? proj : this.fallbackProj_; if (this.projection_ == ol.proj.get('EPSG:4326')) { this.tilingScheme_ = new Cesium.GeographicTilingScheme(); @@ -162,7 +162,7 @@ olcs.core.OLImageryProvider.prototype.handleSourceChanged_ = function() { } this.rectangle_ = this.tilingScheme_.rectangle; - var credit = + const credit = olcs.core.OLImageryProvider.createCreditForSource(this.source_); this.credit_ = credit || undefined; @@ -178,21 +178,21 @@ olcs.core.OLImageryProvider.prototype.handleSourceChanged_ = function() { * @return {?Cesium.Credit} */ olcs.core.OLImageryProvider.createCreditForSource = function(source) { - var text = ''; - var attributions = source.getAttributions(); + let text = ''; + const attributions = source.getAttributions(); if (attributions) { - attributions.forEach(function(el) { + attributions.forEach((el) => { // strip html tags (not supported in Cesium) - text += el.getHTML().replace(/<\/?[^>]+(>|$)/g, '') + ' '; + text += `${el.getHTML().replace(/<\/?[^>]+(>|$)/g, '')} `; }); } - var imageUrl, link; + let imageUrl, link; if (text.length == 0) { // only use logo if no text is specified // otherwise the Cesium will automatically skip the text: // "The text to be displayed on the screen if no imageUrl is specified." - var logo = source.getLogo(); + const logo = source.getLogo(); if (logo) { if (typeof logo == 'string') { imageUrl = logo; @@ -223,17 +223,17 @@ olcs.core.OLImageryProvider.prototype.getTileCredits = function(x, y, level) { * @override */ olcs.core.OLImageryProvider.prototype.requestImage = function(x, y, level) { - var tileUrlFunction = this.source_.getTileUrlFunction(); + const tileUrlFunction = this.source_.getTileUrlFunction(); if (tileUrlFunction && this.projection_) { // Perform mapping of Cesium tile coordinates to OpenLayers tile coordinates: // 1) Cesium zoom level 0 is OpenLayers zoom level 1 for EPSG:4326 - var z_ = this.tilingScheme_ instanceof Cesium.GeographicTilingScheme ? + const z_ = this.tilingScheme_ instanceof Cesium.GeographicTilingScheme ? level + 1 : level; // 2) OpenLayers tile coordinates increase from bottom to top - var y_ = -y - 1; + const y_ = -y - 1; - var url = tileUrlFunction.call(this.source_, + let url = tileUrlFunction.call(this.source_, [z_, x, y_], 1, this.projection_); if (this.proxy_) { url = this.proxy_.getURL(url); diff --git a/src/core/vectorlayercounterpart.js b/src/core/vectorlayercounterpart.js index 6851361cc..68366f3ae 100644 --- a/src/core/vectorlayercounterpart.js +++ b/src/core/vectorlayercounterpart.js @@ -11,8 +11,8 @@ goog.require('ol.Observable'); * @param {!Cesium.Scene} scene */ olcs.core.VectorLayerCounterpart = function(layerProjection, scene) { - var billboards = new Cesium.BillboardCollection({scene: scene}); - var primitives = new Cesium.PrimitiveCollection(); + const billboards = new Cesium.BillboardCollection({scene}); + const primitives = new Cesium.PrimitiveCollection(); /** * @type {!Array.} @@ -25,9 +25,9 @@ olcs.core.VectorLayerCounterpart = function(layerProjection, scene) { */ this.context = { projection: layerProjection, - billboards: billboards, + billboards, featureToCesiumMap: {}, - primitives: primitives + primitives }; this.rootCollection_.add(billboards); diff --git a/src/featureconverter.js b/src/featureconverter.js index 0ddab7d93..e30361958 100644 --- a/src/featureconverter.js +++ b/src/featureconverter.js @@ -43,23 +43,23 @@ olcs.FeatureConverter = function(scene) { * @private */ olcs.FeatureConverter.prototype.onRemoveOrClearFeature_ = function(evt) { - var source = evt.target; + const source = evt.target; goog.asserts.assertInstanceof(source, ol.source.Vector); - var cancellers = olcs.util.obj(source)['olcs_cancellers']; + const cancellers = olcs.util.obj(source)['olcs_cancellers']; if (cancellers) { - var feature = evt.feature; + const feature = evt.feature; if (feature) { // remove - var id = ol.getUid(feature); - var canceller = cancellers[id]; + const id = ol.getUid(feature); + const canceller = cancellers[id]; if (canceller) { canceller(); delete cancellers[id]; } } else { // clear - for (var key in cancellers) { + for (const key in cancellers) { if (cancellers.hasOwnProperty(key)) { cancellers[key](); } @@ -95,17 +95,17 @@ olcs.FeatureConverter.prototype.setReferenceForPicking = function(layer, feature * @protected */ olcs.FeatureConverter.prototype.createColoredPrimitive = function(layer, feature, olGeometry, geometry, color, opt_lineWidth) { - var createInstance = function(geometry, color) { + const createInstance = function(geometry, color) { return new Cesium.GeometryInstance({ // always update Cesium externs before adding a property - geometry: geometry, + geometry, attributes: { color: Cesium.ColorGeometryInstanceAttribute.fromColor(color) } }); }; - var options = { + const options = { // always update Cesium externs before adding a property flat: true, // work with all geometries renderState: { @@ -122,14 +122,14 @@ olcs.FeatureConverter.prototype.createColoredPrimitive = function(layer, feature options.renderState.lineWidth = opt_lineWidth; } - var instances = createInstance(geometry, color); + const instances = createInstance(geometry, color); - var heightReference = this.getHeightReference(layer, feature, olGeometry); + const heightReference = this.getHeightReference(layer, feature, olGeometry); - var primitive; + let primitive; if (heightReference == Cesium.HeightReference.CLAMP_TO_GROUND) { - var ctor = instances.geometry.constructor; + const ctor = instances.geometry.constructor; if (ctor && !ctor['createShadowVolume']) { return null; } @@ -138,11 +138,11 @@ olcs.FeatureConverter.prototype.createColoredPrimitive = function(layer, feature geometryInstances: instances }); } else { - var appearance = new Cesium.PerInstanceColorAppearance(options); + const appearance = new Cesium.PerInstanceColorAppearance(options); primitive = new Cesium.Primitive({ // always update Cesium externs before adding a property geometryInstances: instances, - appearance: appearance + appearance }); } @@ -159,10 +159,10 @@ olcs.FeatureConverter.prototype.createColoredPrimitive = function(layer, feature * @protected */ olcs.FeatureConverter.prototype.extractColorFromOlStyle = function(style, outline) { - var fillColor = style.getFill() ? style.getFill().getColor() : null; - var strokeColor = style.getStroke() ? style.getStroke().getColor() : null; + const fillColor = style.getFill() ? style.getFill().getColor() : null; + const strokeColor = style.getStroke() ? style.getStroke().getColor() : null; - var olColor = 'black'; + let olColor = 'black'; if (strokeColor && outline) { olColor = strokeColor; } else if (fillColor) { @@ -181,7 +181,7 @@ olcs.FeatureConverter.prototype.extractColorFromOlStyle = function(style, outlin */ olcs.FeatureConverter.prototype.extractLineWidthFromOlStyle = function(style) { // Handling of line width WebGL limitations is handled by Cesium. - var width = style.getStroke() ? style.getStroke().getWidth() : undefined; + const width = style.getStroke() ? style.getStroke().getWidth() : undefined; return width !== undefined ? width : 1; }; @@ -199,20 +199,20 @@ olcs.FeatureConverter.prototype.extractLineWidthFromOlStyle = function(style) { * @protected */ olcs.FeatureConverter.prototype.wrapFillAndOutlineGeometries = function(layer, feature, olGeometry, fillGeometry, outlineGeometry, olStyle) { - var fillColor = this.extractColorFromOlStyle(olStyle, false); - var outlineColor = this.extractColorFromOlStyle(olStyle, true); + const fillColor = this.extractColorFromOlStyle(olStyle, false); + const outlineColor = this.extractColorFromOlStyle(olStyle, true); - var primitives = new Cesium.PrimitiveCollection(); + const primitives = new Cesium.PrimitiveCollection(); if (olStyle.getFill()) { - var p1 = this.createColoredPrimitive(layer, feature, olGeometry, + const p1 = this.createColoredPrimitive(layer, feature, olGeometry, fillGeometry, fillColor); goog.asserts.assert(!!p1); primitives.add(p1); } if (olStyle.getStroke()) { - var width = this.extractLineWidthFromOlStyle(olStyle); - var p2 = this.createColoredPrimitive(layer, feature, olGeometry, + const width = this.extractLineWidthFromOlStyle(olStyle); + const p2 = this.createColoredPrimitive(layer, feature, olGeometry, outlineGeometry, outlineColor, width); if (p2) { // Some outline geometries are not supported by Cesium in clamp to ground @@ -238,7 +238,7 @@ olcs.FeatureConverter.prototype.wrapFillAndOutlineGeometries = function(layer, f * @protected */ olcs.FeatureConverter.prototype.addTextStyle = function(layer, feature, geometry, style, primitive) { - var primitives; + let primitives; if (!(primitive instanceof Cesium.PrimitiveCollection)) { primitives = new Cesium.PrimitiveCollection(); primitives.add(primitive); @@ -250,8 +250,8 @@ olcs.FeatureConverter.prototype.addTextStyle = function(layer, feature, geometry return primitives; } - var text = /** @type {!ol.style.Text} */ (style.getText()); - var label = this.olGeometry4326TextPartToCesium(layer, feature, geometry, + const text = /** @type {!ol.style.Text} */ (style.getText()); + const label = this.olGeometry4326TextPartToCesium(layer, feature, geometry, text); if (label) { primitives.add(label); @@ -273,7 +273,7 @@ olcs.FeatureConverter.prototype.addTextStyle = function(layer, feature, geometry * @api */ olcs.FeatureConverter.prototype.csAddBillboard = function(billboards, bbOptions, layer, feature, geometry, style) { - var bb = billboards.add(bbOptions); + const bb = billboards.add(bbOptions); this.setReferenceForPicking(layer, feature, bb); return bb; }; @@ -295,9 +295,9 @@ olcs.FeatureConverter.prototype.olCircleGeometryToCesium = function(layer, featu goog.asserts.assert(olGeometry.getType() == 'Circle'); // ol.Coordinate - var center = olGeometry.getCenter(); - var height = center.length == 3 ? center[2] : 0.0; - var point = center.slice(); + let center = olGeometry.getCenter(); + const height = center.length == 3 ? center[2] : 0.0; + let point = center.slice(); point[0] += olGeometry.getRadius(); // Cesium @@ -305,24 +305,24 @@ olcs.FeatureConverter.prototype.olCircleGeometryToCesium = function(layer, featu point = olcs.core.ol4326CoordinateToCesiumCartesian(point); // Accurate computation of straight distance - var radius = Cesium.Cartesian3.distance(center, point); + const radius = Cesium.Cartesian3.distance(center, point); - var fillGeometry = new Cesium.CircleGeometry({ + const fillGeometry = new Cesium.CircleGeometry({ // always update Cesium externs before adding a property - center: center, - radius: radius, - height: height + center, + radius, + height }); - var outlineGeometry = new Cesium.CircleOutlineGeometry({ + const outlineGeometry = new Cesium.CircleOutlineGeometry({ // always update Cesium externs before adding a property - center: center, - radius: radius, + center, + radius, extrudedHeight: height, - height: height + height }); - var primitives = this.wrapFillAndOutlineGeometries( + const primitives = this.wrapFillAndOutlineGeometries( layer, feature, olGeometry, fillGeometry, outlineGeometry, olStyle); return this.addTextStyle(layer, feature, olGeometry, olStyle, primitives); @@ -344,26 +344,26 @@ olcs.FeatureConverter.prototype.olLineStringGeometryToCesium = function(layer, f olGeometry = olcs.core.olGeometryCloneTo4326(olGeometry, projection); goog.asserts.assert(olGeometry.getType() == 'LineString'); - var positions = olcs.core.ol4326CoordinateArrayToCsCartesians( + const positions = olcs.core.ol4326CoordinateArrayToCsCartesians( olGeometry.getCoordinates()); - var appearance = new Cesium.PolylineMaterialAppearance({ + const appearance = new Cesium.PolylineMaterialAppearance({ // always update Cesium externs before adding a property material: this.olStyleToCesium(feature, olStyle, true) }); - var geometryOptions = { + const geometryOptions = { // always update Cesium externs before adding a property - positions: positions, + positions, width: this.extractLineWidthFromOlStyle(olStyle), vertexFormat: appearance.vertexFormat }; - var outlinePrimitive; - var heightReference = this.getHeightReference(layer, feature, olGeometry); + let outlinePrimitive; + const heightReference = this.getHeightReference(layer, feature, olGeometry); if (heightReference == Cesium.HeightReference.CLAMP_TO_GROUND) { - var color = this.extractColorFromOlStyle(olStyle, true); + const color = this.extractColorFromOlStyle(olStyle, true); outlinePrimitive = new Cesium.GroundPrimitive({ // always update Cesium externs before adding a property geometryInstances: new Cesium.GeometryInstance({ @@ -379,7 +379,7 @@ olcs.FeatureConverter.prototype.olLineStringGeometryToCesium = function(layer, f geometryInstances: new Cesium.GeometryInstance({ geometry: new Cesium.PolylineGeometry(geometryOptions) }), - appearance: appearance + appearance }); } @@ -405,20 +405,20 @@ olcs.FeatureConverter.prototype.olPolygonGeometryToCesium = function(layer, feat olGeometry = olcs.core.olGeometryCloneTo4326(olGeometry, projection); goog.asserts.assert(olGeometry.getType() == 'Polygon'); - var fillGeometry, outlineGeometry; + let fillGeometry, outlineGeometry; if ((olGeometry.getCoordinates()[0].length == 5) && (feature.getGeometry().get('olcs.polygon_kind') === 'rectangle')) { // Create a rectangle according to the longitude and latitude curves - var coordinates = olGeometry.getCoordinates()[0]; + const coordinates = olGeometry.getCoordinates()[0]; // Extract the West, South, East, North coordinates - var extent = ol.extent.boundingExtent(coordinates); - var rectangle = Cesium.Rectangle.fromDegrees(extent[0], extent[1], + const extent = ol.extent.boundingExtent(coordinates); + const rectangle = Cesium.Rectangle.fromDegrees(extent[0], extent[1], extent[2], extent[3]); // Extract the average height of the vertices - var maxHeight = 0.0; + let maxHeight = 0.0; if (coordinates[0].length == 3) { - for (var c = 0; c < coordinates.length; c++) { + for (let c = 0; c < coordinates.length; c++) { maxHeight = Math.max(maxHeight, coordinates[c][2]); } } @@ -426,25 +426,25 @@ olcs.FeatureConverter.prototype.olPolygonGeometryToCesium = function(layer, feat // Render the cartographic rectangle fillGeometry = new Cesium.RectangleGeometry({ ellipsoid: Cesium.Ellipsoid.WGS84, - rectangle: rectangle, + rectangle, height: maxHeight }); outlineGeometry = new Cesium.RectangleOutlineGeometry({ ellipsoid: Cesium.Ellipsoid.WGS84, - rectangle: rectangle, + rectangle, height: maxHeight }); } else { - var rings = olGeometry.getLinearRings(); + const rings = olGeometry.getLinearRings(); // always update Cesium externs before adding a property - var hierarchy = {}; - var polygonHierarchy = hierarchy; + const hierarchy = {}; + const polygonHierarchy = hierarchy; goog.asserts.assert(rings.length > 0); - for (var i = 0; i < rings.length; ++i) { - var olPos = rings[i].getCoordinates(); - var positions = olcs.core.ol4326CoordinateArrayToCsCartesians(olPos); + for (let i = 0; i < rings.length; ++i) { + const olPos = rings[i].getCoordinates(); + const positions = olcs.core.ol4326CoordinateArrayToCsCartesians(olPos); goog.asserts.assert(positions && positions.length > 0); if (i == 0) { hierarchy.positions = positions; @@ -453,14 +453,14 @@ olcs.FeatureConverter.prototype.olPolygonGeometryToCesium = function(layer, feat hierarchy.holes = []; } hierarchy.holes.push({ - positions: positions + positions }); } } fillGeometry = new Cesium.PolygonGeometry({ // always update Cesium externs before adding a property - polygonHierarchy: polygonHierarchy, + polygonHierarchy, perPositionHeight: true }); @@ -471,7 +471,7 @@ olcs.FeatureConverter.prototype.olPolygonGeometryToCesium = function(layer, feat }); } - var primitives = this.wrapFillAndOutlineGeometries( + const primitives = this.wrapFillAndOutlineGeometries( layer, feature, olGeometry, fillGeometry, outlineGeometry, olStyle); return this.addTextStyle(layer, feature, olGeometry, olStyle, primitives); @@ -488,7 +488,7 @@ olcs.FeatureConverter.prototype.olPolygonGeometryToCesium = function(layer, feat olcs.FeatureConverter.prototype.getHeightReference = function(layer, feature, geometry) { // Read from the geometry - var altitudeMode = geometry.get('altitudeMode'); + let altitudeMode = geometry.get('altitudeMode'); // Or from the feature if (altitudeMode === undefined) { @@ -500,7 +500,7 @@ olcs.FeatureConverter.prototype.getHeightReference = function(layer, feature, ge altitudeMode = layer.get('altitudeMode'); } - var heightReference = Cesium.HeightReference.NONE; + let heightReference = Cesium.HeightReference.NONE; if (altitudeMode === 'clampToGround') { heightReference = Cesium.HeightReference.CLAMP_TO_GROUND; } else if (altitudeMode === 'relativeToGround') { @@ -529,21 +529,21 @@ olcs.FeatureConverter.prototype.olPointGeometryToCesium = function(layer, featur goog.asserts.assert(olGeometry.getType() == 'Point'); olGeometry = olcs.core.olGeometryCloneTo4326(olGeometry, projection); - var imageStyle = style.getImage(); + const imageStyle = style.getImage(); if (imageStyle) { if (imageStyle instanceof ol.style.Icon) { // make sure the image is scheduled for load imageStyle.load(); } - var image = imageStyle.getImage(1); // get normal density - var isImageLoaded = function(image) { + const image = imageStyle.getImage(1); // get normal density + const isImageLoaded = function(image) { return image.src != '' && image.naturalHeight != 0 && image.naturalWidth != 0 && image.complete; }; - var reallyCreateBillboard = (function() { + const reallyCreateBillboard = (function() { if (!image) { return; } @@ -552,26 +552,26 @@ olcs.FeatureConverter.prototype.olPointGeometryToCesium = function(layer, featur image instanceof HTMLImageElement)) { return; } - var center = olGeometry.getCoordinates(); - var position = olcs.core.ol4326CoordinateToCesiumCartesian(center); - var color; - var opacity = imageStyle.getOpacity(); + const center = olGeometry.getCoordinates(); + const position = olcs.core.ol4326CoordinateToCesiumCartesian(center); + let color; + const opacity = imageStyle.getOpacity(); if (opacity !== undefined) { color = new Cesium.Color(1.0, 1.0, 1.0, opacity); } - var heightReference = this.getHeightReference(layer, feature, olGeometry); + const heightReference = this.getHeightReference(layer, feature, olGeometry); - var bbOptions = /** @type {Cesium.optionsBillboardCollectionAdd} */ ({ + const bbOptions = /** @type {Cesium.optionsBillboardCollectionAdd} */ ({ // always update Cesium externs before adding a property - image: image, - color: color, + image, + color, scale: imageStyle.getScale(), - heightReference: heightReference, + heightReference, verticalOrigin: Cesium.VerticalOrigin.BOTTOM, - position: position + position }); - var bb = this.csAddBillboard(billboards, bbOptions, layer, feature, + const bb = this.csAddBillboard(billboards, bbOptions, layer, feature, olGeometry, style); if (opt_newBillboardCallback) { opt_newBillboardCallback(bb); @@ -580,22 +580,22 @@ olcs.FeatureConverter.prototype.olPointGeometryToCesium = function(layer, featur if (image instanceof Image && !isImageLoaded(image)) { // Cesium requires the image to be loaded - var cancelled = false; - var source = layer.getSource(); + let cancelled = false; + let source = layer.getSource(); if (source instanceof ol.source.ImageVector) { source = source.getSource(); } - var canceller = function() { + const canceller = function() { cancelled = true; }; source.on(['removefeature', 'clear'], this.boundOnRemoveOrClearFeatureListener_); - var cancellers = olcs.util.obj(source)['olcs_cancellers']; + let cancellers = olcs.util.obj(source)['olcs_cancellers']; if (!cancellers) { cancellers = olcs.util.obj(source)['olcs_cancellers'] = {}; } - var fuid = ol.getUid(feature); + const fuid = ol.getUid(feature); if (cancellers[fuid]) { // When the feature change quickly, a canceller may still be present so // we cancel it here to prevent creation of a billboard. @@ -603,7 +603,7 @@ olcs.FeatureConverter.prototype.olPointGeometryToCesium = function(layer, featur } cancellers[fuid] = canceller; - var listener = function() { + const listener = function() { if (!billboards.isDestroyed() && !cancelled) { // Create billboard if the feature is still displayed on the map. reallyCreateBillboard(); @@ -644,36 +644,36 @@ olcs.FeatureConverter.prototype.olMultiGeometryToCesium = function(layer, featur // FIXME: would be better to combine all child geometries in one primitive // instead we create n primitives for simplicity. - var accumulate = function(geometries, functor) { - var primitives = new Cesium.PrimitiveCollection(); - geometries.forEach(function(geometry) { + const accumulate = function(geometries, functor) { + const primitives = new Cesium.PrimitiveCollection(); + geometries.forEach((geometry) => { primitives.add(functor(layer, feature, geometry, projection, olStyle)); }); return primitives; }; - var subgeos; + let subgeos; switch (geometry.getType()) { case 'MultiPoint': geometry = /** @type {!ol.geom.MultiPoint} */ (geometry); subgeos = geometry.getPoints(); if (olStyle.getText()) { - var primitives = new Cesium.PrimitiveCollection(); - subgeos.forEach(function(geometry) { + const primitives = new Cesium.PrimitiveCollection(); + subgeos.forEach((geometry) => { goog.asserts.assert(geometry); - var result = this.olPointGeometryToCesium(layer, feature, geometry, + const result = this.olPointGeometryToCesium(layer, feature, geometry, projection, olStyle, billboards, opt_newBillboardCallback); if (result) { primitives.add(result); } - }.bind(this)); + }); return primitives; } else { - subgeos.forEach(function(geometry) { + subgeos.forEach((geometry) => { goog.asserts.assert(geometry); this.olPointGeometryToCesium(layer, feature, geometry, projection, olStyle, billboards, opt_newBillboardCallback); - }.bind(this)); + }); return null; } case 'MultiLineString': @@ -685,7 +685,7 @@ olcs.FeatureConverter.prototype.olMultiGeometryToCesium = function(layer, featur subgeos = geometry.getPolygons(); return accumulate(subgeos, this.olPolygonGeometryToCesium.bind(this)); default: - goog.asserts.fail('Unhandled multi geometry type' + geometry.getType()); + goog.asserts.fail(`Unhandled multi geometry type${geometry.getType()}`); } }; @@ -700,19 +700,19 @@ olcs.FeatureConverter.prototype.olMultiGeometryToCesium = function(layer, featur * @api */ olcs.FeatureConverter.prototype.olGeometry4326TextPartToCesium = function(layer, feature, geometry, style) { - var text = style.getText(); + const text = style.getText(); goog.asserts.assert(text !== undefined); - var labels = new Cesium.LabelCollection({scene: this.scene}); + const labels = new Cesium.LabelCollection({scene: this.scene}); // TODO: export and use the text draw position from OpenLayers . // See src/ol/render/vector.js - var extentCenter = ol.extent.getCenter(geometry.getExtent()); + const extentCenter = ol.extent.getCenter(geometry.getExtent()); if (geometry instanceof ol.geom.SimpleGeometry) { - var first = geometry.getFirstCoordinate(); + const first = geometry.getFirstCoordinate(); extentCenter[2] = first.length == 3 ? first[2] : 0.0; } - var options = /** @type {Cesium.optionsLabelCollection} */ ({}); + const options = /** @type {Cesium.optionsLabelCollection} */ ({}); options.position = olcs.core.ol4326CoordinateToCesiumCartesian(extentCenter); @@ -720,19 +720,19 @@ olcs.FeatureConverter.prototype.olGeometry4326TextPartToCesium = function(layer, options.heightReference = this.getHeightReference(layer, feature, geometry); - var offsetX = style.getOffsetX(); - var offsetY = style.getOffsetY(); + const offsetX = style.getOffsetX(); + const offsetY = style.getOffsetY(); if (offsetX != 0 && offsetY != 0) { - var offset = new Cesium.Cartesian2(offsetX, offsetY); + const offset = new Cesium.Cartesian2(offsetX, offsetY); options.pixelOffset = offset; } - var font = style.getFont(); + const font = style.getFont(); if (font !== undefined) { options.font = font; } - var labelStyle = undefined; + let labelStyle = undefined; if (style.getFill()) { options.fillColor = this.extractColorFromOlStyle(style, false); labelStyle = Cesium.LabelStyle.FILL; @@ -747,7 +747,7 @@ olcs.FeatureConverter.prototype.olGeometry4326TextPartToCesium = function(layer, } options.style = labelStyle; - var horizontalOrigin; + let horizontalOrigin; switch (style.getTextAlign()) { case 'left': horizontalOrigin = Cesium.HorizontalOrigin.LEFT; @@ -762,7 +762,7 @@ olcs.FeatureConverter.prototype.olGeometry4326TextPartToCesium = function(layer, options.horizontalOrigin = horizontalOrigin; if (style.getTextBaseline()) { - var verticalOrigin; + let verticalOrigin; switch (style.getTextBaseline()) { case 'top': verticalOrigin = Cesium.VerticalOrigin.TOP; @@ -780,13 +780,13 @@ olcs.FeatureConverter.prototype.olGeometry4326TextPartToCesium = function(layer, verticalOrigin = Cesium.VerticalOrigin.BOTTOM; break; default: - goog.asserts.fail('unhandled baseline ' + style.getTextBaseline()); + goog.asserts.fail(`unhandled baseline ${style.getTextBaseline()}`); } options.verticalOrigin = verticalOrigin; } - var l = labels.add(options); + const l = labels.add(options); this.setReferenceForPicking(layer, feature, l); return labels; }; @@ -801,13 +801,13 @@ olcs.FeatureConverter.prototype.olGeometry4326TextPartToCesium = function(layer, * @api */ olcs.FeatureConverter.prototype.olStyleToCesium = function(feature, style, outline) { - var fill = style.getFill(); - var stroke = style.getStroke(); + const fill = style.getFill(); + const stroke = style.getStroke(); if ((outline && !stroke) || (!outline && !fill)) { return null; // FIXME use a default style? Developer error? } - var color = outline ? stroke.getColor() : fill.getColor(); + let color = outline ? stroke.getColor() : fill.getColor(); color = olcs.core.convertColorToCesium(color); if (outline && stroke.getLineDash()) { @@ -821,7 +821,7 @@ olcs.FeatureConverter.prototype.olStyleToCesium = function(feature, style, outli } else { return Cesium.Material.fromType('Color', { // always update Cesium externs before adding a property - color: color + color }); } @@ -842,12 +842,12 @@ olcs.FeatureConverter.prototype.computePlainStyle = function(layer, feature, fal /** * @type {ol.FeatureStyleFunction|undefined} */ - var featureStyleFunction = feature.getStyleFunction(); + const featureStyleFunction = feature.getStyleFunction(); /** * @type {ol.style.Style|Array.} */ - var style = null; + let style = null; if (featureStyleFunction) { style = featureStyleFunction.call(feature, resolution); @@ -881,37 +881,37 @@ olcs.FeatureConverter.prototype.computePlainStyle = function(layer, feature, fal * @api */ olcs.FeatureConverter.prototype.olFeatureToCesium = function(layer, feature, style, context, opt_geom) { - var geom = opt_geom || feature.getGeometry(); - var proj = context.projection; + let geom = opt_geom || feature.getGeometry(); + const proj = context.projection; if (!geom) { // OpenLayers features may not have a geometry // See http://geojson.org/geojson-spec.html#feature-objects return null; } - var newBillboardAddedCallback = function(bb) { + const newBillboardAddedCallback = function(bb) { context.featureToCesiumMap[ol.getUid(feature)] = bb; }; switch (geom.getType()) { case 'GeometryCollection': - var primitives = new Cesium.PrimitiveCollection(); - var collection = /** @type {!ol.geom.GeometryCollection} */ (geom); + const primitives = new Cesium.PrimitiveCollection(); + const collection = /** @type {!ol.geom.GeometryCollection} */ (geom); // TODO: use getGeometriesArray() instead - collection.getGeometries().forEach(function(geom) { + collection.getGeometries().forEach((geom) => { if (geom) { - var prims = this.olFeatureToCesium(layer, feature, style, context, + const prims = this.olFeatureToCesium(layer, feature, style, context, geom); if (prims) { primitives.add(prims); } } - }.bind(this)); + }); return primitives; case 'Point': geom = /** @type {!ol.geom.Point} */ (geom); - var bbs = context.billboards; - var result = this.olPointGeometryToCesium(layer, feature, geom, proj, + const bbs = context.billboards; + const result = this.olPointGeometryToCesium(layer, feature, geom, proj, style, bbs, newBillboardAddedCallback); if (!result) { // no wrapping primitive @@ -934,7 +934,7 @@ olcs.FeatureConverter.prototype.olFeatureToCesium = function(layer, feature, sty case 'MultiPoint': case 'MultiLineString': case 'MultiPolygon': - var result2 = this.olMultiGeometryToCesium(layer, feature, geom, proj, + const result2 = this.olMultiGeometryToCesium(layer, feature, geom, proj, style, context.billboards, newBillboardAddedCallback); if (!result2) { // no wrapping primitive @@ -945,7 +945,7 @@ olcs.FeatureConverter.prototype.olFeatureToCesium = function(layer, feature, sty case 'LinearRing': throw new Error('LinearRing should only be part of polygon.'); default: - throw new Error('Ol geom type not handled : ' + geom.getType()); + throw new Error(`Ol geom type not handled : ${geom.getType()}`); } }; @@ -961,8 +961,8 @@ olcs.FeatureConverter.prototype.olFeatureToCesium = function(layer, feature, sty * @api */ olcs.FeatureConverter.prototype.olVectorLayerToCesium = function(olLayer, olView, featurePrimitiveMap) { - var proj = olView.getProjection(); - var resolution = olView.getResolution(); + const proj = olView.getProjection(); + const resolution = olView.getResolution(); if (resolution === undefined || !proj) { goog.asserts.fail('View not ready'); @@ -971,7 +971,7 @@ olcs.FeatureConverter.prototype.olVectorLayerToCesium = function(olLayer, olView throw new Error('View not ready'); } - var source = olLayer.getSource(); + let source = olLayer.getSource(); if (olLayer instanceof ol.layer.Image) { if (source instanceof ol.source.ImageVector) { source = source.getSource(); @@ -982,32 +982,32 @@ olcs.FeatureConverter.prototype.olVectorLayerToCesium = function(olLayer, olView } goog.asserts.assertInstanceof(source, ol.source.Vector); - var features = source.getFeatures(); - var counterpart = new olcs.core.VectorLayerCounterpart(proj, this.scene); - var context = counterpart.context; - for (var i = 0; i < features.length; ++i) { - var feature = features[i]; + const features = source.getFeatures(); + const counterpart = new olcs.core.VectorLayerCounterpart(proj, this.scene); + const context = counterpart.context; + for (let i = 0; i < features.length; ++i) { + const feature = features[i]; if (!feature) { continue; } /** * @type {ol.StyleFunction|undefined} */ - var layerStyle; + let layerStyle; if (olLayer instanceof ol.layer.Image) { - var imageSource = olLayer.getSource(); + const imageSource = olLayer.getSource(); goog.asserts.assertInstanceof(imageSource, ol.source.ImageVector); layerStyle = imageSource.getStyleFunction(); } else { layerStyle = olLayer.getStyleFunction(); } - var style = this.computePlainStyle(olLayer, feature, layerStyle, + const style = this.computePlainStyle(olLayer, feature, layerStyle, resolution); if (!style) { // only 'render' features with a style continue; } - var primitives = this.olFeatureToCesium(olLayer, feature, style, context); + const primitives = this.olFeatureToCesium(olLayer, feature, style, context); if (!primitives) { continue; } @@ -1029,8 +1029,8 @@ olcs.FeatureConverter.prototype.olVectorLayerToCesium = function(olLayer, olView * @api */ olcs.FeatureConverter.prototype.convert = function(layer, view, feature, context) { - var proj = view.getProjection(); - var resolution = view.getResolution(); + const proj = view.getProjection(); + const resolution = view.getResolution(); if (resolution == undefined || !proj) { return null; @@ -1039,9 +1039,9 @@ olcs.FeatureConverter.prototype.convert = function(layer, view, feature, context /** * @type {ol.StyleFunction|undefined} */ - var layerStyle; + let layerStyle; if (layer instanceof ol.layer.Image) { - var imageSource = layer.getSource(); + const imageSource = layer.getSource(); if (imageSource instanceof ol.source.ImageVector) { layerStyle = imageSource.getStyleFunction(); } else { @@ -1050,7 +1050,7 @@ olcs.FeatureConverter.prototype.convert = function(layer, view, feature, context } else { layerStyle = layer.getStyleFunction(); } - var style = this.computePlainStyle(layer, feature, layerStyle, resolution); + const style = this.computePlainStyle(layer, feature, layerStyle, resolution); if (!style) { // only 'render' features with a style diff --git a/src/olcesium.js b/src/olcesium.js index ad55948ed..14a020e24 100644 --- a/src/olcesium.js +++ b/src/olcesium.js @@ -70,25 +70,25 @@ olcs.OLCesium = function(options) { */ this.resolutionScaleChanged_ = true; // force resize - var fillArea = 'position:absolute;top:0;left:0;width:100%;height:100%;'; + const fillArea = 'position:absolute;top:0;left:0;width:100%;height:100%;'; /** * @type {!Element} * @private */ this.container_ = document.createElement('DIV'); - var containerAttribute = document.createAttribute('style'); - containerAttribute.value = fillArea + 'visibility:hidden;'; + const containerAttribute = document.createAttribute('style'); + containerAttribute.value = `${fillArea}visibility:hidden;`; this.container_.setAttributeNode(containerAttribute); - var targetElement = options.target || null; + let targetElement = options.target || null; if (targetElement) { if (typeof targetElement === 'string') { targetElement = document.getElementById(targetElement); } targetElement.appendChild(this.container_); } else { - var oc = this.map_.getViewport().querySelector('.ol-overlaycontainer'); + const oc = this.map_.getViewport().querySelector('.ol-overlaycontainer'); if (oc && oc.parentNode) { oc.parentNode.insertBefore(this.container_, oc); } @@ -107,7 +107,7 @@ olcs.OLCesium = function(options) { */ this.canvas_ = /** @type {!HTMLCanvasElement} */ ( document.createElement('CANVAS')); - var canvasAttribute = document.createAttribute('style'); + const canvasAttribute = document.createAttribute('style'); canvasAttribute.value = fillArea; this.canvas_.setAttributeNode(canvasAttribute); @@ -139,7 +139,7 @@ olcs.OLCesium = function(options) { */ this.hiddenRootGroup_ = null; - var sceneOptions = options.sceneOptions !== undefined ? options.sceneOptions : + const sceneOptions = options.sceneOptions !== undefined ? options.sceneOptions : /** @type {Cesium.SceneOptions} */ ({}); sceneOptions.canvas = this.canvas_; sceneOptions.scene3DOnly = true; @@ -150,7 +150,7 @@ olcs.OLCesium = function(options) { */ this.scene_ = new Cesium.Scene(sceneOptions); - var sscc = this.scene_.screenSpaceCameraController; + const sscc = this.scene_.screenSpaceCameraController; sscc.tiltEventTypes.push({ 'eventType': Cesium.CameraEventType.LEFT_DRAG, @@ -187,7 +187,7 @@ olcs.OLCesium = function(options) { dataSourceCollection: this.dataSourceCollection_ }); - var synchronizers = options.createSynchronizers ? + const synchronizers = options.createSynchronizers ? options.createSynchronizers(this.map_, this.scene_, this.dataSourceCollection_) : [ new olcs.RasterSynchronizer(this.map_, this.scene_), new olcs.VectorSynchronizer(this.map_, this.scene_) @@ -196,13 +196,13 @@ olcs.OLCesium = function(options) { // Assures correct canvas size after initialisation this.handleResize_(); - for (var i = synchronizers.length - 1; i >= 0; --i) { + for (let i = synchronizers.length - 1; i >= 0; --i) { synchronizers[i].synchronize(); } if (this.isOverMap_) { // if in "stacked mode", hide everything except canvas (including credits) - var credits = this.canvas_.nextElementSibling; + const credits = this.canvas_.nextElementSibling; if (credits) { credits.style.display = 'none'; } @@ -272,7 +272,7 @@ olcs.OLCesium = function(options) { */ this.boundingSphereScratch_ = new Cesium.BoundingSphere(); - var eventHelper = new Cesium.EventHelper(); + const eventHelper = new Cesium.EventHelper(); eventHelper.add(this.scene_.postRender, olcs.OLCesium.prototype.updateTrackedEntity_, this); }; @@ -285,7 +285,7 @@ Object.defineProperties(olcs.OLCesium.prototype, { 'set': /** @this {olcs.OLCesium} */ function(feature) { if (this.trackedFeature_ !== feature) { - var scene = this.scene_; + const scene = this.scene_; //Stop tracking if (!feature || !feature.getGeometry()) { @@ -308,21 +308,21 @@ Object.defineProperties(olcs.OLCesium.prototype, { //when the bounding sphere is ready (most likely next frame). this.needTrackedEntityUpdate_ = true; - var to4326Transform = this.to4326Transform_; - var toCesiumPosition = function() { - var geometry = feature.getGeometry(); + const to4326Transform = this.to4326Transform_; + const toCesiumPosition = function() { + const geometry = feature.getGeometry(); goog.asserts.assertInstanceof(geometry, ol.geom.Point); - var coo = geometry.getCoordinates(); - var coo4326 = to4326Transform(coo, undefined, coo.length); + const coo = geometry.getCoordinates(); + const coo4326 = to4326Transform(coo, undefined, coo.length); return olcs.core.ol4326CoordinateToCesiumCartesian(coo4326); }; // Create an invisible point entity for tracking. // It is independant from the primitive/geometry created by the vector synchronizer. - var options = { - 'position': new Cesium.CallbackProperty(function(time, result) { - return toCesiumPosition(); - }, false), + const options = { + 'position': new Cesium.CallbackProperty((time, result) => + toCesiumPosition() + , false), 'point': { 'pixelSize': 1, 'color': Cesium.Color.TRANSPARENT @@ -363,8 +363,8 @@ olcs.OLCesium.prototype.onAnimationFrame_ = function(frameTime) { this.renderId_ = undefined; // check if a frame was rendered within the target frame rate - var interval = 1000.0 / this.targetFrameRate_; - var delta = frameTime - this.lastFrameTime_; + const interval = 1000.0 / this.targetFrameRate_; + const delta = frameTime - this.lastFrameTime_; if (delta < interval) { // too soon, don't render yet this.render_(); @@ -374,15 +374,15 @@ olcs.OLCesium.prototype.onAnimationFrame_ = function(frameTime) { // time to render a frame, save the time this.lastFrameTime_ = frameTime; - var julianDate = this.time_(); + const julianDate = this.time_(); this.scene_.initializeFrame(); this.handleResize_(); this.dataSourceDisplay_.update(julianDate); // Update tracked entity if (this.entityView_) { - var trackedEntity = this.trackedEntity_; - var trackedState = this.dataSourceDisplay_.getBoundingSphere(trackedEntity, false, this.boundingSphereScratch_); + const trackedEntity = this.trackedEntity_; + const trackedState = this.dataSourceDisplay_.getBoundingSphere(trackedEntity, false, this.boundingSphereScratch_); if (trackedState === Cesium.BoundingSphereState.DONE) { this.boundingSphereScratch_.radius = 1; // a radius of 1 is enough for tracking points this.entityView_.update(julianDate, this.boundingSphereScratch_); @@ -405,17 +405,17 @@ olcs.OLCesium.prototype.updateTrackedEntity_ = function() { return; } - var trackedEntity = this.trackedEntity_; - var scene = this.scene_; + const trackedEntity = this.trackedEntity_; + const scene = this.scene_; - var state = this.dataSourceDisplay_.getBoundingSphere(trackedEntity, false, this.boundingSphereScratch_); + const state = this.dataSourceDisplay_.getBoundingSphere(trackedEntity, false, this.boundingSphereScratch_); if (state === Cesium.BoundingSphereState.PENDING) { return; } scene.screenSpaceCameraController.enableTilt = false; - var bs = state !== Cesium.BoundingSphereState.FAILED ? this.boundingSphereScratch_ : undefined; + const bs = state !== Cesium.BoundingSphereState.FAILED ? this.boundingSphereScratch_ : undefined; if (bs) { bs.radius = 1; } @@ -429,8 +429,8 @@ olcs.OLCesium.prototype.updateTrackedEntity_ = function() { * @private */ olcs.OLCesium.prototype.handleResize_ = function() { - var width = this.canvas_.clientWidth; - var height = this.canvas_.clientHeight; + let width = this.canvas_.clientWidth; + let height = this.canvas_.clientHeight; if (width === 0 | height === 0) { // The canvas DOM element is not ready yet. @@ -443,7 +443,7 @@ olcs.OLCesium.prototype.handleResize_ = function() { return; } - var resolutionScale = this.resolutionScale_; + let resolutionScale = this.resolutionScale_; if (!olcs.util.supportsImageRenderingPixelated()) { resolutionScale *= window.devicePixelRatio || 1.0; } @@ -530,7 +530,7 @@ olcs.OLCesium.prototype.setEnabled = function(enable) { // some Cesium operations are operating with canvas.clientWidth, // so we can't remove it from DOM or even make display:none; this.container_.style.visibility = this.enabled_ ? 'visible' : 'hidden'; - var interactions; + let interactions; if (this.enabled_) { this.throwOnUnitializedMap_(); if (this.isOverMap_) { @@ -540,7 +540,7 @@ olcs.OLCesium.prototype.setEnabled = function(enable) { }, this); interactions.clear(); - var rootGroup = this.map_.getLayerGroup(); + const rootGroup = this.map_.getLayerGroup(); if (rootGroup.getVisible()) { this.hiddenRootGroup_ = rootGroup; this.hiddenRootGroup_.setVisible(false); @@ -551,7 +551,7 @@ olcs.OLCesium.prototype.setEnabled = function(enable) { } else { if (this.isOverMap_) { interactions = this.map_.getInteractions(); - this.pausedInteractions_.forEach(function(interaction) { + this.pausedInteractions_.forEach((interaction) => { interactions.push(interaction); }); this.pausedInteractions_.length = 0; @@ -580,9 +580,9 @@ olcs.OLCesium.prototype.warmUp = function(height, timeout) { } this.throwOnUnitializedMap_(); this.camera_.readFromView(); - var ellipsoid = this.globe_.ellipsoid; - var csCamera = this.scene_.camera; - var position = ellipsoid.cartesianToCartographic(csCamera.position); + const ellipsoid = this.globe_.ellipsoid; + const csCamera = this.scene_.camera; + const position = ellipsoid.cartesianToCartographic(csCamera.position); if (position.height < height) { position.height = height; csCamera.position = ellipsoid.cartographicToCartesian(position); @@ -591,9 +591,9 @@ olcs.OLCesium.prototype.warmUp = function(height, timeout) { this.warmingUp_ = true; this.render_(); - setTimeout((function() { + setTimeout(() => { this.warmingUp_ = false; - }).bind(this), timeout); + }, timeout); }; @@ -684,11 +684,10 @@ olcs.OLCesium.prototype.setTargetFrameRate = function(value) { * @private */ olcs.OLCesium.prototype.throwOnUnitializedMap_ = function() { - var map = this.map_; - var view = map.getView(); - var center = view.getCenter(); + const map = this.map_; + const view = map.getView(); + const center = view.getCenter(); if (!view.isDef() || isNaN(center[0]) || isNaN(center[1])) { - throw new Error('The OpenLayers map is not properly initialized: ' + - center + ' / ' + view.getResolution()); + throw new Error(`The OpenLayers map is not properly initialized: ${center} / ${view.getResolution()}`); } }; diff --git a/src/olcs.js b/src/olcs.js index 4cab0fad9..66843e415 100644 --- a/src/olcs.js +++ b/src/olcs.js @@ -30,13 +30,13 @@ olcs.util.imageRenderingValueResult_ = undefined; */ olcs.util.supportsImageRenderingPixelated = function() { if (olcs.util.supportsImageRenderingPixelatedResult_ === undefined) { - var canvas = document.createElement('canvas'); + const canvas = document.createElement('canvas'); canvas.setAttribute('style', 'image-rendering: -moz-crisp-edges;' + 'image-rendering: pixelated;'); // canvas.style.imageRendering will be undefined, null or an // empty string on unsupported browsers. - var tmp = canvas.style['imageRendering']; // non standard + const tmp = canvas.style['imageRendering']; // non standard olcs.util.supportsImageRenderingPixelatedResult_ = !!tmp; if (olcs.util.supportsImageRenderingPixelatedResult_) { olcs.util.imageRenderingValueResult_ = tmp; diff --git a/src/rastersynchronizer.js b/src/rastersynchronizer.js index 6c7ddcaee..a44b71572 100644 --- a/src/rastersynchronizer.js +++ b/src/rastersynchronizer.js @@ -66,7 +66,7 @@ olcs.RasterSynchronizer.prototype.removeSingleCesiumObject = function(object, de * @inheritDoc */ olcs.RasterSynchronizer.prototype.removeAllCesiumObjects = function(destroy) { - for (var i = 0; i < this.ourLayers_.length; ++i) { + for (let i = 0; i < this.ourLayers_.length; ++i) { this.cesiumLayers_.remove(this.ourLayers_.get(i), destroy); } this.ourLayers_.removeAll(false); @@ -85,7 +85,7 @@ olcs.RasterSynchronizer.prototype.removeAllCesiumObjects = function(destroy) { * @protected */ olcs.RasterSynchronizer.prototype.convertLayerToCesiumImageries = function(olLayer, viewProj) { - var result = olcs.core.tileLayerToImageryLayer(olLayer, viewProj); + const result = olcs.core.tileLayerToImageryLayer(olLayer, viewProj); return result ? [result] : null; }; @@ -94,26 +94,26 @@ olcs.RasterSynchronizer.prototype.convertLayerToCesiumImageries = function(olLay * @inheritDoc */ olcs.RasterSynchronizer.prototype.createSingleLayerCounterparts = function(olLayer) { - var viewProj = this.view.getProjection(); - var cesiumObjects = this.convertLayerToCesiumImageries(olLayer, viewProj); + const viewProj = this.view.getProjection(); + const cesiumObjects = this.convertLayerToCesiumImageries(olLayer, viewProj); if (cesiumObjects) { olLayer.on(['change:opacity', 'change:visible'], - function(e) { + (e) => { // the compiler does not seem to be able to infer this goog.asserts.assert(cesiumObjects); - for (var i = 0; i < cesiumObjects.length; ++i) { + for (let i = 0; i < cesiumObjects.length; ++i) { olcs.core.updateCesiumLayerProperties(olLayer, cesiumObjects[i]); } }); - for (var i = 0; i < cesiumObjects.length; ++i) { + for (let i = 0; i < cesiumObjects.length; ++i) { olcs.core.updateCesiumLayerProperties(olLayer, cesiumObjects[i]); } // there is no way to modify Cesium layer extent, // we have to recreate when OpenLayers layer extent changes: olLayer.on('change:extent', function(e) { - for (var i = 0; i < cesiumObjects.length; ++i) { + for (let i = 0; i < cesiumObjects.length; ++i) { this.cesiumLayers_.remove(cesiumObjects[i], true); // destroy this.ourLayers_.remove(cesiumObjects[i], false); } @@ -123,8 +123,8 @@ olcs.RasterSynchronizer.prototype.createSingleLayerCounterparts = function(olLay olLayer.on('change', function(e) { // when the source changes, re-add the layer to force update - for (var i = 0; i < cesiumObjects.length; ++i) { - var position = this.cesiumLayers_.indexOf(cesiumObjects[i]); + for (let i = 0; i < cesiumObjects.length; ++i) { + const position = this.cesiumLayers_.indexOf(cesiumObjects[i]); if (position >= 0) { this.cesiumLayers_.remove(cesiumObjects[i], false); this.cesiumLayers_.add(cesiumObjects[i], position); @@ -144,31 +144,31 @@ olcs.RasterSynchronizer.prototype.createSingleLayerCounterparts = function(olLay * @protected */ olcs.RasterSynchronizer.prototype.orderLayers = function() { - var layers = []; - var zIndices = {}; - var queue = [this.mapLayerGroup]; + const layers = []; + const zIndices = {}; + const queue = [this.mapLayerGroup]; while (queue.length > 0) { - var olLayer = queue.splice(0, 1)[0]; + const olLayer = queue.splice(0, 1)[0]; layers.push(olLayer); zIndices[ol.getUid(olLayer)] = olLayer.getZIndex(); if (olLayer instanceof ol.layer.Group) { - var sublayers = olLayer.getLayers(); + const sublayers = olLayer.getLayers(); if (sublayers) { // Prepend queue with sublayers in order - queue.unshift.apply(queue, sublayers.getArray()); + queue.unshift(...sublayers.getArray()); } } } - ol.array.stableSort(layers, function(layer1, layer2) { - return zIndices[ol.getUid(layer1)] - zIndices[ol.getUid(layer2)]; - }); + ol.array.stableSort(layers, (layer1, layer2) => + zIndices[ol.getUid(layer1)] - zIndices[ol.getUid(layer2)] + ); layers.forEach(function(olLayer) { - var olLayerId = ol.getUid(olLayer).toString(); - var cesiumObjects = this.layerMap[olLayerId]; + const olLayerId = ol.getUid(olLayer).toString(); + const cesiumObjects = this.layerMap[olLayerId]; if (cesiumObjects) { cesiumObjects.forEach(this.raiseToTop, this); } diff --git a/src/vectorsynchronizer.js b/src/vectorsynchronizer.js index 3f9557c0e..7b1ec38c4 100644 --- a/src/vectorsynchronizer.js +++ b/src/vectorsynchronizer.js @@ -75,7 +75,7 @@ olcs.VectorSynchronizer.prototype.removeSingleCesiumObject = function(object, de olcs.VectorSynchronizer.prototype.removeAllCesiumObjects = function(destroy) { this.csAllPrimitives_.destroyPrimitives = destroy; if (destroy) { - for (var i = 0; i < this.csAllPrimitives_.length; ++i) { + for (let i = 0; i < this.csAllPrimitives_.length; ++i) { this.csAllPrimitives_.get(i)['counterpart'].destroy(); } } @@ -95,7 +95,7 @@ olcs.VectorSynchronizer.prototype.createSingleLayerCounterparts = function(olLay } goog.asserts.assertInstanceof(olLayer, ol.layer.Layer); - var source = olLayer.getSource(); + let source = olLayer.getSource(); if (source instanceof ol.source.ImageVector) { source = source.getSource(); } @@ -103,62 +103,62 @@ olcs.VectorSynchronizer.prototype.createSingleLayerCounterparts = function(olLay goog.asserts.assertInstanceof(source, ol.source.Vector); goog.asserts.assert(this.view); - var view = this.view; - var featurePrimitiveMap = {}; - var counterpart = this.converter.olVectorLayerToCesium(olLayer, view, + const view = this.view; + const featurePrimitiveMap = {}; + const counterpart = this.converter.olVectorLayerToCesium(olLayer, view, featurePrimitiveMap); - var csPrimitives = counterpart.getRootPrimitive(); - var olListenKeys = counterpart.olListenKeys; + const csPrimitives = counterpart.getRootPrimitive(); + const olListenKeys = counterpart.olListenKeys; csPrimitives.show = olLayer.getVisible(); - olListenKeys.push(ol.events.listen(olLayer, 'change:visible', function(e) { + olListenKeys.push(ol.events.listen(olLayer, 'change:visible', (e) => { csPrimitives.show = olLayer.getVisible(); })); - var onAddFeature = (function(feature) { + const onAddFeature = (function(feature) { goog.asserts.assert( (olLayer instanceof ol.layer.Vector) || (olLayer instanceof ol.layer.Image) ); - var context = counterpart.context; - var prim = this.converter.convert(olLayer, view, feature, context); + const context = counterpart.context; + const prim = this.converter.convert(olLayer, view, feature, context); if (prim) { featurePrimitiveMap[ol.getUid(feature)] = prim; csPrimitives.add(prim); } }).bind(this); - var onRemoveFeature = (function(feature) { - var geometry = feature.getGeometry(); - var id = ol.getUid(feature); + const onRemoveFeature = (function(feature) { + const geometry = feature.getGeometry(); + const id = ol.getUid(feature); if (!geometry || geometry.getType() == 'Point') { - var context = counterpart.context; - var bb = context.featureToCesiumMap[id]; + const context = counterpart.context; + const bb = context.featureToCesiumMap[id]; delete context.featureToCesiumMap[id]; if (bb instanceof Cesium.Billboard) { context.billboards.remove(bb); } } - var csPrimitive = featurePrimitiveMap[id]; + const csPrimitive = featurePrimitiveMap[id]; delete featurePrimitiveMap[id]; if (csPrimitive) { csPrimitives.remove(csPrimitive); } }).bind(this); - olListenKeys.push(ol.events.listen(source, 'addfeature', function(e) { + olListenKeys.push(ol.events.listen(source, 'addfeature', (e) => { goog.asserts.assert(e.feature); onAddFeature(e.feature); }, this)); - olListenKeys.push(ol.events.listen(source, 'removefeature', function(e) { + olListenKeys.push(ol.events.listen(source, 'removefeature', (e) => { goog.asserts.assert(e.feature); onRemoveFeature(e.feature); }, this)); - olListenKeys.push(ol.events.listen(source, 'changefeature', function(e) { - var feature = e.feature; + olListenKeys.push(ol.events.listen(source, 'changefeature', (e) => { + const feature = e.feature; goog.asserts.assert(feature); onRemoveFeature(feature); onAddFeature(feature);