From ad62739a6e9e49e9676038b430537d4bc23ae392 Mon Sep 17 00:00:00 2001 From: Tim Schaub Date: Thu, 11 Jan 2018 23:32:36 -0700 Subject: [PATCH 1/2] Use blocked scoped variables In addition to using const and let, this also upgrades our linter config and removes lint (mostly whitespace). --- examples/accessible.js | 10 +- examples/animation.js | 36 +- examples/arcgis-image.js | 6 +- examples/arcgis-tiled.js | 6 +- examples/attributions.js | 6 +- examples/bing-maps.js | 14 +- examples/blend-modes.js | 28 +- examples/box-selection.js | 16 +- examples/button-title.js | 2 +- examples/canvas-gradient-pattern.js | 26 +- examples/canvas-tiles.js | 4 +- examples/cartodb.js | 6 +- examples/center.js | 42 +- examples/cluster.js | 28 +- examples/color-manipulation.js | 80 +- examples/custom-controls.js | 14 +- examples/custom-interactions.js | 44 +- examples/d3.js | 48 +- examples/device-orientation.js | 16 +- examples/drag-and-drop-image-vector.js | 22 +- examples/drag-and-drop.js | 22 +- examples/drag-rotate-and-zoom.js | 2 +- examples/draw-and-modify-features.js | 14 +- examples/draw-features.js | 14 +- examples/draw-freehand.js | 14 +- examples/draw-shapes.js | 42 +- examples/dynamic-data.js | 36 +- examples/earthquake-clusters.js | 55 +- examples/earthquake-custom-symbol.js | 32 +- examples/epsg-4326.js | 4 +- examples/export-map.js | 4 +- examples/export-pdf.js | 48 +- examples/extent-interaction.js | 6 +- examples/feature-animation.js | 37 +- examples/feature-move-animation.js | 50 +- examples/flight-animation.js | 108 +- examples/fractal.js | 64 +- examples/full-screen-drag-rotate-and-zoom.js | 2 +- examples/full-screen-source.js | 4 +- examples/full-screen.js | 4 +- examples/geojson-vt.js | 36 +- examples/geojson.js | 14 +- examples/geolocation-orientation.js | 78 +- examples/geolocation.js | 14 +- examples/getfeatureinfo-image.js | 20 +- examples/getfeatureinfo-layers.js | 6 +- examples/getfeatureinfo-tile.js | 20 +- examples/gpx.js | 18 +- examples/graticule.js | 4 +- examples/heatmap-earthquakes.js | 14 +- examples/here-maps.js | 32 +- examples/hit-tolerance.js | 26 +- examples/icon-color.js | 14 +- examples/icon-negative.js | 20 +- examples/icon-sprite-webgl.js | 44 +- examples/icon.js | 30 +- examples/igc.js | 68 +- examples/image-filter.js | 60 +- examples/image-load-events.js | 12 +- examples/image-vector-layer.js | 16 +- examples/jsts.js | 22 +- examples/kml-earthquakes.js | 30 +- examples/kml-timezones.js | 38 +- examples/kml.js | 16 +- examples/layer-clipping-webgl.js | 28 +- examples/layer-clipping.js | 12 +- examples/layer-extent.js | 10 +- examples/layer-group.js | 6 +- examples/layer-spy.js | 22 +- examples/layer-swipe.js | 14 +- examples/layer-z-index.js | 22 +- examples/lazy-source.js | 6 +- examples/line-arrows.js | 20 +- examples/localized-openstreetmap.js | 6 +- examples/magnify.js | 52 +- examples/mapbox-vector-tiles-advanced.js | 18 +- examples/mapbox-vector-tiles.js | 4 +- examples/mapguide-untiled.js | 8 +- examples/measure.js | 106 +- examples/min-max-resolution.js | 2 +- examples/min-zoom.js | 12 +- examples/mobile-full-screen.js | 6 +- examples/modify-features.js | 10 +- examples/modify-test.js | 22 +- examples/mouse-position.js | 10 +- examples/mousewheel-zoom.js | 2 +- examples/moveend.js | 12 +- examples/navigation-controls.js | 2 +- examples/osm-vector-tiles.js | 26 +- examples/overlay.js | 18 +- examples/overviewmap-custom.js | 4 +- examples/overviewmap.js | 2 +- examples/permalink.js | 24 +- examples/pinch-zoom.js | 2 +- examples/polygon-styles.js | 12 +- examples/popup.js | 14 +- examples/preload.js | 6 +- examples/raster.js | 74 +- examples/region-growing.js | 64 +- examples/regularshape.js | 24 +- examples/render-geometry.js | 10 +- examples/reprojection-by-code.js | 36 +- examples/reprojection-image.js | 4 +- examples/reprojection-wgs84.js | 2 +- examples/reprojection.js | 56 +- examples/reusable-source.js | 12 +- examples/rotation.js | 2 +- examples/scale-line.js | 6 +- examples/scaleline-indiana-east.js | 4 +- examples/sea-level.js | 24 +- examples/select-features.js | 22 +- examples/semi-transparent-layer.js | 2 +- examples/shaded-relief.js | 50 +- examples/side-by-side.js | 10 +- examples/simple.js | 2 +- examples/snap.js | 22 +- examples/sphere-mollweide.js | 4 +- examples/stamen.js | 2 +- examples/static-image.js | 6 +- examples/street-labels.js | 6 +- examples/symbol-atlas-webgl.js | 36 +- examples/synthetic-lines.js | 22 +- examples/synthetic-points.js | 42 +- examples/teleport.js | 6 +- examples/tile-load-events.js | 12 +- examples/tile-transitions.js | 10 +- examples/tilejson.js | 2 +- examples/tileutfgrid.js | 50 +- examples/tissot.js | 16 +- examples/topojson.js | 8 +- examples/topolis.js | 58 +- examples/translate-features.js | 10 +- examples/turf.js | 26 +- examples/vector-esri-edit.js | 54 +- examples/vector-esri.js | 32 +- examples/vector-label-decluttering.js | 22 +- examples/vector-labels.js | 76 +- examples/vector-layer.js | 20 +- examples/vector-osm.js | 24 +- examples/vector-tile-info.js | 8 +- examples/vector-wfs-getfeature.js | 16 +- examples/vector-wfs.js | 8 +- examples/webpack/config.js | 8 +- examples/webpack/example-builder.js | 4 +- examples/wkt.js | 12 +- examples/wms-capabilities.js | 4 +- examples/wms-custom-proj.js | 70 +- examples/wms-custom-tilegrid-512x256.js | 14 +- examples/wms-image-custom-proj.js | 10 +- examples/wms-image.js | 4 +- examples/wms-no-proj.js | 6 +- examples/wms-tiled-wrap-180.js | 4 +- examples/wms-tiled.js | 4 +- examples/wms-time.js | 22 +- examples/wmts-capabilities.js | 4 +- examples/wmts-dimensions.js | 22 +- examples/wmts-hidpi.js | 14 +- examples/wmts-ign.js | 20 +- examples/wmts-layer-from-capabilities.js | 8 +- examples/wmts.js | 14 +- examples/xyz-esri-4326-512.js | 10 +- examples/xyz-esri.js | 2 +- examples/xyz-retina.js | 10 +- examples/xyz.js | 2 +- examples/zoom-constrained.js | 2 +- examples/zoomify.js | 18 +- examples/zoomslider.js | 20 +- package.json | 40 +- src/ol/AssertionError.js | 4 +- src/ol/CanvasMap.js | 2 +- src/ol/CenterConstraint.js | 2 +- src/ol/Collection.js | 40 +- src/ol/Disposable.js | 2 +- src/ol/Feature.js | 34 +- src/ol/Geolocation.js | 40 +- src/ol/Graticule.js | 160 +- src/ol/Image.js | 6 +- src/ol/ImageBase.js | 2 +- src/ol/ImageCanvas.js | 4 +- src/ol/ImageTile.js | 8 +- src/ol/Kinetic.js | 14 +- src/ol/Map.js | 2 +- src/ol/MapBrowserEvent.js | 4 +- src/ol/MapBrowserEventHandler.js | 62 +- src/ol/MapBrowserPointerEvent.js | 6 +- src/ol/MapEvent.js | 2 +- src/ol/Object.js | 12 +- src/ol/Observable.js | 22 +- src/ol/Overlay.js | 90 +- src/ol/PluggableMap.js | 312 ++-- src/ol/ResolutionConstraint.js | 16 +- src/ol/RotationConstraint.js | 6 +- src/ol/Tile.js | 14 +- src/ol/TileCache.js | 10 +- src/ol/TileQueue.js | 40 +- src/ol/TileRange.js | 2 +- src/ol/VectorImageTile.js | 64 +- src/ol/VectorTile.js | 4 +- src/ol/View.js | 308 ++-- src/ol/array.js | 50 +- src/ol/color.js | 40 +- src/ol/control.js | 10 +- src/ol/control/Attribution.js | 50 +- src/ol/control/Control.js | 8 +- src/ol/control/FullScreen.js | 36 +- src/ol/control/MousePosition.js | 38 +- src/ol/control/OverviewMap.js | 178 +-- src/ol/control/Rotate.js | 32 +- src/ol/control/ScaleLine.js | 40 +- src/ol/control/Zoom.js | 40 +- src/ol/control/ZoomSlider.js | 66 +- src/ol/control/ZoomToExtent.js | 26 +- src/ol/coordinate.js | 86 +- src/ol/css.js | 18 +- src/ol/dom.js | 12 +- src/ol/events.js | 46 +- src/ol/events/Event.js | 2 +- src/ol/events/EventTarget.js | 20 +- src/ol/events/condition.js | 20 +- src/ol/extent.js | 140 +- src/ol/featureloader.js | 20 +- src/ol/format/EsriJSON.js | 142 +- src/ol/format/Feature.js | 26 +- src/ol/format/GML.js | 2 +- src/ol/format/GML2.js | 313 ++-- src/ol/format/GML3.js | 449 +++--- src/ol/format/GMLBase.js | 159 +- src/ol/format/GPX.js | 502 +++---- src/ol/format/GeoJSON.js | 72 +- src/ol/format/IGC.js | 58 +- src/ol/format/JSONFeature.js | 10 +- src/ol/format/KML.js | 1297 +++++++++-------- src/ol/format/MVT.js | 87 +- src/ol/format/OSMXML.js | 68 +- src/ol/format/OWS.js | 204 +-- src/ol/format/Polyline.js | 88 +- src/ol/format/TextFeature.js | 2 +- src/ol/format/TopoJSON.js | 88 +- src/ol/format/WFS.js | 280 ++-- src/ol/format/WKT.js | 161 +- src/ol/format/WMSCapabilities.js | 402 ++--- src/ol/format/WMSGetFeatureInfo.js | 40 +- src/ol/format/WMTSCapabilities.js | 268 ++-- src/ol/format/XLink.js | 4 +- src/ol/format/XML.js | 4 +- src/ol/format/XMLFeature.js | 32 +- src/ol/format/XSD.js | 26 +- src/ol/format/filter.js | 10 +- src/ol/format/filter/And.js | 4 +- src/ol/format/filter/Bbox.js | 2 +- src/ol/format/filter/Comparison.js | 2 +- src/ol/format/filter/ComparisonBinary.js | 2 +- src/ol/format/filter/Contains.js | 2 +- src/ol/format/filter/During.js | 2 +- src/ol/format/filter/EqualTo.js | 2 +- src/ol/format/filter/Filter.js | 2 +- src/ol/format/filter/GreaterThan.js | 2 +- src/ol/format/filter/GreaterThanOrEqualTo.js | 2 +- src/ol/format/filter/Intersects.js | 2 +- src/ol/format/filter/IsBetween.js | 2 +- src/ol/format/filter/IsLike.js | 2 +- src/ol/format/filter/IsNull.js | 2 +- src/ol/format/filter/LessThan.js | 2 +- src/ol/format/filter/LessThanOrEqualTo.js | 2 +- src/ol/format/filter/LogicalNary.js | 2 +- src/ol/format/filter/Not.js | 2 +- src/ol/format/filter/NotEqualTo.js | 2 +- src/ol/format/filter/Or.js | 4 +- src/ol/format/filter/Spatial.js | 2 +- src/ol/format/filter/Within.js | 2 +- src/ol/geom/Circle.js | 58 +- src/ol/geom/Geometry.js | 22 +- src/ol/geom/GeometryCollection.js | 74 +- src/ol/geom/LineString.js | 40 +- src/ol/geom/LinearRing.js | 26 +- src/ol/geom/MultiLineString.js | 86 +- src/ol/geom/MultiPoint.js | 42 +- src/ol/geom/MultiPolygon.js | 127 +- src/ol/geom/Point.js | 16 +- src/ol/geom/Polygon.js | 130 +- src/ol/geom/SimpleGeometry.js | 54 +- src/ol/geom/flat/area.js | 24 +- src/ol/geom/flat/center.js | 10 +- src/ol/geom/flat/closest.js | 84 +- src/ol/geom/flat/contains.js | 36 +- src/ol/geom/flat/deflate.js | 31 +- src/ol/geom/flat/flip.js | 10 +- src/ol/geom/flat/geodesic.js | 100 +- src/ol/geom/flat/inflate.js | 28 +- src/ol/geom/flat/interiorpoint.js | 30 +- src/ol/geom/flat/interpolate.js | 64 +- src/ol/geom/flat/intersectsextent.js | 40 +- src/ol/geom/flat/length.js | 20 +- src/ol/geom/flat/orient.js | 42 +- src/ol/geom/flat/reverse.js | 7 +- src/ol/geom/flat/segments.js | 8 +- src/ol/geom/flat/simplify.js | 139 +- src/ol/geom/flat/straightchunk.js | 18 +- src/ol/geom/flat/textpath.js | 48 +- src/ol/geom/flat/topology.js | 4 +- src/ol/geom/flat/transform.js | 54 +- src/ol/has.js | 6 +- src/ol/index.js | 16 +- src/ol/interaction.js | 22 +- src/ol/interaction/DoubleClickZoom.js | 18 +- src/ol/interaction/DragAndDrop.js | 48 +- src/ol/interaction/DragBox.js | 16 +- src/ol/interaction/DragPan.js | 38 +- src/ol/interaction/DragRotate.js | 30 +- src/ol/interaction/DragRotateAndZoom.js | 34 +- src/ol/interaction/DragZoom.js | 26 +- src/ol/interaction/Draw.js | 136 +- src/ol/interaction/Extent.js | 76 +- src/ol/interaction/Interaction.js | 42 +- src/ol/interaction/KeyboardPan.js | 20 +- src/ol/interaction/KeyboardZoom.js | 18 +- src/ol/interaction/Modify.js | 244 ++-- src/ol/interaction/MouseWheelZoom.js | 40 +- src/ol/interaction/PinchRotate.js | 40 +- src/ol/interaction/PinchZoom.js | 44 +- src/ol/interaction/Pointer.js | 26 +- src/ol/interaction/Select.js | 116 +- src/ol/interaction/Snap.js | 136 +- src/ol/interaction/Translate.js | 70 +- src/ol/layer/Base.js | 4 +- src/ol/layer/Group.js | 62 +- src/ol/layer/Heatmap.js | 70 +- src/ol/layer/Image.js | 4 +- src/ol/layer/Layer.js | 38 +- src/ol/layer/Tile.js | 8 +- src/ol/layer/Vector.js | 8 +- src/ol/layer/VectorTile.js | 10 +- src/ol/loadingstrategy.js | 10 +- src/ol/math.js | 44 +- src/ol/net.js | 8 +- src/ol/obj.js | 18 +- src/ol/plugins.js | 8 +- src/ol/pointer/EventSource.js | 2 +- src/ol/pointer/MouseSource.js | 32 +- src/ol/pointer/MsSource.js | 26 +- src/ol/pointer/NativeSource.js | 4 +- src/ol/pointer/PointerEvent.js | 10 +- src/ol/pointer/PointerEventHandler.js | 42 +- src/ol/pointer/TouchSource.js | 50 +- src/ol/proj.js | 80 +- src/ol/proj/EPSG3857.js | 24 +- src/ol/proj/EPSG4326.js | 2 +- src/ol/proj/Projection.js | 2 +- src/ol/proj/Units.js | 2 +- src/ol/proj/proj4.js | 20 +- src/ol/proj/projections.js | 6 +- src/ol/proj/transforms.js | 14 +- src/ol/render.js | 16 +- src/ol/render/Box.js | 20 +- src/ol/render/Event.js | 6 +- src/ol/render/Feature.js | 46 +- src/ol/render/ReplayGroup.js | 2 +- src/ol/render/VectorContext.js | 2 +- src/ol/render/canvas.js | 52 +- src/ol/render/canvas/ImageReplay.js | 38 +- src/ol/render/canvas/Immediate.js | 232 +-- src/ol/render/canvas/LineStringReplay.js | 44 +- src/ol/render/canvas/PolygonReplay.js | 92 +- src/ol/render/canvas/Replay.js | 334 ++--- src/ol/render/canvas/ReplayGroup.js | 131 +- src/ol/render/canvas/TextReplay.js | 178 +-- src/ol/render/replay.js | 2 +- src/ol/render/webgl.js | 4 +- src/ol/render/webgl/CircleReplay.js | 69 +- src/ol/render/webgl/ImageReplay.js | 44 +- src/ol/render/webgl/Immediate.js | 152 +- src/ol/render/webgl/LineStringReplay.js | 145 +- src/ol/render/webgl/PolygonReplay.js | 325 ++--- src/ol/render/webgl/Replay.js | 60 +- src/ol/render/webgl/ReplayGroup.js | 122 +- src/ol/render/webgl/TextReplay.js | 149 +- src/ol/render/webgl/TextureReplay.js | 112 +- .../webgl/circlereplay/defaultshader.js | 2 +- .../circlereplay/defaultshader/Locations.js | 26 +- .../webgl/linestringreplay/defaultshader.js | 2 +- .../defaultshader/Locations.js | 28 +- .../webgl/polygonreplay/defaultshader.js | 2 +- .../polygonreplay/defaultshader/Locations.js | 14 +- .../webgl/texturereplay/defaultshader.js | 2 +- .../texturereplay/defaultshader/Locations.js | 22 +- src/ol/renderer/Layer.js | 34 +- src/ol/renderer/Map.js | 90 +- src/ol/renderer/canvas/ImageLayer.js | 74 +- src/ol/renderer/canvas/IntermediateCanvas.js | 46 +- src/ol/renderer/canvas/Layer.js | 58 +- src/ol/renderer/canvas/Map.js | 82 +- src/ol/renderer/canvas/TileLayer.js | 126 +- src/ol/renderer/canvas/VectorLayer.js | 176 +-- src/ol/renderer/canvas/VectorTileLayer.js | 265 ++-- src/ol/renderer/vector.js | 101 +- src/ol/renderer/webgl/ImageLayer.js | 124 +- src/ol/renderer/webgl/Layer.js | 58 +- src/ol/renderer/webgl/Map.js | 206 +-- src/ol/renderer/webgl/TileLayer.js | 152 +- src/ol/renderer/webgl/VectorLayer.js | 152 +- src/ol/renderer/webgl/defaultmapshader.js | 2 +- .../webgl/defaultmapshader/Locations.js | 14 +- src/ol/renderer/webgl/tilelayershader.js | 2 +- .../webgl/tilelayershader/Locations.js | 10 +- src/ol/reproj.js | 120 +- src/ol/reproj/Image.js | 56 +- src/ol/reproj/Tile.js | 103 +- src/ol/reproj/Triangulation.js | 112 +- src/ol/reproj/common.js | 4 +- src/ol/size.js | 2 +- src/ol/source/BingMaps.js | 86 +- src/ol/source/CartoDB.js | 14 +- src/ol/source/Cluster.js | 38 +- src/ol/source/Image.js | 32 +- src/ol/source/ImageArcGISRest.js | 40 +- src/ol/source/ImageCanvas.js | 14 +- src/ol/source/ImageMapGuide.js | 40 +- src/ol/source/ImageStatic.js | 26 +- src/ol/source/ImageWMS.js | 64 +- src/ol/source/OSM.js | 10 +- src/ol/source/Raster.js | 82 +- src/ol/source/Source.js | 2 +- src/ol/source/Stamen.js | 12 +- src/ol/source/Tile.js | 26 +- src/ol/source/TileArcGISRest.js | 42 +- src/ol/source/TileDebug.js | 18 +- src/ol/source/TileImage.js | 92 +- src/ol/source/TileJSON.js | 28 +- src/ol/source/TileUTFGrid.js | 84 +- src/ol/source/TileWMS.js | 72 +- src/ol/source/UrlTile.js | 16 +- src/ol/source/Vector.js | 238 +-- src/ol/source/VectorTile.js | 44 +- src/ol/source/WMTS.js | 114 +- src/ol/source/XYZ.js | 8 +- src/ol/source/Zoomify.js | 64 +- src/ol/source/common.js | 2 +- src/ol/sphere.js | 78 +- src/ol/string.js | 16 +- src/ol/structs/LRUCache.js | 28 +- src/ol/structs/LinkedList.js | 16 +- src/ol/structs/PriorityQueue.js | 56 +- src/ol/structs/RBush.js | 36 +- src/ol/style.js | 2 +- src/ol/style/Atlas.js | 18 +- src/ol/style/AtlasManager.js | 34 +- src/ol/style/Circle.js | 6 +- src/ol/style/Fill.js | 6 +- src/ol/style/Icon.js | 44 +- src/ol/style/IconImage.js | 36 +- src/ol/style/IconImageCache.js | 12 +- src/ol/style/Image.js | 2 +- src/ol/style/RegularShape.js | 78 +- src/ol/style/Stroke.js | 6 +- src/ol/style/Style.js | 30 +- src/ol/style/Text.js | 4 +- src/ol/tilecoord.js | 20 +- src/ol/tilegrid.js | 50 +- src/ol/tilegrid/TileGrid.js | 140 +- src/ol/tilegrid/WMTS.js | 50 +- src/ol/tilegrid/common.js | 4 +- src/ol/tileurlfunction.js | 56 +- src/ol/transform.js | 57 +- src/ol/typedefs.js | 25 +- src/ol/uri.js | 6 +- src/ol/webgl.js | 8 +- src/ol/webgl/Buffer.js | 2 +- src/ol/webgl/Context.js | 74 +- src/ol/webgl/Fragment.js | 2 +- src/ol/webgl/Shader.js | 2 +- src/ol/webgl/Vertex.js | 2 +- src/ol/xml.js | 90 +- tasks/generate-exports.js | 46 +- tasks/generate-externs.js | 36 +- tasks/generate-info.js | 68 +- tasks/glslunit.js | 8 +- test/rendering/ol/layer/clip.test.js | 24 +- test/rendering/ol/layer/image.test.js | 26 +- test/rendering/ol/layer/tile.test.js | 76 +- test/rendering/ol/layer/vector.test.js | 144 +- test/rendering/ol/layer/vectortile.test.js | 32 +- test/rendering/ol/map.test.js | 24 +- test/rendering/ol/render.test.js | 58 +- test/rendering/ol/reproj/image.test.js | 34 +- test/rendering/ol/reproj/tile.test.js | 82 +- test/rendering/ol/source/raster.test.js | 14 +- test/rendering/ol/source/tilewms.test.js | 20 +- test/rendering/ol/style/circle.test.js | 12 +- test/rendering/ol/style/icon.test.js | 21 +- test/rendering/ol/style/linestring.test.js | 26 +- test/rendering/ol/style/polygon.test.js | 54 +- test/rendering/ol/style/regularshape.test.js | 14 +- test/rendering/ol/style/text.test.js | 44 +- test/spec/ol/array.test.js | 394 ++--- test/spec/ol/assertionerror.test.js | 10 +- test/spec/ol/collection.test.js | 108 +- test/spec/ol/color.test.js | 46 +- test/spec/ol/control/attribution.test.js | 12 +- test/spec/ol/control/control.test.js | 14 +- test/spec/ol/control/fullscreen.test.js | 2 +- test/spec/ol/control/mouseposition.test.js | 6 +- test/spec/ol/control/overviewmap.test.js | 24 +- test/spec/ol/control/rotate.test.js | 2 +- test/spec/ol/control/scaleline.test.js | 102 +- test/spec/ol/control/zoom.test.js | 2 +- test/spec/ol/control/zoomslider.test.js | 34 +- test/spec/ol/control/zoomtoextent.test.js | 2 +- test/spec/ol/coordinate.test.js | 166 +-- test/spec/ol/css.test.js | 4 +- test/spec/ol/disposable.test.js | 8 +- test/spec/ol/dom/dom.test.js | 76 +- test/spec/ol/events.test.js | 82 +- test/spec/ol/events/event.test.js | 12 +- test/spec/ol/events/eventtarget.test.js | 6 +- test/spec/ol/expect.test.js | 54 +- test/spec/ol/extent.test.js | 414 +++--- test/spec/ol/feature.test.js | 164 +-- test/spec/ol/featureloader.test.js | 14 +- test/spec/ol/format/esrijson.test.js | 462 +++--- test/spec/ol/format/geojson.test.js | 372 ++--- test/spec/ol/format/gml.test.js | 396 ++--- test/spec/ol/format/gpx.test.js | 224 +-- test/spec/ol/format/igc.test.js | 62 +- test/spec/ol/format/kml.test.js | 1168 +++++++-------- test/spec/ol/format/mvt.test.js | 66 +- test/spec/ol/format/osmxml.test.js | 46 +- test/spec/ol/format/ows.test.js | 40 +- test/spec/ol/format/polyline.test.js | 96 +- test/spec/ol/format/topojson.test.js | 54 +- test/spec/ol/format/wfs.test.js | 397 ++--- test/spec/ol/format/wkt.test.js | 358 ++--- test/spec/ol/format/wmscapabilities.test.js | 28 +- test/spec/ol/format/wmsgetfeatureinfo.test.js | 36 +- test/spec/ol/format/wmtscapabilities.test.js | 44 +- test/spec/ol/format/xsd.test.js | 2 +- test/spec/ol/geolocation.test.js | 2 +- test/spec/ol/geom/circle.test.js | 88 +- test/spec/ol/geom/flat/area.test.js | 8 +- test/spec/ol/geom/flat/center.test.js | 36 +- test/spec/ol/geom/flat/closest.test.js | 72 +- test/spec/ol/geom/flat/contains.test.js | 14 +- test/spec/ol/geom/flat/deflate.test.js | 12 +- test/spec/ol/geom/flat/flip.test.js | 24 +- test/spec/ol/geom/flat/inflate.test.js | 6 +- test/spec/ol/geom/flat/interpolate.test.js | 68 +- .../ol/geom/flat/intersectsextent.test.js | 66 +- test/spec/ol/geom/flat/length.test.js | 80 +- test/spec/ol/geom/flat/orient.test.js | 60 +- test/spec/ol/geom/flat/reverse.test.js | 62 +- test/spec/ol/geom/flat/segments.test.js | 18 +- test/spec/ol/geom/flat/simplify.test.js | 132 +- test/spec/ol/geom/flat/straightchunk.test.js | 24 +- test/spec/ol/geom/flat/textpath.test.js | 94 +- .../ol/geom/flat/topologyflatgeom.test.js | 12 +- test/spec/ol/geom/flat/transform.test.js | 32 +- test/spec/ol/geom/geometrycollection.test.js | 90 +- test/spec/ol/geom/linestring.test.js | 68 +- test/spec/ol/geom/multilinestring.test.js | 142 +- test/spec/ol/geom/multipoint.test.js | 50 +- test/spec/ol/geom/multipolygon.test.js | 70 +- test/spec/ol/geom/point.test.js | 40 +- test/spec/ol/geom/polygon.test.js | 134 +- test/spec/ol/graticule.test.js | 38 +- test/spec/ol/imagetile.test.js | 52 +- test/spec/ol/index.test.js | 6 +- test/spec/ol/interaction/draganddrop.test.js | 22 +- .../ol/interaction/dragrotateandzoom.test.js | 26 +- test/spec/ol/interaction/dragzoom.test.js | 36 +- test/spec/ol/interaction/draw.test.js | 188 +-- test/spec/ol/interaction/extent.test.js | 18 +- test/spec/ol/interaction/interaction.test.js | 20 +- test/spec/ol/interaction/keyboardpan.test.js | 6 +- test/spec/ol/interaction/keyboardzoom.test.js | 6 +- test/spec/ol/interaction/modify.test.js | 178 +-- .../ol/interaction/mousewheelzoom.test.js | 30 +- test/spec/ol/interaction/select.test.js | 130 +- test/spec/ol/interaction/snap.test.js | 52 +- test/spec/ol/interaction/translate.test.js | 56 +- test/spec/ol/layer/group.test.js | 91 +- test/spec/ol/layer/heatmap.test.js | 2 +- test/spec/ol/layer/layer.test.js | 74 +- test/spec/ol/layer/tile.test.js | 2 +- test/spec/ol/layer/vector.test.js | 30 +- test/spec/ol/layer/vectortile.test.js | 4 +- test/spec/ol/map.test.js | 142 +- test/spec/ol/mapbrowserevent.test.js | 32 +- test/spec/ol/math.test.js | 4 +- test/spec/ol/net.test.js | 18 +- test/spec/ol/object.test.js | 38 +- test/spec/ol/objectutil.test.js | 10 +- test/spec/ol/observable.test.js | 18 +- test/spec/ol/overlay.test.js | 16 +- test/spec/ol/pointer/mousesource.test.js | 14 +- .../ol/pointer/pointereventhandler.test.js | 34 +- test/spec/ol/pointer/touchsource.test.js | 18 +- test/spec/ol/proj.test.js | 198 +-- test/spec/ol/proj/epsg3857.test.js | 52 +- test/spec/ol/proj/transforms.test.js | 12 +- test/spec/ol/render.test.js | 20 +- test/spec/ol/render/box.test.js | 4 +- test/spec/ol/render/canvas/immediate.test.js | 76 +- test/spec/ol/render/canvas/index.test.js | 22 +- .../spec/ol/render/canvas/replaygroup.test.js | 20 +- test/spec/ol/render/canvas/textreplay.test.js | 12 +- test/spec/ol/render/feature.test.js | 34 +- .../spec/ol/render/webgl/circlereplay.test.js | 44 +- test/spec/ol/render/webgl/imagereplay.test.js | 30 +- test/spec/ol/render/webgl/immediate.test.js | 24 +- test/spec/ol/render/webgl/index.test.js | 14 +- .../ol/render/webgl/linestringreplay.test.js | 156 +- .../ol/render/webgl/polygonreplay.test.js | 122 +- test/spec/ol/render/webgl/textreplay.test.js | 159 +- .../ol/render/webgl/texturereplay.test.js | 24 +- .../ol/renderer/canvas/imagelayer.test.js | 6 +- .../canvas/intermediatecanvas.test.js | 12 +- test/spec/ol/renderer/canvas/map.test.js | 40 +- test/spec/ol/renderer/canvas/replay.test.js | 138 +- .../spec/ol/renderer/canvas/tilelayer.test.js | 20 +- .../ol/renderer/canvas/vectorlayer.test.js | 80 +- .../renderer/canvas/vectortilelayer.test.js | 104 +- test/spec/ol/renderer/layer.test.js | 42 +- test/spec/ol/renderer/map.test.js | 4 +- test/spec/ol/renderer/vector.test.js | 88 +- .../spec/ol/renderer/webgl/imagelayer.test.js | 26 +- test/spec/ol/reproj/image.test.js | 28 +- test/spec/ol/reproj/reproj.test.js | 32 +- test/spec/ol/reproj/tile.test.js | 66 +- test/spec/ol/reproj/triangulation.test.js | 22 +- test/spec/ol/resolutionconstraint.test.js | 12 +- test/spec/ol/rotationconstraint.test.js | 2 +- test/spec/ol/size.test.js | 30 +- test/spec/ol/source/bingmaps.test.js | 32 +- test/spec/ol/source/cartodb.test.js | 2 +- test/spec/ol/source/cluster.test.js | 16 +- test/spec/ol/source/imagearcgisrest.test.js | 82 +- test/spec/ol/source/imagestatic.test.js | 18 +- test/spec/ol/source/imagewms.test.js | 200 +-- test/spec/ol/source/raster.test.js | 68 +- test/spec/ol/source/source.test.js | 38 +- test/spec/ol/source/stamen.test.js | 4 +- test/spec/ol/source/tile.test.js | 126 +- test/spec/ol/source/tilearcgisrest.test.js | 114 +- test/spec/ol/source/tileimage.test.js | 82 +- test/spec/ol/source/tilejson.test.js | 40 +- test/spec/ol/source/tileutfgrid.test.js | 92 +- test/spec/ol/source/tilewms.test.js | 186 +-- test/spec/ol/source/urltile.test.js | 84 +- test/spec/ol/source/vector.test.js | 192 +-- test/spec/ol/source/vectortile.test.js | 18 +- test/spec/ol/source/wmts.test.js | 290 ++-- test/spec/ol/source/xyz.test.js | 74 +- test/spec/ol/source/zoomify.test.js | 120 +- test/spec/ol/sphere.test.js | 26 +- test/spec/ol/string.test.js | 2 +- test/spec/ol/structs/linkedlist.test.js | 48 +- test/spec/ol/structs/lrucache.test.js | 24 +- test/spec/ol/structs/priorityqueue.test.js | 38 +- test/spec/ol/structs/rbush.test.js | 84 +- test/spec/ol/style/atlasmanager.test.js | 112 +- test/spec/ol/style/circle.test.js | 58 +- test/spec/ol/style/fill.test.js | 12 +- test/spec/ol/style/icon.test.js | 64 +- test/spec/ol/style/iconimagecache.test.js | 6 +- test/spec/ol/style/regularshape.test.js | 64 +- test/spec/ol/style/stroke.test.js | 12 +- test/spec/ol/style/style.test.js | 68 +- test/spec/ol/style/text.test.js | 18 +- test/spec/ol/tile.test.js | 44 +- test/spec/ol/tilecache.test.js | 4 +- test/spec/ol/tilecoord.test.js | 38 +- test/spec/ol/tilegrid/tilegrid.test.js | 258 ++-- test/spec/ol/tilegrid/wmts.test.js | 214 +-- test/spec/ol/tilequeue.test.js | 54 +- test/spec/ol/tilerange.test.js | 44 +- test/spec/ol/tileurlfunction.test.js | 44 +- test/spec/ol/transform.test.js | 44 +- test/spec/ol/uri.test.js | 18 +- test/spec/ol/vec/mat4.test.js | 10 +- test/spec/ol/vectorimagetile.test.js | 116 +- test/spec/ol/vectortile.test.js | 8 +- test/spec/ol/view.test.js | 382 ++--- test/spec/ol/webgl/buffer.test.js | 6 +- test/test-extensions.js | 172 +-- transforms/module.js | 130 +- 684 files changed, 18120 insertions(+), 18184 deletions(-) diff --git a/examples/accessible.js b/examples/accessible.js index c2f6611e23..2c5f1c6199 100644 --- a/examples/accessible.js +++ b/examples/accessible.js @@ -5,7 +5,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -24,13 +24,13 @@ var map = new Map({ }); document.getElementById('zoom-out').onclick = function() { - var view = map.getView(); - var zoom = view.getZoom(); + const view = map.getView(); + const zoom = view.getZoom(); view.setZoom(zoom - 1); }; document.getElementById('zoom-in').onclick = function() { - var view = map.getView(); - var zoom = view.getZoom(); + const view = map.getView(); + const zoom = view.getZoom(); view.setZoom(zoom + 1); }; diff --git a/examples/animation.js b/examples/animation.js index ad92b9892b..1c43765975 100644 --- a/examples/animation.js +++ b/examples/animation.js @@ -5,18 +5,18 @@ import TileLayer from '../src/ol/layer/Tile.js'; import {fromLonLat} from '../src/ol/proj.js'; import OSM from '../src/ol/source/OSM.js'; -var london = fromLonLat([-0.12755, 51.507222]); -var moscow = fromLonLat([37.6178, 55.7517]); -var istanbul = fromLonLat([28.9744, 41.0128]); -var rome = fromLonLat([12.5, 41.9]); -var bern = fromLonLat([7.4458, 46.95]); +const london = fromLonLat([-0.12755, 51.507222]); +const moscow = fromLonLat([37.6178, 55.7517]); +const istanbul = fromLonLat([28.9744, 41.0128]); +const rome = fromLonLat([12.5, 41.9]); +const bern = fromLonLat([7.4458, 46.95]); -var view = new View({ +const view = new View({ center: istanbul, zoom: 6 }); -var map = new Map({ +const map = new Map({ target: 'map', layers: [ new TileLayer({ @@ -32,7 +32,9 @@ var map = new Map({ // A bounce easing method (from https://github.com/DmitryBaranovskiy/raphael). function bounce(t) { - var s = 7.5625, p = 2.75, l; + const s = 7.5625; + const p = 2.75; + let l; if (t < (1 / p)) { l = s * t * t; } else { @@ -75,7 +77,7 @@ onClick('rotate-right', function() { onClick('rotate-around-rome', function() { // Rotation animation takes the shortest arc, so animate in two parts - var rotation = view.getRotation(); + const rotation = view.getRotation(); view.animate({ rotation: rotation + Math.PI, anchor: rome, @@ -112,7 +114,7 @@ onClick('bounce-to-istanbul', function() { onClick('spin-to-rome', function() { // Rotation animation takes the shortest arc, so animate in two parts - var center = view.getCenter(); + const center = view.getCenter(); view.animate({ center: [ center[0] + (rome[0] - center[0]) / 2, @@ -128,10 +130,10 @@ onClick('spin-to-rome', function() { }); function flyTo(location, done) { - var duration = 2000; - var zoom = view.getZoom(); - var parts = 2; - var called = false; + const duration = 2000; + const zoom = view.getZoom(); + let parts = 2; + let called = false; function callback(complete) { --parts; if (called) { @@ -160,13 +162,13 @@ onClick('fly-to-bern', function() { }); function tour() { - var locations = [london, bern, rome, moscow, istanbul]; - var index = -1; + const locations = [london, bern, rome, moscow, istanbul]; + let index = -1; function next(more) { if (more) { ++index; if (index < locations.length) { - var delay = index === 0 ? 0 : 750; + const delay = index === 0 ? 0 : 750; setTimeout(function() { flyTo(locations[index], next); }, delay); diff --git a/examples/arcgis-image.js b/examples/arcgis-image.js index e7250ed7c0..b644c1eb5f 100644 --- a/examples/arcgis-image.js +++ b/examples/arcgis-image.js @@ -5,10 +5,10 @@ import ImageLayer from '../src/ol/layer/Image.js'; import OSM from '../src/ol/source/OSM.js'; import ImageArcGISRest from '../src/ol/source/ImageArcGISRest.js'; -var url = 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' + +const url = 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' + 'Specialty/ESRI_StateCityHighway_USA/MapServer'; -var layers = [ +const layers = [ new TileLayer({ source: new OSM() }), @@ -20,7 +20,7 @@ var layers = [ }) }) ]; -var map = new Map({ +const map = new Map({ layers: layers, target: 'map', view: new View({ diff --git a/examples/arcgis-tiled.js b/examples/arcgis-tiled.js index cb3ea87bc2..deef00549e 100644 --- a/examples/arcgis-tiled.js +++ b/examples/arcgis-tiled.js @@ -4,10 +4,10 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; import TileArcGISRest from '../src/ol/source/TileArcGISRest.js'; -var url = 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' + +const url = 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' + 'Specialty/ESRI_StateCityHighway_USA/MapServer'; -var layers = [ +const layers = [ new TileLayer({ source: new OSM() }), @@ -18,7 +18,7 @@ var layers = [ }) }) ]; -var map = new Map({ +const map = new Map({ layers: layers, target: 'map', view: new View({ diff --git a/examples/attributions.js b/examples/attributions.js index 8f976dcbb4..731eabbbab 100644 --- a/examples/attributions.js +++ b/examples/attributions.js @@ -5,10 +5,10 @@ import Attribution from '../src/ol/control/Attribution.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var attribution = new Attribution({ +const attribution = new Attribution({ collapsible: false }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -23,7 +23,7 @@ var map = new Map({ }); function checkSize() { - var small = map.getSize()[0] < 600; + const small = map.getSize()[0] < 600; attribution.setCollapsible(small); attribution.setCollapsed(small); } diff --git a/examples/bing-maps.js b/examples/bing-maps.js index 0848bcdea3..66419646a4 100644 --- a/examples/bing-maps.js +++ b/examples/bing-maps.js @@ -4,7 +4,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import BingMaps from '../src/ol/source/BingMaps.js'; -var styles = [ +const styles = [ 'Road', 'RoadOnDemand', 'Aerial', @@ -12,8 +12,8 @@ var styles = [ 'collinsBart', 'ordnanceSurvey' ]; -var layers = []; -var i, ii; +const layers = []; +let i, ii; for (i = 0, ii = styles.length; i < ii; ++i) { layers.push(new TileLayer({ visible: false, @@ -27,7 +27,7 @@ for (i = 0, ii = styles.length; i < ii; ++i) { }) })); } -var map = new Map({ +const map = new Map({ layers: layers, // Improve user experience by loading tiles while dragging/zooming. Will make // zooming choppy on mobile or slow devices. @@ -39,10 +39,10 @@ var map = new Map({ }) }); -var select = document.getElementById('layer-select'); +const select = document.getElementById('layer-select'); function onChange() { - var style = select.value; - for (var i = 0, ii = layers.length; i < ii; ++i) { + const style = select.value; + for (let i = 0, ii = layers.length; i < ii; ++i) { layers[i].setVisible(styles[i] === style); } } diff --git a/examples/blend-modes.js b/examples/blend-modes.js index 45e900d178..00e7610c09 100644 --- a/examples/blend-modes.js +++ b/examples/blend-modes.js @@ -14,7 +14,7 @@ import Style from '../src/ol/style/Style.js'; // // Every layer has one feature that is styled with a circle, together the // features form the corners of an equilateral triangle and their styles overlap -var redLayer = new VectorLayer({ +const redLayer = new VectorLayer({ source: new VectorSource({ features: [new Feature(new Point([0, 0]))] }), @@ -31,7 +31,7 @@ var redLayer = new VectorLayer({ }) }) }); -var greenLayer = new VectorLayer({ +const greenLayer = new VectorLayer({ source: new VectorSource({ // 433.013 is roughly 250 * Math.sqrt(3) features: [new Feature(new Point([250, 433.013]))] @@ -49,7 +49,7 @@ var greenLayer = new VectorLayer({ }) }) }); -var blueLayer = new VectorLayer({ +const blueLayer = new VectorLayer({ source: new VectorSource({ features: [new Feature(new Point([500, 0]))] }), @@ -69,7 +69,7 @@ var blueLayer = new VectorLayer({ // Create the map, the view is centered on the triangle. Zooming and panning is // restricted to a sane area -var map = new Map({ +const map = new Map({ layers: [ redLayer, greenLayer, @@ -86,10 +86,10 @@ var map = new Map({ }); // Get the form elements and bind the listeners -var select = document.getElementById('blend-mode'); -var affectRed = document.getElementById('affect-red'); -var affectGreen = document.getElementById('affect-green'); -var affectBlue = document.getElementById('affect-blue'); +const select = document.getElementById('blend-mode'); +const affectRed = document.getElementById('affect-red'); +const affectGreen = document.getElementById('affect-green'); +const affectBlue = document.getElementById('affect-blue'); /** @@ -98,7 +98,7 @@ var affectBlue = document.getElementById('affect-blue'); * * @param {ol.render.Event} evt The render event. */ -var setBlendModeFromSelect = function(evt) { +const setBlendModeFromSelect = function(evt) { evt.context.globalCompositeOperation = select.value; }; @@ -109,7 +109,7 @@ var setBlendModeFromSelect = function(evt) { * * @param {ol.render.Event} evt The render event. */ -var resetBlendModeFromSelect = function(evt) { +const resetBlendModeFromSelect = function(evt) { evt.context.globalCompositeOperation = 'source-over'; }; @@ -119,7 +119,7 @@ var resetBlendModeFromSelect = function(evt) { * * @param {ol.layer.Vector} layer The layer to bind the handlers to. */ -var bindLayerListeners = function(layer) { +const bindLayerListeners = function(layer) { layer.on('precompose', setBlendModeFromSelect); layer.on('postcompose', resetBlendModeFromSelect); }; @@ -130,7 +130,7 @@ var bindLayerListeners = function(layer) { * * @param {ol.layer.Vector} layer The layer to unbind the handlers from. */ -var unbindLayerListeners = function(layer) { +const unbindLayerListeners = function(layer) { layer.un('precompose', setBlendModeFromSelect); layer.un('postcompose', resetBlendModeFromSelect); }; @@ -141,8 +141,8 @@ var unbindLayerListeners = function(layer) { * * @this {HTMLInputElement} */ -var affectLayerClicked = function() { - var layer; +const affectLayerClicked = function() { + let layer; if (this.id == 'affect-red') { layer = redLayer; } else if (this.id == 'affect-green') { diff --git a/examples/box-selection.js b/examples/box-selection.js index 69be214ab4..2ab2b587c6 100644 --- a/examples/box-selection.js +++ b/examples/box-selection.js @@ -10,13 +10,13 @@ import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ url: 'data/geojson/countries.geojson', format: new GeoJSON() }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -33,13 +33,13 @@ var map = new Map({ }); // a normal select interaction to handle click -var select = new Select(); +const select = new Select(); map.addInteraction(select); -var selectedFeatures = select.getFeatures(); +const selectedFeatures = select.getFeatures(); // a DragBox interaction used to select features by drawing boxes -var dragBox = new DragBox({ +const dragBox = new DragBox({ condition: _ol_events_condition_.platformModifierKeyOnly }); @@ -48,7 +48,7 @@ map.addInteraction(dragBox); dragBox.on('boxend', function() { // features that intersect the box are added to the collection of // selected features - var extent = dragBox.getGeometry().getExtent(); + const extent = dragBox.getGeometry().getExtent(); vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) { selectedFeatures.push(feature); }); @@ -59,10 +59,10 @@ dragBox.on('boxstart', function() { selectedFeatures.clear(); }); -var infoBox = document.getElementById('info'); +const infoBox = document.getElementById('info'); selectedFeatures.on(['add', 'remove'], function() { - var names = selectedFeatures.getArray().map(function(feature) { + const names = selectedFeatures.getArray().map(function(feature) { return feature.get('name'); }); if (names.length > 0) { diff --git a/examples/button-title.js b/examples/button-title.js index 13d4bd971c..c48462a62f 100644 --- a/examples/button-title.js +++ b/examples/button-title.js @@ -3,7 +3,7 @@ import View from '../src/ol/View.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() diff --git a/examples/canvas-gradient-pattern.js b/examples/canvas-gradient-pattern.js index 7e7e1f6f98..1e64f3e363 100644 --- a/examples/canvas-gradient-pattern.js +++ b/examples/canvas-gradient-pattern.js @@ -10,22 +10,22 @@ import Fill from '../src/ol/style/Fill.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var canvas = document.createElement('canvas'); -var context = canvas.getContext('2d'); +const canvas = document.createElement('canvas'); +const context = canvas.getContext('2d'); // Gradient and pattern are in canvas pixel space, so we adjust for the // renderer's pixel ratio -var pixelRatio = _ol_has_.DEVICE_PIXEL_RATIO; +const pixelRatio = _ol_has_.DEVICE_PIXEL_RATIO; // Generate a rainbow gradient function gradient(feature, resolution) { - var extent = feature.getGeometry().getExtent(); + const extent = feature.getGeometry().getExtent(); // Gradient starts on the left edge of each feature, and ends on the right. // Coordinate origin is the top-left corner of the extent of the geometry, so // we just divide the geometry's extent width by resolution and multiply with // pixelRatio to match the renderer's pixel coordinate system. - var grad = context.createLinearGradient(0, 0, - _ol_extent_.getWidth(extent) / resolution * pixelRatio, 0); + const grad = context.createLinearGradient(0, 0, + _ol_extent_.getWidth(extent) / resolution * pixelRatio, 0); grad.addColorStop(0, 'red'); grad.addColorStop(1 / 6, 'orange'); grad.addColorStop(2 / 6, 'yellow'); @@ -37,7 +37,7 @@ function gradient(feature, resolution) { } // Generate a canvasPattern with two circles on white background -var pattern = (function() { +const pattern = (function() { canvas.width = 11 * pixelRatio; canvas.height = 11 * pixelRatio; // white background @@ -57,8 +57,8 @@ var pattern = (function() { }()); // Generate style for gradient or pattern fill -var fill = new Fill(); -var style = new Style({ +const fill = new Fill(); +const style = new Style({ fill: fill, stroke: new Stroke({ color: '#333', @@ -74,14 +74,14 @@ var style = new Style({ * @param {number} resolution Resolution. * @return {ol.style.Style} The style to use for the feature. */ -var getStackedStyle = function(feature, resolution) { - var id = feature.getId(); +const getStackedStyle = function(feature, resolution) { + const id = feature.getId(); fill.setColor(id > 'J' ? gradient(feature, resolution) : pattern); return style; }; // Create a vector layer that makes use of the style function above… -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: new VectorSource({ url: 'data/geojson/countries.geojson', format: new GeoJSON() @@ -90,7 +90,7 @@ var vectorLayer = new VectorLayer({ }); // … finally create a map with that layer. -var map = new Map({ +const map = new Map({ layers: [ vectorLayer ], diff --git a/examples/canvas-tiles.js b/examples/canvas-tiles.js index 8839063a74..dc58b6ac8c 100644 --- a/examples/canvas-tiles.js +++ b/examples/canvas-tiles.js @@ -7,8 +7,8 @@ import OSM from '../src/ol/source/OSM.js'; import TileDebug from '../src/ol/source/TileDebug.js'; -var osmSource = new OSM(); -var map = new Map({ +const osmSource = new OSM(); +const map = new Map({ layers: [ new TileLayer({ source: osmSource diff --git a/examples/cartodb.js b/examples/cartodb.js index c515b247ef..09c78eeba9 100644 --- a/examples/cartodb.js +++ b/examples/cartodb.js @@ -4,7 +4,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import CartoDB from '../src/ol/source/CartoDB.js'; import OSM from '../src/ol/source/OSM.js'; -var mapConfig = { +const mapConfig = { 'layers': [{ 'type': 'cartodb', 'options': { @@ -15,12 +15,12 @@ var mapConfig = { }] }; -var cartoDBSource = new CartoDB({ +const cartoDBSource = new CartoDB({ account: 'documentation', config: mapConfig }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() diff --git a/examples/center.js b/examples/center.js index f63b37e2de..c6ab1703ae 100644 --- a/examples/center.js +++ b/examples/center.js @@ -11,11 +11,11 @@ import Fill from '../src/ol/style/Fill.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var source = new VectorSource({ +const source = new VectorSource({ url: 'data/geojson/switzerland.geojson', format: new GeoJSON() }); -var style = new Style({ +const style = new Style({ fill: new Fill({ color: 'rgba(255, 255, 255, 0.6)' }), @@ -34,15 +34,15 @@ var style = new Style({ }) }) }); -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: source, style: style }); -var view = new View({ +const view = new View({ center: [0, 0], zoom: 1 }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -58,40 +58,40 @@ var map = new Map({ view: view }); -var zoomtoswitzerlandbest = document.getElementById('zoomtoswitzerlandbest'); +const zoomtoswitzerlandbest = document.getElementById('zoomtoswitzerlandbest'); zoomtoswitzerlandbest.addEventListener('click', function() { - var feature = source.getFeatures()[0]; - var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); + const feature = source.getFeatures()[0]; + const polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); view.fit(polygon, {padding: [170, 50, 30, 150], constrainResolution: false}); }, false); -var zoomtoswitzerlandconstrained = +const zoomtoswitzerlandconstrained = document.getElementById('zoomtoswitzerlandconstrained'); zoomtoswitzerlandconstrained.addEventListener('click', function() { - var feature = source.getFeatures()[0]; - var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); + const feature = source.getFeatures()[0]; + const polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); view.fit(polygon, {padding: [170, 50, 30, 150]}); }, false); -var zoomtoswitzerlandnearest = +const zoomtoswitzerlandnearest = document.getElementById('zoomtoswitzerlandnearest'); zoomtoswitzerlandnearest.addEventListener('click', function() { - var feature = source.getFeatures()[0]; - var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); + const feature = source.getFeatures()[0]; + const polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); view.fit(polygon, {padding: [170, 50, 30, 150], nearest: true}); }, false); -var zoomtolausanne = document.getElementById('zoomtolausanne'); +const zoomtolausanne = document.getElementById('zoomtolausanne'); zoomtolausanne.addEventListener('click', function() { - var feature = source.getFeatures()[1]; - var point = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); + const feature = source.getFeatures()[1]; + const point = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); view.fit(point, {padding: [170, 50, 30, 150], minResolution: 50}); }, false); -var centerlausanne = document.getElementById('centerlausanne'); +const centerlausanne = document.getElementById('centerlausanne'); centerlausanne.addEventListener('click', function() { - var feature = source.getFeatures()[1]; - var point = /** @type {ol.geom.Point} */ (feature.getGeometry()); - var size = /** @type {ol.Size} */ (map.getSize()); + const feature = source.getFeatures()[1]; + const point = /** @type {ol.geom.Point} */ (feature.getGeometry()); + const size = /** @type {ol.Size} */ (map.getSize()); view.centerOn(point.getCoordinates(), size, [570, 500]); }, false); diff --git a/examples/cluster.js b/examples/cluster.js index 8016547cad..5edfdd796c 100644 --- a/examples/cluster.js +++ b/examples/cluster.js @@ -14,31 +14,31 @@ import Style from '../src/ol/style/Style.js'; import Text from '../src/ol/style/Text.js'; -var distance = document.getElementById('distance'); +const distance = document.getElementById('distance'); -var count = 20000; -var features = new Array(count); -var e = 4500000; -for (var i = 0; i < count; ++i) { - var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; +const count = 20000; +const features = new Array(count); +const e = 4500000; +for (let i = 0; i < count; ++i) { + const coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; features[i] = new Feature(new Point(coordinates)); } -var source = new VectorSource({ +const source = new VectorSource({ features: features }); -var clusterSource = new Cluster({ +const clusterSource = new Cluster({ distance: parseInt(distance.value, 10), source: source }); -var styleCache = {}; -var clusters = new VectorLayer({ +const styleCache = {}; +const clusters = new VectorLayer({ source: clusterSource, style: function(feature) { - var size = feature.get('features').length; - var style = styleCache[size]; + const size = feature.get('features').length; + let style = styleCache[size]; if (!style) { style = new Style({ image: new CircleStyle({ @@ -63,11 +63,11 @@ var clusters = new VectorLayer({ } }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var map = new Map({ +const map = new Map({ layers: [raster, clusters], target: 'map', view: new View({ diff --git a/examples/color-manipulation.js b/examples/color-manipulation.js index b86fc42806..1ee09c4634 100644 --- a/examples/color-manipulation.js +++ b/examples/color-manipulation.js @@ -10,14 +10,14 @@ import Stamen from '../src/ol/source/Stamen.js'; * Color manipulation functions below are adapted from * https://github.com/d3/d3-color. */ -var Xn = 0.950470; -var Yn = 1; -var Zn = 1.088830; -var t0 = 4 / 29; -var t1 = 6 / 29; -var t2 = 3 * t1 * t1; -var t3 = t1 * t1 * t1; -var twoPi = 2 * Math.PI; +const Xn = 0.950470; +const Yn = 1; +const Zn = 1.088830; +const t0 = 4 / 29; +const t1 = 6 / 29; +const t2 = 3 * t1 * t1; +const t3 = t1 * t1 * t1; +const twoPi = 2 * Math.PI; /** @@ -26,23 +26,23 @@ var twoPi = 2 * Math.PI; * @return {Array.} A pixel in HCL space. */ function rgb2hcl(pixel) { - var red = rgb2xyz(pixel[0]); - var green = rgb2xyz(pixel[1]); - var blue = rgb2xyz(pixel[2]); + const red = rgb2xyz(pixel[0]); + const green = rgb2xyz(pixel[1]); + const blue = rgb2xyz(pixel[2]); - var x = xyz2lab( - (0.4124564 * red + 0.3575761 * green + 0.1804375 * blue) / Xn); - var y = xyz2lab( - (0.2126729 * red + 0.7151522 * green + 0.0721750 * blue) / Yn); - var z = xyz2lab( - (0.0193339 * red + 0.1191920 * green + 0.9503041 * blue) / Zn); + const x = xyz2lab( + (0.4124564 * red + 0.3575761 * green + 0.1804375 * blue) / Xn); + const y = xyz2lab( + (0.2126729 * red + 0.7151522 * green + 0.0721750 * blue) / Yn); + const z = xyz2lab( + (0.0193339 * red + 0.1191920 * green + 0.9503041 * blue) / Zn); - var l = 116 * y - 16; - var a = 500 * (x - y); - var b = 200 * (y - z); + const l = 116 * y - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); - var c = Math.sqrt(a * a + b * b); - var h = Math.atan2(b, a); + const c = Math.sqrt(a * a + b * b); + let h = Math.atan2(b, a); if (h < 0) { h += twoPi; } @@ -61,16 +61,16 @@ function rgb2hcl(pixel) { * @return {Array.} A pixel in RGB space. */ function hcl2rgb(pixel) { - var h = pixel[0]; - var c = pixel[1]; - var l = pixel[2]; + const h = pixel[0]; + const c = pixel[1]; + const l = pixel[2]; - var a = Math.cos(h) * c; - var b = Math.sin(h) * c; + const a = Math.cos(h) * c; + const b = Math.sin(h) * c; - var y = (l + 16) / 116; - var x = isNaN(a) ? y : y + a / 500; - var z = isNaN(b) ? y : y - b / 200; + let y = (l + 16) / 116; + let x = isNaN(a) ? y : y + a / 500; + let z = isNaN(b) ? y : y - b / 200; y = Yn * lab2xyz(y); x = Xn * lab2xyz(x); @@ -100,15 +100,15 @@ function xyz2rgb(x) { 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); } -var raster = new RasterSource({ +const raster = new RasterSource({ sources: [new Stamen({ layer: 'watercolor', transition: 0 })], operation: function(pixels, data) { - var hcl = rgb2hcl(pixels[0]); + const hcl = rgb2hcl(pixels[0]); - var h = hcl[0] + Math.PI * data.hue / 180; + let h = hcl[0] + Math.PI * data.hue / 180; if (h < 0) { h += twoPi; } else if (h > twoPi) { @@ -139,16 +139,16 @@ var raster = new RasterSource({ } }); -var controls = {}; +const controls = {}; raster.on('beforeoperations', function(event) { - var data = event.data; - for (var id in controls) { + const data = event.data; + for (const id in controls) { data[id] = Number(controls[id].value); } }); -var map = new Map({ +const map = new Map({ layers: [ new ImageLayer({ source: raster @@ -162,10 +162,10 @@ var map = new Map({ }) }); -var controlIds = ['hue', 'chroma', 'lightness']; +const controlIds = ['hue', 'chroma', 'lightness']; controlIds.forEach(function(id) { - var control = document.getElementById(id); - var output = document.getElementById(id + 'Out'); + const control = document.getElementById(id); + const output = document.getElementById(id + 'Out'); control.addEventListener('input', function() { output.innerText = control.value; raster.changed(); diff --git a/examples/custom-controls.js b/examples/custom-controls.js index f086020355..7d94e1b046 100644 --- a/examples/custom-controls.js +++ b/examples/custom-controls.js @@ -11,7 +11,7 @@ import OSM from '../src/ol/source/OSM.js'; * Define a namespace for the application. */ window.app = {}; -var app = window.app; +const app = window.app; // @@ -26,20 +26,20 @@ var app = window.app; */ app.RotateNorthControl = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; - var button = document.createElement('button'); + const button = document.createElement('button'); button.innerHTML = 'N'; - var this_ = this; - var handleRotateNorth = function() { + const this_ = this; + const handleRotateNorth = function() { this_.getMap().getView().setRotation(0); }; button.addEventListener('click', handleRotateNorth, false); button.addEventListener('touchstart', handleRotateNorth, false); - var element = document.createElement('div'); + const element = document.createElement('div'); element.className = 'rotate-north ol-unselectable ol-control'; element.appendChild(button); @@ -57,7 +57,7 @@ inherits(app.RotateNorthControl, Control); // -var map = new Map({ +const map = new Map({ controls: defaultControls({ attributionOptions: { collapsible: false diff --git a/examples/custom-interactions.js b/examples/custom-interactions.js index cc5dd1bad6..044fc2cd88 100644 --- a/examples/custom-interactions.js +++ b/examples/custom-interactions.js @@ -20,7 +20,7 @@ import Style from '../src/ol/style/Style.js'; /** * Define a namespace for the application. */ -var app = {}; +const app = {}; /** @@ -69,12 +69,12 @@ inherits(app.Drag, PointerInteraction); * @return {boolean} `true` to start the drag sequence. */ app.Drag.prototype.handleDownEvent = function(evt) { - var map = evt.map; + const map = evt.map; - var feature = map.forEachFeatureAtPixel(evt.pixel, - function(feature) { - return feature; - }); + const feature = map.forEachFeatureAtPixel(evt.pixel, + function(feature) { + return feature; + }); if (feature) { this.coordinate_ = evt.coordinate; @@ -89,10 +89,10 @@ app.Drag.prototype.handleDownEvent = function(evt) { * @param {ol.MapBrowserEvent} evt Map browser event. */ app.Drag.prototype.handleDragEvent = function(evt) { - var deltaX = evt.coordinate[0] - this.coordinate_[0]; - var deltaY = evt.coordinate[1] - this.coordinate_[1]; + const deltaX = evt.coordinate[0] - this.coordinate_[0]; + const deltaY = evt.coordinate[1] - this.coordinate_[1]; - var geometry = this.feature_.getGeometry(); + const geometry = this.feature_.getGeometry(); geometry.translate(deltaX, deltaY); this.coordinate_[0] = evt.coordinate[0]; @@ -105,12 +105,12 @@ app.Drag.prototype.handleDragEvent = function(evt) { */ app.Drag.prototype.handleMoveEvent = function(evt) { if (this.cursor_) { - var map = evt.map; - var feature = map.forEachFeatureAtPixel(evt.pixel, - function(feature) { - return feature; - }); - var element = evt.map.getTargetElement(); + const map = evt.map; + const feature = map.forEachFeatureAtPixel(evt.pixel, + function(feature) { + return feature; + }); + const element = evt.map.getTargetElement(); if (feature) { if (element.style.cursor != this.cursor_) { this.previousCursor_ = element.style.cursor; @@ -134,17 +134,17 @@ app.Drag.prototype.handleUpEvent = function() { }; -var pointFeature = new Feature(new Point([0, 0])); +const pointFeature = new Feature(new Point([0, 0])); -var lineFeature = new Feature( - new LineString([[-1e7, 1e6], [-1e6, 3e6]])); +const lineFeature = new Feature( + new LineString([[-1e7, 1e6], [-1e6, 3e6]])); -var polygonFeature = new Feature( - new Polygon([[[-3e6, -1e6], [-3e6, 1e6], - [-1e6, 1e6], [-1e6, -1e6], [-3e6, -1e6]]])); +const polygonFeature = new Feature( + new Polygon([[[-3e6, -1e6], [-3e6, 1e6], + [-1e6, 1e6], [-1e6, -1e6], [-3e6, -1e6]]])); -var map = new Map({ +const map = new Map({ interactions: defaultInteractions().extend([new app.Drag()]), layers: [ new TileLayer({ diff --git a/examples/d3.js b/examples/d3.js index c0096cb8e8..193afd771f 100644 --- a/examples/d3.js +++ b/examples/d3.js @@ -9,7 +9,7 @@ import ImageCanvasSource from '../src/ol/source/ImageCanvas.js'; import Stamen from '../src/ol/source/Stamen.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new Stamen({ @@ -29,7 +29,7 @@ var map = new Map({ * Load the topojson data and create an ol.layer.Image for that data. */ d3.json('data/topojson/us.json', function(error, us) { - var features = topojson.feature(us, us.objects.counties); + const features = topojson.feature(us, us.objects.counties); /** * This function uses d3 to render the topojson features to a canvas. @@ -40,39 +40,39 @@ d3.json('data/topojson/us.json', function(error, us) { * @param {ol.proj.Projection} projection Projection. * @return {HTMLCanvasElement} A canvas element. */ - var canvasFunction = function(extent, resolution, pixelRatio, size, projection) { - var canvasWidth = size[0]; - var canvasHeight = size[1]; + const canvasFunction = function(extent, resolution, pixelRatio, size, projection) { + const canvasWidth = size[0]; + const canvasHeight = size[1]; - var canvas = d3.select(document.createElement('canvas')); + const canvas = d3.select(document.createElement('canvas')); canvas.attr('width', canvasWidth).attr('height', canvasHeight); - var context = canvas.node().getContext('2d'); + const context = canvas.node().getContext('2d'); - var d3Projection = d3.geoMercator().scale(1).translate([0, 0]); - var d3Path = d3.geoPath().projection(d3Projection); + const d3Projection = d3.geoMercator().scale(1).translate([0, 0]); + let d3Path = d3.geoPath().projection(d3Projection); - var pixelBounds = d3Path.bounds(features); - var pixelBoundsWidth = pixelBounds[1][0] - pixelBounds[0][0]; - var pixelBoundsHeight = pixelBounds[1][1] - pixelBounds[0][1]; + const pixelBounds = d3Path.bounds(features); + const pixelBoundsWidth = pixelBounds[1][0] - pixelBounds[0][0]; + const pixelBoundsHeight = pixelBounds[1][1] - pixelBounds[0][1]; - var geoBounds = d3.geoBounds(features); - var geoBoundsLeftBottom = fromLonLat(geoBounds[0], projection); - var geoBoundsRightTop = fromLonLat(geoBounds[1], projection); - var geoBoundsWidth = geoBoundsRightTop[0] - geoBoundsLeftBottom[0]; + const geoBounds = d3.geoBounds(features); + const geoBoundsLeftBottom = fromLonLat(geoBounds[0], projection); + const geoBoundsRightTop = fromLonLat(geoBounds[1], projection); + let geoBoundsWidth = geoBoundsRightTop[0] - geoBoundsLeftBottom[0]; if (geoBoundsWidth < 0) { geoBoundsWidth += getWidth(projection.getExtent()); } - var geoBoundsHeight = geoBoundsRightTop[1] - geoBoundsLeftBottom[1]; + const geoBoundsHeight = geoBoundsRightTop[1] - geoBoundsLeftBottom[1]; - var widthResolution = geoBoundsWidth / pixelBoundsWidth; - var heightResolution = geoBoundsHeight / pixelBoundsHeight; - var r = Math.max(widthResolution, heightResolution); - var scale = r / (resolution / pixelRatio); + const widthResolution = geoBoundsWidth / pixelBoundsWidth; + const heightResolution = geoBoundsHeight / pixelBoundsHeight; + const r = Math.max(widthResolution, heightResolution); + const scale = r / (resolution / pixelRatio); - var center = toLonLat(getCenter(extent), projection); + const center = toLonLat(getCenter(extent), projection); d3Projection.scale(scale).center(center) - .translate([canvasWidth / 2, canvasHeight / 2]); + .translate([canvasWidth / 2, canvasHeight / 2]); d3Path = d3Path.projection(d3Projection).context(context); d3Path(features); context.stroke(); @@ -80,7 +80,7 @@ d3.json('data/topojson/us.json', function(error, us) { return canvas.node(); }; - var layer = new ImageLayer({ + const layer = new ImageLayer({ source: new ImageCanvasSource({ canvasFunction: canvasFunction, projection: 'EPSG:3857' diff --git a/examples/device-orientation.js b/examples/device-orientation.js index 1b2147d94c..3ffe639e8e 100644 --- a/examples/device-orientation.js +++ b/examples/device-orientation.js @@ -6,11 +6,11 @@ import TileLayer from '../src/ol/layer/Tile.js'; import {toRadians} from '../src/ol/math.js'; import OSM from '../src/ol/source/OSM.js'; -var view = new View({ +const view = new View({ center: [0, 0], zoom: 2 }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -30,15 +30,15 @@ function el(id) { } -var gn = new GyroNorm(); +const gn = new GyroNorm(); gn.init().then(function() { gn.start(function(event) { - var center = view.getCenter(); - var resolution = view.getResolution(); - var alpha = toRadians(event.do.beta); - var beta = toRadians(event.do.beta); - var gamma = toRadians(event.do.gamma); + const center = view.getCenter(); + const resolution = view.getResolution(); + const alpha = toRadians(event.do.beta); + const beta = toRadians(event.do.beta); + const gamma = toRadians(event.do.gamma); el('alpha').innerText = alpha + ' [rad]'; el('beta').innerText = beta + ' [rad]'; diff --git a/examples/drag-and-drop-image-vector.js b/examples/drag-and-drop-image-vector.js index 4678ffbee0..84ff00979a 100644 --- a/examples/drag-and-drop-image-vector.js +++ b/examples/drag-and-drop-image-vector.js @@ -17,7 +17,7 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var defaultStyle = { +const defaultStyle = { 'Point': new Style({ image: new CircleStyle({ fill: new Fill({ @@ -74,8 +74,8 @@ var defaultStyle = { }) }; -var styleFunction = function(feature, resolution) { - var featureStyleFunction = feature.getStyleFunction(); +const styleFunction = function(feature, resolution) { + const featureStyleFunction = feature.getStyleFunction(); if (featureStyleFunction) { return featureStyleFunction.call(feature, resolution); } else { @@ -83,7 +83,7 @@ var styleFunction = function(feature, resolution) { } }; -var dragAndDropInteraction = new DragAndDrop({ +const dragAndDropInteraction = new DragAndDrop({ formatConstructors: [ GPX, GeoJSON, @@ -93,7 +93,7 @@ var dragAndDropInteraction = new DragAndDrop({ ] }); -var map = new Map({ +const map = new Map({ interactions: defaultInteractions().extend([dragAndDropInteraction]), layers: [ new TileLayer({ @@ -111,7 +111,7 @@ var map = new Map({ }); dragAndDropInteraction.on('addfeatures', function(event) { - var vectorSource = new VectorSource({ + const vectorSource = new VectorSource({ features: event.features }); map.addLayer(new VectorLayer({ @@ -122,14 +122,14 @@ dragAndDropInteraction.on('addfeatures', function(event) { map.getView().fit(vectorSource.getExtent()); }); -var displayFeatureInfo = function(pixel) { - var features = []; +const displayFeatureInfo = function(pixel) { + const features = []; map.forEachFeatureAtPixel(pixel, function(feature) { features.push(feature); }); if (features.length > 0) { - var info = []; - var i, ii; + const info = []; + let i, ii; for (i = 0, ii = features.length; i < ii; ++i) { info.push(features[i].get('name')); } @@ -143,7 +143,7 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); + const pixel = map.getEventPixel(evt.originalEvent); displayFeatureInfo(pixel); }); diff --git a/examples/drag-and-drop.js b/examples/drag-and-drop.js index 4bfdd07686..dafcdc47dc 100644 --- a/examples/drag-and-drop.js +++ b/examples/drag-and-drop.js @@ -17,7 +17,7 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var defaultStyle = { +const defaultStyle = { 'Point': new Style({ image: new CircleStyle({ fill: new Fill({ @@ -74,8 +74,8 @@ var defaultStyle = { }) }; -var styleFunction = function(feature, resolution) { - var featureStyleFunction = feature.getStyleFunction(); +const styleFunction = function(feature, resolution) { + const featureStyleFunction = feature.getStyleFunction(); if (featureStyleFunction) { return featureStyleFunction.call(feature, resolution); } else { @@ -83,7 +83,7 @@ var styleFunction = function(feature, resolution) { } }; -var dragAndDropInteraction = new DragAndDrop({ +const dragAndDropInteraction = new DragAndDrop({ formatConstructors: [ GPX, GeoJSON, @@ -93,7 +93,7 @@ var dragAndDropInteraction = new DragAndDrop({ ] }); -var map = new Map({ +const map = new Map({ interactions: defaultInteractions().extend([dragAndDropInteraction]), layers: [ new TileLayer({ @@ -111,7 +111,7 @@ var map = new Map({ }); dragAndDropInteraction.on('addfeatures', function(event) { - var vectorSource = new VectorSource({ + const vectorSource = new VectorSource({ features: event.features }); map.addLayer(new VectorLayer({ @@ -121,14 +121,14 @@ dragAndDropInteraction.on('addfeatures', function(event) { map.getView().fit(vectorSource.getExtent()); }); -var displayFeatureInfo = function(pixel) { - var features = []; +const displayFeatureInfo = function(pixel) { + const features = []; map.forEachFeatureAtPixel(pixel, function(feature) { features.push(feature); }); if (features.length > 0) { - var info = []; - var i, ii; + const info = []; + let i, ii; for (i = 0, ii = features.length; i < ii; ++i) { info.push(features[i].get('name')); } @@ -142,7 +142,7 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); + const pixel = map.getEventPixel(evt.originalEvent); displayFeatureInfo(pixel); }); diff --git a/examples/drag-rotate-and-zoom.js b/examples/drag-rotate-and-zoom.js index 8a33fd33a8..22ecf9adfa 100644 --- a/examples/drag-rotate-and-zoom.js +++ b/examples/drag-rotate-and-zoom.js @@ -6,7 +6,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ interactions: defaultInteractions().extend([ new DragRotateAndZoom() ]), diff --git a/examples/draw-and-modify-features.js b/examples/draw-and-modify-features.js index 19cab51e58..4da34fced8 100644 --- a/examples/draw-and-modify-features.js +++ b/examples/draw-and-modify-features.js @@ -12,12 +12,12 @@ import Fill from '../src/ol/style/Fill.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var source = new VectorSource(); -var vector = new VectorLayer({ +const source = new VectorSource(); +const vector = new VectorLayer({ source: source, style: new Style({ fill: new Fill({ @@ -36,7 +36,7 @@ var vector = new VectorLayer({ }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ @@ -45,11 +45,11 @@ var map = new Map({ }) }); -var modify = new Modify({source: source}); +const modify = new Modify({source: source}); map.addInteraction(modify); -var draw, snap; // global so we can remove them later -var typeSelect = document.getElementById('type'); +let draw, snap; // global so we can remove them later +const typeSelect = document.getElementById('type'); function addInteractions() { draw = new Draw({ diff --git a/examples/draw-features.js b/examples/draw-features.js index 06c9332ba7..f40e7e9df1 100644 --- a/examples/draw-features.js +++ b/examples/draw-features.js @@ -6,17 +6,17 @@ import VectorLayer from '../src/ol/layer/Vector.js'; import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var source = new VectorSource({wrapX: false}); +const source = new VectorSource({wrapX: false}); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: source }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ @@ -25,11 +25,11 @@ var map = new Map({ }) }); -var typeSelect = document.getElementById('type'); +const typeSelect = document.getElementById('type'); -var draw; // global so we can remove it later +let draw; // global so we can remove it later function addInteraction() { - var value = typeSelect.value; + const value = typeSelect.value; if (value !== 'None') { draw = new Draw({ source: source, diff --git a/examples/draw-freehand.js b/examples/draw-freehand.js index 0450693466..1ac4aa27c6 100644 --- a/examples/draw-freehand.js +++ b/examples/draw-freehand.js @@ -6,17 +6,17 @@ import VectorLayer from '../src/ol/layer/Vector.js'; import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var source = new VectorSource({wrapX: false}); +const source = new VectorSource({wrapX: false}); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: source }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ @@ -25,11 +25,11 @@ var map = new Map({ }) }); -var typeSelect = document.getElementById('type'); +const typeSelect = document.getElementById('type'); -var draw; // global so we can remove it later +let draw; // global so we can remove it later function addInteraction() { - var value = typeSelect.value; + const value = typeSelect.value; if (value !== 'None') { draw = new Draw({ source: source, diff --git a/examples/draw-shapes.js b/examples/draw-shapes.js index ea32c589ae..e8eb59c1b4 100644 --- a/examples/draw-shapes.js +++ b/examples/draw-shapes.js @@ -7,17 +7,17 @@ import VectorLayer from '../src/ol/layer/Vector.js'; import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var source = new VectorSource({wrapX: false}); +const source = new VectorSource({wrapX: false}); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: source }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ @@ -26,13 +26,13 @@ var map = new Map({ }) }); -var typeSelect = document.getElementById('type'); +const typeSelect = document.getElementById('type'); -var draw; // global so we can remove it later +let draw; // global so we can remove it later function addInteraction() { - var value = typeSelect.value; + let value = typeSelect.value; if (value !== 'None') { - var geometryFunction; + let geometryFunction; if (value === 'Square') { value = 'Circle'; geometryFunction = Draw.createRegularPolygon(4); @@ -45,19 +45,19 @@ function addInteraction() { if (!geometry) { geometry = new Polygon(null); } - var center = coordinates[0]; - var last = coordinates[1]; - var dx = center[0] - last[0]; - var dy = center[1] - last[1]; - var radius = Math.sqrt(dx * dx + dy * dy); - var rotation = Math.atan2(dy, dx); - var newCoordinates = []; - var numPoints = 12; - for (var i = 0; i < numPoints; ++i) { - var angle = rotation + i * 2 * Math.PI / numPoints; - var fraction = i % 2 === 0 ? 1 : 0.5; - var offsetX = radius * fraction * Math.cos(angle); - var offsetY = radius * fraction * Math.sin(angle); + const center = coordinates[0]; + const last = coordinates[1]; + const dx = center[0] - last[0]; + const dy = center[1] - last[1]; + const radius = Math.sqrt(dx * dx + dy * dy); + const rotation = Math.atan2(dy, dx); + const newCoordinates = []; + const numPoints = 12; + for (let i = 0; i < numPoints; ++i) { + const angle = rotation + i * 2 * Math.PI / numPoints; + const fraction = i % 2 === 0 ? 1 : 0.5; + const offsetX = radius * fraction * Math.cos(angle); + const offsetY = radius * fraction * Math.sin(angle); newCoordinates.push([center[0] + offsetX, center[1] + offsetY]); } newCoordinates.push(newCoordinates[0].slice()); diff --git a/examples/dynamic-data.js b/examples/dynamic-data.js index 320aec8bb1..09dee9fcab 100644 --- a/examples/dynamic-data.js +++ b/examples/dynamic-data.js @@ -10,7 +10,7 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -23,7 +23,7 @@ var map = new Map({ }) }); -var imageStyle = new Style({ +const imageStyle = new Style({ image: new CircleStyle({ radius: 5, snapToPixel: false, @@ -32,7 +32,7 @@ var imageStyle = new Style({ }) }); -var headInnerImageStyle = new Style({ +const headInnerImageStyle = new Style({ image: new CircleStyle({ radius: 2, snapToPixel: false, @@ -40,7 +40,7 @@ var headInnerImageStyle = new Style({ }) }); -var headOuterImageStyle = new Style({ +const headOuterImageStyle = new Style({ image: new CircleStyle({ radius: 5, snapToPixel: false, @@ -48,27 +48,27 @@ var headOuterImageStyle = new Style({ }) }); -var n = 200; -var omegaTheta = 30000; // Rotation period in ms -var R = 7e6; -var r = 2e6; -var p = 2e6; +const n = 200; +const omegaTheta = 30000; // Rotation period in ms +const R = 7e6; +const r = 2e6; +const p = 2e6; map.on('postcompose', function(event) { - var vectorContext = event.vectorContext; - var frameState = event.frameState; - var theta = 2 * Math.PI * frameState.time / omegaTheta; - var coordinates = []; - var i; + const vectorContext = event.vectorContext; + const frameState = event.frameState; + const theta = 2 * Math.PI * frameState.time / omegaTheta; + const coordinates = []; + let i; for (i = 0; i < n; ++i) { - var t = theta + 2 * Math.PI * i / n; - var x = (R + r) * Math.cos(t) + p * Math.cos((R + r) * t / r); - var y = (R + r) * Math.sin(t) + p * Math.sin((R + r) * t / r); + const t = theta + 2 * Math.PI * i / n; + const x = (R + r) * Math.cos(t) + p * Math.cos((R + r) * t / r); + const y = (R + r) * Math.sin(t) + p * Math.sin((R + r) * t / r); coordinates.push([x, y]); } vectorContext.setStyle(imageStyle); vectorContext.drawGeometry(new MultiPoint(coordinates)); - var headPoint = new Point(coordinates[coordinates.length - 1]); + const headPoint = new Point(coordinates[coordinates.length - 1]); vectorContext.setStyle(headOuterImageStyle); vectorContext.drawGeometry(headPoint); diff --git a/examples/earthquake-clusters.js b/examples/earthquake-clusters.js index c6131c996a..2530e0afe9 100644 --- a/examples/earthquake-clusters.js +++ b/examples/earthquake-clusters.js @@ -17,21 +17,21 @@ import Style from '../src/ol/style/Style.js'; import Text from '../src/ol/style/Text.js'; -var earthquakeFill = new Fill({ +const earthquakeFill = new Fill({ color: 'rgba(255, 153, 0, 0.8)' }); -var earthquakeStroke = new Stroke({ +const earthquakeStroke = new Stroke({ color: 'rgba(255, 204, 0, 0.2)', width: 1 }); -var textFill = new Fill({ +const textFill = new Fill({ color: '#fff' }); -var textStroke = new Stroke({ +const textStroke = new Stroke({ color: 'rgba(0, 0, 0, 0.6)', width: 3 }); -var invisibleFill = new Fill({ +const invisibleFill = new Fill({ color: 'rgba(255, 255, 255, 0.01)' }); @@ -39,9 +39,9 @@ function createEarthquakeStyle(feature) { // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a // standards-violating tag in each Placemark. We extract it // from the Placemark's name instead. - var name = feature.get('name'); - var magnitude = parseFloat(name.substr(2)); - var radius = 5 + 20 * (magnitude - 5); + const name = feature.get('name'); + const magnitude = parseFloat(name.substr(2)); + const radius = 5 + 20 * (magnitude - 5); return new Style({ geometry: feature.getGeometry(), @@ -56,16 +56,17 @@ function createEarthquakeStyle(feature) { }); } -var maxFeatureCount, vector; -function calculateClusterInfo(resolution) { +let maxFeatureCount; +let vector = null; +const calculateClusterInfo = function(resolution) { maxFeatureCount = 0; - var features = vector.getSource().getFeatures(); - var feature, radius; - for (var i = features.length - 1; i >= 0; --i) { + const features = vector.getSource().getFeatures(); + let feature, radius; + for (let i = features.length - 1; i >= 0; --i) { feature = features[i]; - var originalFeatures = feature.get('features'); - var extent = _ol_extent_.createEmpty(); - var j, jj; + const originalFeatures = feature.get('features'); + const extent = _ol_extent_.createEmpty(); + let j, jj; for (j = 0, jj = originalFeatures.length; j < jj; ++j) { _ol_extent_.extend(extent, originalFeatures[j].getGeometry().getExtent()); } @@ -74,16 +75,16 @@ function calculateClusterInfo(resolution) { resolution; feature.set('radius', radius); } -} +}; -var currentResolution; +let currentResolution; function styleFunction(feature, resolution) { if (resolution != currentResolution) { calculateClusterInfo(resolution); currentResolution = resolution; } - var style; - var size = feature.get('features').length; + let style; + const size = feature.get('features').length; if (size > 1) { style = new Style({ image: new CircleStyle({ @@ -99,22 +100,22 @@ function styleFunction(feature, resolution) { }) }); } else { - var originalFeature = feature.get('features')[0]; + const originalFeature = feature.get('features')[0]; style = createEarthquakeStyle(originalFeature); } return style; } function selectStyleFunction(feature) { - var styles = [new Style({ + const styles = [new Style({ image: new CircleStyle({ radius: feature.get('radius'), fill: invisibleFill }) })]; - var originalFeatures = feature.get('features'); - var originalFeature; - for (var i = originalFeatures.length - 1; i >= 0; --i) { + const originalFeatures = feature.get('features'); + let originalFeature; + for (let i = originalFeatures.length - 1; i >= 0; --i) { originalFeature = originalFeatures[i]; styles.push(createEarthquakeStyle(originalFeature)); } @@ -134,13 +135,13 @@ vector = new VectorLayer({ style: styleFunction }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new Stamen({ layer: 'toner' }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], interactions: defaultInteractions().extend([new Select({ condition: function(evt) { diff --git a/examples/earthquake-custom-symbol.js b/examples/earthquake-custom-symbol.js index 58c2c43bc8..4bfbf58736 100644 --- a/examples/earthquake-custom-symbol.js +++ b/examples/earthquake-custom-symbol.js @@ -13,28 +13,28 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var symbol = [[0, 0], [4, 2], [6, 0], [10, 5], [6, 3], [4, 5], [0, 0]]; -var scale; -var scaleFunction = function(coordinate) { +const symbol = [[0, 0], [4, 2], [6, 0], [10, 5], [6, 3], [4, 5], [0, 0]]; +let scale; +const scaleFunction = function(coordinate) { return [coordinate[0] * scale, coordinate[1] * scale]; }; -var styleCache = {}; -var styleFunction = function(feature) { +const styleCache = {}; +const styleFunction = function(feature) { // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a // standards-violating tag in each Placemark. We extract it from // the Placemark's name instead. - var name = feature.get('name'); - var magnitude = parseFloat(name.substr(2)); - var size = parseInt(10 + 40 * (magnitude - 5), 10); + const name = feature.get('name'); + const magnitude = parseFloat(name.substr(2)); + const size = parseInt(10 + 40 * (magnitude - 5), 10); scale = size / 10; - var style = styleCache[size]; + let style = styleCache[size]; if (!style) { - var canvas = + const canvas = /** @type {HTMLCanvasElement} */ (document.createElement('canvas')); - var vectorContext = _ol_render_.toContext( - /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d')), - {size: [size, size], pixelRatio: 1}); + const vectorContext = _ol_render_.toContext( + /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d')), + {size: [size, size], pixelRatio: 1}); vectorContext.setStyle(new Style({ fill: new Fill({color: 'rgba(255, 153, 0, 0.4)'}), stroke: new Stroke({color: 'rgba(255, 204, 0, 0.2)', width: 2}) @@ -52,7 +52,7 @@ var styleFunction = function(feature) { return style; }; -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ url: 'data/kml/2012_Earthquakes_Mag5.kml', format: new KML({ @@ -62,13 +62,13 @@ var vector = new VectorLayer({ style: styleFunction }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new Stamen({ layer: 'toner' }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ diff --git a/examples/epsg-4326.js b/examples/epsg-4326.js index 7e0850ecfc..02d58dbf8f 100644 --- a/examples/epsg-4326.js +++ b/examples/epsg-4326.js @@ -6,7 +6,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import TileWMS from '../src/ol/source/TileWMS.js'; -var layers = [ +const layers = [ new TileLayer({ source: new TileWMS({ url: 'https://ahocevar.com/geoserver/wms', @@ -18,7 +18,7 @@ var layers = [ }) ]; -var map = new Map({ +const map = new Map({ controls: defaultControls().extend([ new ScaleLine({ units: 'degrees' diff --git a/examples/export-map.js b/examples/export-map.js index 339ecd2ad9..710c225ef0 100644 --- a/examples/export-map.js +++ b/examples/export-map.js @@ -9,7 +9,7 @@ import VectorLayer from '../src/ol/layer/Vector.js'; import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -35,7 +35,7 @@ var map = new Map({ document.getElementById('export-png').addEventListener('click', function() { map.once('postcompose', function(event) { - var canvas = event.context.canvas; + const canvas = event.context.canvas; if (navigator.msSaveBlob) { navigator.msSaveBlob(canvas.msToBlob(), 'map.png'); } else { diff --git a/examples/export-pdf.js b/examples/export-pdf.js index c1bdcd2a60..6b89e5a2d8 100644 --- a/examples/export-pdf.js +++ b/examples/export-pdf.js @@ -8,25 +8,25 @@ import VectorLayer from '../src/ol/layer/Vector.js'; import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var format = new WKT(); -var feature = format.readFeature( - 'POLYGON((10.689697265625 -25.0927734375, 34.595947265625 ' + +const format = new WKT(); +const feature = format.readFeature( + 'POLYGON((10.689697265625 -25.0927734375, 34.595947265625 ' + '-20.1708984375, 38.814697265625 -35.6396484375, 13.502197265625 ' + '-39.1552734375, 10.689697265625 -25.0927734375))'); feature.getGeometry().transform('EPSG:4326', 'EPSG:3857'); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ features: [feature] }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', controls: defaultControls({ @@ -41,7 +41,7 @@ var map = new Map({ }); -var dims = { +const dims = { a0: [1189, 841], a1: [841, 594], a2: [594, 420], @@ -50,39 +50,39 @@ var dims = { a5: [210, 148] }; -var loading = 0; -var loaded = 0; +let loading = 0; +let loaded = 0; -var exportButton = document.getElementById('export-pdf'); +const exportButton = document.getElementById('export-pdf'); exportButton.addEventListener('click', function() { exportButton.disabled = true; document.body.style.cursor = 'progress'; - var format = document.getElementById('format').value; - var resolution = document.getElementById('resolution').value; - var dim = dims[format]; - var width = Math.round(dim[0] * resolution / 25.4); - var height = Math.round(dim[1] * resolution / 25.4); - var size = /** @type {ol.Size} */ (map.getSize()); - var extent = map.getView().calculateExtent(size); + const format = document.getElementById('format').value; + const resolution = document.getElementById('resolution').value; + const dim = dims[format]; + const width = Math.round(dim[0] * resolution / 25.4); + const height = Math.round(dim[1] * resolution / 25.4); + const size = /** @type {ol.Size} */ (map.getSize()); + const extent = map.getView().calculateExtent(size); - var source = raster.getSource(); + const source = raster.getSource(); - var tileLoadStart = function() { + const tileLoadStart = function() { ++loading; }; - var tileLoadEnd = function() { + function tileLoadEnd() { ++loaded; if (loading === loaded) { - var canvas = this; + const canvas = this; window.setTimeout(function() { loading = 0; loaded = 0; - var data = canvas.toDataURL('image/png'); - var pdf = new jsPDF('landscape', undefined, format); + const data = canvas.toDataURL('image/png'); + const pdf = new jsPDF('landscape', undefined, format); pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]); pdf.save('map.pdf'); source.un('tileloadstart', tileLoadStart); @@ -95,7 +95,7 @@ exportButton.addEventListener('click', function() { document.body.style.cursor = 'auto'; }, 100); } - }; + } map.once('postcompose', function(event) { source.on('tileloadstart', tileLoadStart); diff --git a/examples/extent-interaction.js b/examples/extent-interaction.js index b048326402..a0ba78599c 100644 --- a/examples/extent-interaction.js +++ b/examples/extent-interaction.js @@ -8,12 +8,12 @@ import VectorLayer from '../src/ol/layer/Vector.js'; import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ url: 'data/geojson/countries.geojson', format: new GeoJSON() }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -29,7 +29,7 @@ var map = new Map({ }) }); -var extent = new ExtentInteraction({ +const extent = new ExtentInteraction({ condition: _ol_events_condition_.platformModifierKeyOnly }); map.addInteraction(extent); diff --git a/examples/feature-animation.js b/examples/feature-animation.js index 442e971df2..1908d9acb1 100644 --- a/examples/feature-animation.js +++ b/examples/feature-animation.js @@ -15,7 +15,7 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM({ @@ -35,38 +35,38 @@ var map = new Map({ }) }); -var source = new VectorSource({ +const source = new VectorSource({ wrapX: false }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: source }); map.addLayer(vector); function addRandomFeature() { - var x = Math.random() * 360 - 180; - var y = Math.random() * 180 - 90; - var geom = new Point(fromLonLat([x, y])); - var feature = new Feature(geom); + const x = Math.random() * 360 - 180; + const y = Math.random() * 180 - 90; + const geom = new Point(fromLonLat([x, y])); + const feature = new Feature(geom); source.addFeature(feature); } -var duration = 3000; +const duration = 3000; function flash(feature) { - var start = new Date().getTime(); - var listenerKey; + const start = new Date().getTime(); + const listenerKey = map.on('postcompose', animate); function animate(event) { - var vectorContext = event.vectorContext; - var frameState = event.frameState; - var flashGeom = feature.getGeometry().clone(); - var elapsed = frameState.time - start; - var elapsedRatio = elapsed / duration; + const vectorContext = event.vectorContext; + const frameState = event.frameState; + const flashGeom = feature.getGeometry().clone(); + const elapsed = frameState.time - start; + const elapsedRatio = elapsed / duration; // radius will be 5 at start and 30 at end. - var radius = easeOut(elapsedRatio) * 25 + 5; - var opacity = easeOut(1 - elapsedRatio); + const radius = easeOut(elapsedRatio) * 25 + 5; + const opacity = easeOut(1 - elapsedRatio); - var style = new Style({ + const style = new Style({ image: new CircleStyle({ radius: radius, snapToPixel: false, @@ -86,7 +86,6 @@ function flash(feature) { // tell OpenLayers to continue postcompose animation map.render(); } - listenerKey = map.on('postcompose', animate); } source.on('addfeature', function(e) { diff --git a/examples/feature-move-animation.js b/examples/feature-move-animation.js index fd34c697c1..007dcd5e40 100644 --- a/examples/feature-move-animation.js +++ b/examples/feature-move-animation.js @@ -15,7 +15,7 @@ import Style from '../src/ol/style/Style.js'; // This long string is placed here due to jsFiddle limitations. // It is usually loaded with AJAX. -var polyline = [ +const polyline = [ 'hldhx@lnau`BCG_EaC??cFjAwDjF??uBlKMd@}@z@??aC^yk@z_@se@b[wFdE??wFfE}N', 'fIoGxB_I\\gG}@eHoCyTmPqGaBaHOoD\\??yVrGotA|N??o[N_STiwAtEmHGeHcAkiA}^', 'aMyBiHOkFNoI`CcVvM??gG^gF_@iJwC??eCcA]OoL}DwFyCaCgCcCwDcGwHsSoX??wI_E', @@ -57,34 +57,34 @@ var polyline = [ '~@ym@yjA??a@cFd@kBrCgDbAUnAcBhAyAdk@et@??kF}D??OL' ].join(''); -var route = /** @type {ol.geom.LineString} */ (new Polyline({ +const route = /** @type {ol.geom.LineString} */ (new Polyline({ factor: 1e6 }).readGeometry(polyline, { dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' })); -var routeCoords = route.getCoordinates(); -var routeLength = routeCoords.length; +const routeCoords = route.getCoordinates(); +const routeLength = routeCoords.length; -var routeFeature = new Feature({ +const routeFeature = new Feature({ type: 'route', geometry: route }); -var geoMarker = new Feature({ +const geoMarker = new Feature({ type: 'geoMarker', geometry: new Point(routeCoords[0]) }); -var startMarker = new Feature({ +const startMarker = new Feature({ type: 'icon', geometry: new Point(routeCoords[0]) }); -var endMarker = new Feature({ +const endMarker = new Feature({ type: 'icon', geometry: new Point(routeCoords[routeLength - 1]) }); -var styles = { +const styles = { 'route': new Style({ stroke: new Stroke({ width: 6, color: [237, 212, 0, 0.8] @@ -108,12 +108,12 @@ var styles = { }) }; -var animating = false; -var speed, now; -var speedInput = document.getElementById('speed'); -var startButton = document.getElementById('start-animation'); +let animating = false; +let speed, now; +const speedInput = document.getElementById('speed'); +const startButton = document.getElementById('start-animation'); -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: new VectorSource({ features: [routeFeature, geoMarker, startMarker, endMarker] }), @@ -126,8 +126,8 @@ var vectorLayer = new VectorLayer({ } }); -var center = [-5639523.95, -3501274.52]; -var map = new Map({ +const center = [-5639523.95, -3501274.52]; +const map = new Map({ target: document.getElementById('map'), loadTilesWhileAnimating: true, view: new View({ @@ -147,23 +147,23 @@ var map = new Map({ ] }); -var moveFeature = function(event) { - var vectorContext = event.vectorContext; - var frameState = event.frameState; +const moveFeature = function(event) { + const vectorContext = event.vectorContext; + const frameState = event.frameState; if (animating) { - var elapsedTime = frameState.time - now; + const elapsedTime = frameState.time - now; // here the trick to increase speed is to jump some indexes // on lineString coordinates - var index = Math.round(speed * elapsedTime / 1000); + const index = Math.round(speed * elapsedTime / 1000); if (index >= routeLength) { stopAnimation(true); return; } - var currentPoint = new Point(routeCoords[index]); - var feature = new Feature(currentPoint); + const currentPoint = new Point(routeCoords[index]); + const feature = new Feature(currentPoint); vectorContext.drawFeature(feature, styles.geoMarker); } // tell OpenLayers to continue the postcompose animation @@ -196,9 +196,9 @@ function stopAnimation(ended) { startButton.textContent = 'Start Animation'; // if animation cancelled set the marker at the beginning - var coord = ended ? routeCoords[routeLength - 1] : routeCoords[0]; + const coord = ended ? routeCoords[routeLength - 1] : routeCoords[0]; /** @type {ol.geom.Point} */ (geoMarker.getGeometry()) - .setCoordinates(coord); + .setCoordinates(coord); //remove listener map.un('postcompose', moveFeature); } diff --git a/examples/flight-animation.js b/examples/flight-animation.js index aacd445b96..270e241894 100644 --- a/examples/flight-animation.js +++ b/examples/flight-animation.js @@ -10,7 +10,7 @@ import VectorSource from '../src/ol/source/Vector.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new Stamen({ @@ -25,77 +25,39 @@ var map = new Map({ }) }); -var style = new Style({ +const style = new Style({ stroke: new Stroke({ color: '#EAE911', width: 2 }) }); -var flightsSource; -var addLater = function(feature, timeout) { - window.setTimeout(function() { - feature.set('start', new Date().getTime()); - flightsSource.addFeature(feature); - }, timeout); -}; - -var pointsPerMs = 0.1; -var animateFlights = function(event) { - var vectorContext = event.vectorContext; - var frameState = event.frameState; - vectorContext.setStyle(style); - - var features = flightsSource.getFeatures(); - for (var i = 0; i < features.length; i++) { - var feature = features[i]; - if (!feature.get('finished')) { - // only draw the lines for which the animation has not finished yet - var coords = feature.getGeometry().getCoordinates(); - var elapsedTime = frameState.time - feature.get('start'); - var elapsedPoints = elapsedTime * pointsPerMs; - - if (elapsedPoints >= coords.length) { - feature.set('finished', true); - } - - var maxIndex = Math.min(elapsedPoints, coords.length); - var currentLine = new LineString(coords.slice(0, maxIndex)); - - // directly draw the line with the vector context - vectorContext.drawGeometry(currentLine); - } - } - // tell OpenLayers to continue the animation - map.render(); -}; - -flightsSource = new VectorSource({ +const flightsSource = new VectorSource({ wrapX: false, attributions: 'Flight data by ' + 'OpenFlights,', loader: function() { - var url = 'data/openflights/flights.json'; + const url = 'data/openflights/flights.json'; fetch(url).then(function(response) { return response.json(); }).then(function(json) { - var flightsData = json.flights; - for (var i = 0; i < flightsData.length; i++) { - var flight = flightsData[i]; - var from = flight[0]; - var to = flight[1]; + const flightsData = json.flights; + for (let i = 0; i < flightsData.length; i++) { + const flight = flightsData[i]; + const from = flight[0]; + const to = flight[1]; // create an arc circle between the two locations - var arcGenerator = new arc.GreatCircle( - {x: from[1], y: from[0]}, - {x: to[1], y: to[0]}); + const arcGenerator = new arc.GreatCircle( + {x: from[1], y: from[0]}, + {x: to[1], y: to[0]}); - var arcLine = arcGenerator.Arc(100, {offset: 10}); + const arcLine = arcGenerator.Arc(100, {offset: 10}); if (arcLine.geometries.length === 1) { - var line = new LineString(arcLine.geometries[0].coords); + const line = new LineString(arcLine.geometries[0].coords); line.transform('EPSG:4326', 'EPSG:3857'); - var feature = new Feature({ + const feature = new Feature({ geometry: line, finished: false }); @@ -109,7 +71,7 @@ flightsSource = new VectorSource({ } }); -var flightsLayer = new VectorLayer({ +const flightsLayer = new VectorLayer({ source: flightsSource, style: function(feature) { // if the animation is still active for a feature, do not @@ -121,4 +83,42 @@ var flightsLayer = new VectorLayer({ } } }); + map.addLayer(flightsLayer); + +const pointsPerMs = 0.1; +function animateFlights(event) { + const vectorContext = event.vectorContext; + const frameState = event.frameState; + vectorContext.setStyle(style); + + const features = flightsSource.getFeatures(); + for (let i = 0; i < features.length; i++) { + const feature = features[i]; + if (!feature.get('finished')) { + // only draw the lines for which the animation has not finished yet + const coords = feature.getGeometry().getCoordinates(); + const elapsedTime = frameState.time - feature.get('start'); + const elapsedPoints = elapsedTime * pointsPerMs; + + if (elapsedPoints >= coords.length) { + feature.set('finished', true); + } + + const maxIndex = Math.min(elapsedPoints, coords.length); + const currentLine = new LineString(coords.slice(0, maxIndex)); + + // directly draw the line with the vector context + vectorContext.drawGeometry(currentLine); + } + } + // tell OpenLayers to continue the animation + map.render(); +} + +function addLater(feature, timeout) { + window.setTimeout(function() { + feature.set('start', new Date().getTime()); + flightsSource.addFeature(feature); + }, timeout); +} diff --git a/examples/fractal.js b/examples/fractal.js index 8600e2b075..1953c417bd 100644 --- a/examples/fractal.js +++ b/examples/fractal.js @@ -5,25 +5,25 @@ import LineString from '../src/ol/geom/LineString.js'; import VectorLayer from '../src/ol/layer/Vector.js'; import VectorSource from '../src/ol/source/Vector.js'; -var radius = 10e6; -var cos30 = Math.cos(Math.PI / 6); -var sin30 = Math.sin(Math.PI / 6); -var rise = radius * sin30; -var run = radius * cos30; +const radius = 10e6; +const cos30 = Math.cos(Math.PI / 6); +const sin30 = Math.sin(Math.PI / 6); +const rise = radius * sin30; +const run = radius * cos30; -var triangle = new LineString([ +const triangle = new LineString([ [0, radius], [run, -rise], [-run, -rise], [0, radius] ]); -var feature = new Feature(triangle); +const feature = new Feature(triangle); -var layer = new VectorLayer({ +const layer = new VectorLayer({ source: new VectorSource({ features: [feature] }) }); -var map = new Map({ +const map = new Map({ layers: [layer], target: 'map', view: new View({ @@ -33,44 +33,44 @@ var map = new Map({ }); function makeFractal(depth) { - var geometry = triangle.clone(); - var graph = coordsToGraph(geometry.getCoordinates()); - for (var i = 0; i < depth; ++i) { - var node = graph; + const geometry = triangle.clone(); + const graph = coordsToGraph(geometry.getCoordinates()); + for (let i = 0; i < depth; ++i) { + let node = graph; while (node.next) { - var next = node.next; + const next = node.next; injectNodes(node); node = next; } } - var coordinates = graphToCoords(graph); + const coordinates = graphToCoords(graph); document.getElementById('count').innerHTML = coordinates.length; geometry.setCoordinates(coordinates); feature.setGeometry(geometry); } function injectNodes(startNode) { - var endNode = startNode.next; + const endNode = startNode.next; - var start = startNode.point; - var end = startNode.next.point; - var dx = end[0] - start[0]; - var dy = end[1] - start[1]; + const start = startNode.point; + const end = startNode.next.point; + const dx = end[0] - start[0]; + const dy = end[1] - start[1]; // first point at 1/3 along the segment - var firstNode = { + const firstNode = { point: [start[0] + dx / 3, start[1] + dy / 3] }; // second point at peak of _/\_ - var r = Math.sqrt(dx * dx + dy * dy) / (2 * cos30); - var a = Math.atan2(dy, dx) + Math.PI / 6; - var secondNode = { + const r = Math.sqrt(dx * dx + dy * dy) / (2 * cos30); + const a = Math.atan2(dy, dx) + Math.PI / 6; + const secondNode = { point: [start[0] + r * Math.cos(a), start[1] + r * Math.sin(a)] }; // third point at 2/3 along the segment - var thirdNode = { + const thirdNode = { point: [end[0] - dx / 3, end[1] - dy / 3] }; @@ -82,11 +82,11 @@ function injectNodes(startNode) { function coordsToGraph(coordinates) { - var graph = { + const graph = { point: coordinates[0] }; - var length = coordinates.length; - for (var level = 0, node = graph; level < length - 1; ++level) { + const length = coordinates.length; + for (let level = 0, node = graph; level < length - 1; ++level) { node.next = { point: coordinates[level + 1] }; @@ -96,20 +96,20 @@ function coordsToGraph(coordinates) { } function graphToCoords(graph) { - var coordinates = [graph.point]; - for (var node = graph, i = 1; node.next; node = node.next, ++i) { + const coordinates = [graph.point]; + for (let node = graph, i = 1; node.next; node = node.next, ++i) { coordinates[i] = node.next.point; } return coordinates; } -var depthInput = document.getElementById('depth'); +const depthInput = document.getElementById('depth'); function update() { makeFractal(Number(depthInput.value)); } -var updateTimer; +let updateTimer; /** diff --git a/examples/full-screen-drag-rotate-and-zoom.js b/examples/full-screen-drag-rotate-and-zoom.js index 08eb37458b..ff83c11a19 100644 --- a/examples/full-screen-drag-rotate-and-zoom.js +++ b/examples/full-screen-drag-rotate-and-zoom.js @@ -8,7 +8,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import BingMaps from '../src/ol/source/BingMaps.js'; -var map = new Map({ +const map = new Map({ controls: defaultControls().extend([ new FullScreen() ]), diff --git a/examples/full-screen-source.js b/examples/full-screen-source.js index 5540db3b7d..639690a167 100644 --- a/examples/full-screen-source.js +++ b/examples/full-screen-source.js @@ -6,12 +6,12 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var view = new View({ +const view = new View({ center: [-9101767, 2822912], zoom: 14 }); -var map = new Map({ +const map = new Map({ controls: defaultControls().extend([ new FullScreen({ source: 'fullscreen' diff --git a/examples/full-screen.js b/examples/full-screen.js index 4d9547c8f3..34b8ef862c 100644 --- a/examples/full-screen.js +++ b/examples/full-screen.js @@ -6,12 +6,12 @@ import TileLayer from '../src/ol/layer/Tile.js'; import BingMaps from '../src/ol/source/BingMaps.js'; -var view = new View({ +const view = new View({ center: [-9101767, 2822912], zoom: 14 }); -var map = new Map({ +const map = new Map({ controls: defaultControls().extend([ new FullScreen() ]), diff --git a/examples/geojson-vt.js b/examples/geojson-vt.js index 06ff1dc2d3..43cf960a8d 100644 --- a/examples/geojson-vt.js +++ b/examples/geojson-vt.js @@ -9,11 +9,11 @@ import VectorTileLayer from '../src/ol/layer/VectorTile.js'; import Projection from '../src/ol/proj/Projection.js'; -var replacer = function(key, value) { +const replacer = function(key, value) { if (value.geometry) { - var type; - var rawType = value.type; - var geometry = value.geometry; + let type; + const rawType = value.type; + let geometry = value.geometry; if (rawType === 1) { type = 'MultiPoint'; @@ -48,12 +48,12 @@ var replacer = function(key, value) { } }; -var tilePixels = new Projection({ +const tilePixels = new Projection({ code: 'TILE_PIXELS', units: 'tile-pixels' }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -66,26 +66,26 @@ var map = new Map({ }) }); -var url = 'data/geojson/countries.geojson'; +const url = 'data/geojson/countries.geojson'; fetch(url).then(function(response) { return response.json(); }).then(function(json) { - var tileIndex = geojsonvt(json, { + const tileIndex = geojsonvt(json, { extent: 4096, debug: 1 }); - var vectorSource = new VectorTileSource({ + const vectorSource = new VectorTileSource({ format: new GeoJSON(), tileLoadFunction: function(tile) { - var format = tile.getFormat(); - var tileCoord = tile.getTileCoord(); - var data = tileIndex.getTile(tileCoord[0], tileCoord[1], -tileCoord[2] - 1); + const format = tile.getFormat(); + const tileCoord = tile.getTileCoord(); + const data = tileIndex.getTile(tileCoord[0], tileCoord[1], -tileCoord[2] - 1); - var features = format.readFeatures( - JSON.stringify({ - type: 'FeatureCollection', - features: data ? data.features : [] - }, replacer)); + const features = format.readFeatures( + JSON.stringify({ + type: 'FeatureCollection', + features: data ? data.features : [] + }, replacer)); tile.setLoader(function() { tile.setFeatures(features); tile.setProjection(tilePixels); @@ -93,7 +93,7 @@ fetch(url).then(function(response) { }, url: 'data:' // arbitrary url, we don't use it in the tileLoadFunction }); - var vectorLayer = new VectorTileLayer({ + const vectorLayer = new VectorTileLayer({ source: vectorSource }); map.addLayer(vectorLayer); diff --git a/examples/geojson.js b/examples/geojson.js index fa497be054..81d6b6ee45 100644 --- a/examples/geojson.js +++ b/examples/geojson.js @@ -14,13 +14,13 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var image = new CircleStyle({ +const image = new CircleStyle({ radius: 5, fill: null, stroke: new Stroke({color: 'red', width: 1}) }); -var styles = { +const styles = { 'Point': new Style({ image: image }), @@ -85,11 +85,11 @@ var styles = { }) }; -var styleFunction = function(feature) { +const styleFunction = function(feature) { return styles[feature.getGeometry().getType()]; }; -var geojsonObject = { +const geojsonObject = { 'type': 'FeatureCollection', 'crs': { 'type': 'name', @@ -160,18 +160,18 @@ var geojsonObject = { }] }; -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ features: (new GeoJSON()).readFeatures(geojsonObject) }); vectorSource.addFeature(new Feature(new Circle([5e6, 7e6], 1e6))); -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: vectorSource, style: styleFunction }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() diff --git a/examples/geolocation-orientation.js b/examples/geolocation-orientation.js index 98c5bb52b1..cf1eb41695 100644 --- a/examples/geolocation-orientation.js +++ b/examples/geolocation-orientation.js @@ -9,13 +9,13 @@ import {fromLonLat} from '../src/ol/proj.js'; import OSM from '../src/ol/source/OSM.js'; // creating the view -var view = new View({ +const view = new View({ center: fromLonLat([5.8713, 45.6452]), zoom: 19 }); // creating the map -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -31,8 +31,8 @@ var map = new Map({ }); // Geolocation marker -var markerEl = document.getElementById('geolocation_marker'); -var marker = new Overlay({ +const markerEl = document.getElementById('geolocation_marker'); +const marker = new Overlay({ positioning: 'center-center', element: markerEl, stopEvent: false @@ -42,11 +42,11 @@ map.addOverlay(marker); // LineString to store the different geolocation positions. This LineString // is time aware. // The Z dimension is actually used to store the rotation (heading). -var positions = new LineString([], - /** @type {ol.geom.GeometryLayout} */ ('XYZM')); +const positions = new LineString([], + /** @type {ol.geom.GeometryLayout} */ ('XYZM')); // Geolocation Control -var geolocation = new Geolocation({ +const geolocation = new Geolocation({ projection: view.getProjection(), trackingOptions: { maximumAge: 10000, @@ -55,25 +55,25 @@ var geolocation = new Geolocation({ } }); -var deltaMean = 500; // the geolocation sampling period mean in ms +let deltaMean = 500; // the geolocation sampling period mean in ms // Listen to position changes geolocation.on('change', function() { - var position = geolocation.getPosition(); - var accuracy = geolocation.getAccuracy(); - var heading = geolocation.getHeading() || 0; - var speed = geolocation.getSpeed() || 0; - var m = Date.now(); + const position = geolocation.getPosition(); + const accuracy = geolocation.getAccuracy(); + const heading = geolocation.getHeading() || 0; + const speed = geolocation.getSpeed() || 0; + const m = Date.now(); addPosition(position, heading, m, speed); - var coords = positions.getCoordinates(); - var len = coords.length; + const coords = positions.getCoordinates(); + const len = coords.length; if (len >= 2) { deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1); } - var html = [ + const html = [ 'Position: ' + position[0].toFixed(2) + ', ' + position[1].toFixed(2), 'Accuracy: ' + accuracy, 'Heading: ' + Math.round(radToDeg(heading)) + '°', @@ -102,17 +102,17 @@ function mod(n) { } function addPosition(position, heading, m, speed) { - var x = position[0]; - var y = position[1]; - var fCoords = positions.getCoordinates(); - var previous = fCoords[fCoords.length - 1]; - var prevHeading = previous && previous[2]; + const x = position[0]; + const y = position[1]; + const fCoords = positions.getCoordinates(); + const previous = fCoords[fCoords.length - 1]; + const prevHeading = previous && previous[2]; if (prevHeading) { - var headingDiff = heading - mod(prevHeading); + let headingDiff = heading - mod(prevHeading); // force the rotation change to be less than 180° if (Math.abs(headingDiff) > Math.PI) { - var sign = (headingDiff >= 0) ? 1 : -1; + const sign = (headingDiff >= 0) ? 1 : -1; headingDiff = -sign * (2 * Math.PI - Math.abs(headingDiff)); } heading = prevHeading + headingDiff; @@ -133,8 +133,8 @@ function addPosition(position, heading, m, speed) { // recenters the view by putting the given coordinates at 3/4 from the top or // the screen function getCenterWithHeading(position, rotation, resolution) { - var size = map.getSize(); - var height = size[1]; + const size = map.getSize(); + const height = size[1]; return [ position[0] - Math.sin(rotation) * height * resolution * 1 / 4, @@ -142,14 +142,14 @@ function getCenterWithHeading(position, rotation, resolution) { ]; } -var previousM = 0; +let previousM = 0; function updateView() { // use sampling period to get a smooth transition - var m = Date.now() - deltaMean * 1.5; + let m = Date.now() - deltaMean * 1.5; m = Math.max(m, previousM); previousM = m; // interpolate position along positions LineString - var c = positions.getCoordinateAtM(m, true); + const c = positions.getCoordinateAtM(m, true); if (c) { view.setCenter(getCenterWithHeading(c, -c[2], view.getResolution())); view.setRotation(-c[2]); @@ -158,7 +158,7 @@ function updateView() { } // geolocate device -var geolocateBtn = document.getElementById('geolocate'); +const geolocateBtn = document.getElementById('geolocate'); geolocateBtn.addEventListener('click', function() { geolocation.setTracking(true); // Start position tracking @@ -169,8 +169,8 @@ geolocateBtn.addEventListener('click', function() { }, false); // simulate device move -var simulationData; -var client = new XMLHttpRequest(); +let simulationData; +const client = new XMLHttpRequest(); client.open('GET', 'data/geolocation-orientation.json'); @@ -182,20 +182,20 @@ client.onload = function() { }; client.send(); -var simulateBtn = document.getElementById('simulate'); +const simulateBtn = document.getElementById('simulate'); simulateBtn.addEventListener('click', function() { - var coordinates = simulationData; + const coordinates = simulationData; - var first = coordinates.shift(); + const first = coordinates.shift(); simulatePositionChange(first); - var prevDate = first.timestamp; + let prevDate = first.timestamp; function geolocate() { - var position = coordinates.shift(); + const position = coordinates.shift(); if (!position) { return; } - var newDate = position.timestamp; + const newDate = position.timestamp; simulatePositionChange(position); window.setTimeout(function() { prevDate = newDate; @@ -211,10 +211,10 @@ simulateBtn.addEventListener('click', function() { }, false); function simulatePositionChange(position) { - var coords = position.coords; + const coords = position.coords; geolocation.set('accuracy', coords.accuracy); geolocation.set('heading', degToRad(coords.heading)); - var projectedPosition = fromLonLat([coords.longitude, coords.latitude]); + const projectedPosition = fromLonLat([coords.longitude, coords.latitude]); geolocation.set('position', projectedPosition); geolocation.set('speed', coords.speed); geolocation.changed(); diff --git a/examples/geolocation.js b/examples/geolocation.js index 0df94b6ef1..235a70cd27 100644 --- a/examples/geolocation.js +++ b/examples/geolocation.js @@ -13,12 +13,12 @@ import Fill from '../src/ol/style/Fill.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var view = new View({ +const view = new View({ center: [0, 0], zoom: 2 }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -33,7 +33,7 @@ var map = new Map({ view: view }); -var geolocation = new Geolocation({ +const geolocation = new Geolocation({ projection: view.getProjection() }); @@ -56,17 +56,17 @@ geolocation.on('change', function() { // handle geolocation error. geolocation.on('error', function(error) { - var info = document.getElementById('info'); + const info = document.getElementById('info'); info.innerHTML = error.message; info.style.display = ''; }); -var accuracyFeature = new Feature(); +const accuracyFeature = new Feature(); geolocation.on('change:accuracyGeometry', function() { accuracyFeature.setGeometry(geolocation.getAccuracyGeometry()); }); -var positionFeature = new Feature(); +const positionFeature = new Feature(); positionFeature.setStyle(new Style({ image: new CircleStyle({ radius: 6, @@ -81,7 +81,7 @@ positionFeature.setStyle(new Style({ })); geolocation.on('change:position', function() { - var coordinates = geolocation.getPosition(); + const coordinates = geolocation.getPosition(); positionFeature.setGeometry(coordinates ? new Point(coordinates) : null); }); diff --git a/examples/getfeatureinfo-image.js b/examples/getfeatureinfo-image.js index 43490c0fcd..167fbdf349 100644 --- a/examples/getfeatureinfo-image.js +++ b/examples/getfeatureinfo-image.js @@ -4,23 +4,23 @@ import ImageLayer from '../src/ol/layer/Image.js'; import ImageWMS from '../src/ol/source/ImageWMS.js'; -var wmsSource = new ImageWMS({ +const wmsSource = new ImageWMS({ url: 'https://ahocevar.com/geoserver/wms', params: {'LAYERS': 'ne:ne'}, serverType: 'geoserver', crossOrigin: 'anonymous' }); -var wmsLayer = new ImageLayer({ +const wmsLayer = new ImageLayer({ source: wmsSource }); -var view = new View({ +const view = new View({ center: [0, 0], zoom: 1 }); -var map = new Map({ +const map = new Map({ layers: [wmsLayer], target: 'map', view: view @@ -28,10 +28,10 @@ var map = new Map({ map.on('singleclick', function(evt) { document.getElementById('info').innerHTML = ''; - var viewResolution = /** @type {number} */ (view.getResolution()); - var url = wmsSource.getGetFeatureInfoUrl( - evt.coordinate, viewResolution, 'EPSG:3857', - {'INFO_FORMAT': 'text/html'}); + const viewResolution = /** @type {number} */ (view.getResolution()); + const url = wmsSource.getGetFeatureInfoUrl( + evt.coordinate, viewResolution, 'EPSG:3857', + {'INFO_FORMAT': 'text/html'}); if (url) { document.getElementById('info').innerHTML = ''; @@ -42,8 +42,8 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); - var hit = map.forEachLayerAtPixel(pixel, function() { + const pixel = map.getEventPixel(evt.originalEvent); + const hit = map.forEachLayerAtPixel(pixel, function() { return true; }); map.getTargetElement().style.cursor = hit ? 'pointer' : ''; diff --git a/examples/getfeatureinfo-layers.js b/examples/getfeatureinfo-layers.js index c93c6103a3..f3e779bd9e 100644 --- a/examples/getfeatureinfo-layers.js +++ b/examples/getfeatureinfo-layers.js @@ -5,17 +5,17 @@ fetch('data/wmsgetfeatureinfo/osm-restaurant-hotel.xml').then(function(response) }).then(function(response) { // this is the standard way to read the features - var allFeatures = new WMSGetFeatureInfo().readFeatures(response); + const allFeatures = new WMSGetFeatureInfo().readFeatures(response); document.getElementById('all').innerText = allFeatures.length.toString(); // when specifying the 'layers' options, only the features of those // layers are returned by the format - var hotelFeatures = new WMSGetFeatureInfo({ + const hotelFeatures = new WMSGetFeatureInfo({ layers: ['hotel'] }).readFeatures(response); document.getElementById('hotel').innerText = hotelFeatures.length.toString(); - var restaurantFeatures = new WMSGetFeatureInfo({ + const restaurantFeatures = new WMSGetFeatureInfo({ layers: ['restaurant'] }).readFeatures(response); document.getElementById('restaurant').innerText = restaurantFeatures.length.toString(); diff --git a/examples/getfeatureinfo-tile.js b/examples/getfeatureinfo-tile.js index d1bc2480ed..3cad68cf1a 100644 --- a/examples/getfeatureinfo-tile.js +++ b/examples/getfeatureinfo-tile.js @@ -4,23 +4,23 @@ import TileLayer from '../src/ol/layer/Tile.js'; import TileWMS from '../src/ol/source/TileWMS.js'; -var wmsSource = new TileWMS({ +const wmsSource = new TileWMS({ url: 'https://ahocevar.com/geoserver/wms', params: {'LAYERS': 'ne:ne', 'TILED': true}, serverType: 'geoserver', crossOrigin: 'anonymous' }); -var wmsLayer = new TileLayer({ +const wmsLayer = new TileLayer({ source: wmsSource }); -var view = new View({ +const view = new View({ center: [0, 0], zoom: 1 }); -var map = new Map({ +const map = new Map({ layers: [wmsLayer], target: 'map', view: view @@ -28,10 +28,10 @@ var map = new Map({ map.on('singleclick', function(evt) { document.getElementById('info').innerHTML = ''; - var viewResolution = /** @type {number} */ (view.getResolution()); - var url = wmsSource.getGetFeatureInfoUrl( - evt.coordinate, viewResolution, 'EPSG:3857', - {'INFO_FORMAT': 'text/html'}); + const viewResolution = /** @type {number} */ (view.getResolution()); + const url = wmsSource.getGetFeatureInfoUrl( + evt.coordinate, viewResolution, 'EPSG:3857', + {'INFO_FORMAT': 'text/html'}); if (url) { document.getElementById('info').innerHTML = ''; @@ -42,8 +42,8 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); - var hit = map.forEachLayerAtPixel(pixel, function() { + const pixel = map.getEventPixel(evt.originalEvent); + const hit = map.forEachLayerAtPixel(pixel, function() { return true; }); map.getTargetElement().style.cursor = hit ? 'pointer' : ''; diff --git a/examples/gpx.js b/examples/gpx.js index 2861e70c84..9ac032aa7f 100644 --- a/examples/gpx.js +++ b/examples/gpx.js @@ -10,14 +10,14 @@ import Fill from '../src/ol/style/Fill.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new BingMaps({ imagerySet: 'Aerial', key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' }) }); -var style = { +const style = { 'Point': new Style({ image: new CircleStyle({ fill: new Fill({ @@ -44,7 +44,7 @@ var style = { }) }; -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ url: 'data/gpx/fells_loop.gpx', format: new GPX() @@ -54,7 +54,7 @@ var vector = new VectorLayer({ } }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: document.getElementById('map'), view: new View({ @@ -63,14 +63,14 @@ var map = new Map({ }) }); -var displayFeatureInfo = function(pixel) { - var features = []; +const displayFeatureInfo = function(pixel) { + const features = []; map.forEachFeatureAtPixel(pixel, function(feature) { features.push(feature); }); if (features.length > 0) { - var info = []; - var i, ii; + const info = []; + let i, ii; for (i = 0, ii = features.length; i < ii; ++i) { info.push(features[i].get('desc')); } @@ -86,7 +86,7 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); + const pixel = map.getEventPixel(evt.originalEvent); displayFeatureInfo(pixel); }); diff --git a/examples/graticule.js b/examples/graticule.js index f435460f72..ed026f4a98 100644 --- a/examples/graticule.js +++ b/examples/graticule.js @@ -7,7 +7,7 @@ import OSM from '../src/ol/source/OSM.js'; import Stroke from '../src/ol/style/Stroke.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM({ @@ -23,7 +23,7 @@ var map = new Map({ }); // Create the graticule component -var graticule = new Graticule({ +const graticule = new Graticule({ // the style to use for the lines, optional. strokeStyle: new Stroke({ color: 'rgba(255,120,0,0.9)', diff --git a/examples/heatmap-earthquakes.js b/examples/heatmap-earthquakes.js index 6645652d6a..054efe098d 100644 --- a/examples/heatmap-earthquakes.js +++ b/examples/heatmap-earthquakes.js @@ -6,10 +6,10 @@ import TileLayer from '../src/ol/layer/Tile.js'; import Stamen from '../src/ol/source/Stamen.js'; import VectorSource from '../src/ol/source/Vector.js'; -var blur = document.getElementById('blur'); -var radius = document.getElementById('radius'); +const blur = document.getElementById('blur'); +const radius = document.getElementById('radius'); -var vector = new HeatmapLayer({ +const vector = new HeatmapLayer({ source: new VectorSource({ url: 'data/kml/2012_Earthquakes_Mag5.kml', format: new KML({ @@ -24,18 +24,18 @@ vector.getSource().on('addfeature', function(event) { // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a // standards-violating tag in each Placemark. We extract it from // the Placemark's name instead. - var name = event.feature.get('name'); - var magnitude = parseFloat(name.substr(2)); + const name = event.feature.get('name'); + const magnitude = parseFloat(name.substr(2)); event.feature.set('weight', magnitude - 5); }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new Stamen({ layer: 'toner' }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ diff --git a/examples/here-maps.js b/examples/here-maps.js index 2e6406beb1..dab6aceffe 100644 --- a/examples/here-maps.js +++ b/examples/here-maps.js @@ -3,9 +3,9 @@ import View from '../src/ol/View.js'; import TileLayer from '../src/ol/layer/Tile.js'; import XYZ from '../src/ol/source/XYZ.js'; -var appId = 'kDm0Jq1K4Ak7Bwtn8uvk'; -var appCode = 'xnmvc4dKZrDfGlvQHXSvwQ'; -var hereLayers = [ +const appId = 'kDm0Jq1K4Ak7Bwtn8uvk'; +const appCode = 'xnmvc4dKZrDfGlvQHXSvwQ'; +const hereLayers = [ { base: 'base', type: 'maptile', @@ -49,13 +49,13 @@ var hereLayers = [ app_code: appCode } ]; -var urlTpl = 'https://{1-4}.{base}.maps.cit.api.here.com' + +const urlTpl = 'https://{1-4}.{base}.maps.cit.api.here.com' + '/{type}/2.1/maptile/newest/{scheme}/{z}/{x}/{y}/256/png' + '?app_id={app_id}&app_code={app_code}'; -var layers = []; -var i, ii; +const layers = []; +let i, ii; for (i = 0, ii = hereLayers.length; i < ii; ++i) { - var layerDesc = hereLayers[i]; + const layerDesc = hereLayers[i]; layers.push(new TileLayer({ visible: false, preload: Infinity, @@ -67,7 +67,7 @@ for (i = 0, ii = hereLayers.length; i < ii; ++i) { })); } -var map = new Map({ +const map = new Map({ layers: layers, // Improve user experience by loading tiles while dragging/zooming. Will make // zooming choppy on mobile or slow devices. @@ -81,17 +81,17 @@ var map = new Map({ function createUrl(tpl, layerDesc) { return tpl - .replace('{base}', layerDesc.base) - .replace('{type}', layerDesc.type) - .replace('{scheme}', layerDesc.scheme) - .replace('{app_id}', layerDesc.app_id) - .replace('{app_code}', layerDesc.app_code); + .replace('{base}', layerDesc.base) + .replace('{type}', layerDesc.type) + .replace('{scheme}', layerDesc.scheme) + .replace('{app_id}', layerDesc.app_id) + .replace('{app_code}', layerDesc.app_code); } -var select = document.getElementById('layer-select'); +const select = document.getElementById('layer-select'); function onChange() { - var scheme = select.value; - for (var i = 0, ii = layers.length; i < ii; ++i) { + const scheme = select.value; + for (let i = 0, ii = layers.length; i < ii; ++i) { layers[i].setVisible(hereLayers[i].scheme === scheme); } } diff --git a/examples/hit-tolerance.js b/examples/hit-tolerance.js index 015887f486..e0e6a617e7 100644 --- a/examples/hit-tolerance.js +++ b/examples/hit-tolerance.js @@ -9,27 +9,27 @@ import LineString from '../src/ol/geom/LineString.js'; import Style from '../src/ol/style/Style.js'; import Stroke from '../src/ol/style/Stroke.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var style = new Style({ +const style = new Style({ stroke: new Stroke({ color: 'black', width: 1 }) }); -var feature = new Feature(new LineString([[-4000000, 0], [4000000, 0]])); +const feature = new Feature(new LineString([[-4000000, 0], [4000000, 0]])); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ features: [feature] }), style: style }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ @@ -38,12 +38,12 @@ var map = new Map({ }) }); -var hitTolerance; +let hitTolerance; -var statusElement = document.getElementById('status'); +const statusElement = document.getElementById('status'); map.on('singleclick', function(e) { - var hit = false; + let hit = false; map.forEachFeatureAtPixel(e.pixel, function() { hit = true; }, { @@ -59,16 +59,16 @@ map.on('singleclick', function(e) { feature.changed(); }); -var selectHitToleranceElement = document.getElementById('hitTolerance'); -var circleCanvas = document.getElementById('circle'); +const selectHitToleranceElement = document.getElementById('hitTolerance'); +const circleCanvas = document.getElementById('circle'); -var changeHitTolerance = function() { +const changeHitTolerance = function() { hitTolerance = parseInt(selectHitToleranceElement.value, 10); - var size = 2 * hitTolerance + 2; + const size = 2 * hitTolerance + 2; circleCanvas.width = size; circleCanvas.height = size; - var ctx = circleCanvas.getContext('2d'); + const ctx = circleCanvas.getContext('2d'); ctx.clearRect(0, 0, size, size); ctx.beginPath(); ctx.arc(hitTolerance + 1, hitTolerance + 1, hitTolerance + 0.5, 0, 2 * Math.PI); diff --git a/examples/icon-color.js b/examples/icon-color.js index 24bbd94c24..edb046729f 100644 --- a/examples/icon-color.js +++ b/examples/icon-color.js @@ -11,15 +11,15 @@ import Icon from '../src/ol/style/Icon.js'; import Style from '../src/ol/style/Style.js'; -var rome = new Feature({ +const rome = new Feature({ geometry: new Point(fromLonLat([12.5, 41.9])) }); -var london = new Feature({ +const london = new Feature({ geometry: new Point(fromLonLat([-0.12755, 51.507222])) }); -var madrid = new Feature({ +const madrid = new Feature({ geometry: new Point(fromLonLat([-3.683333, 40.4])) }); @@ -48,22 +48,22 @@ madrid.setStyle(new Style({ })); -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ features: [rome, london, madrid] }); -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: vectorSource }); -var rasterLayer = new TileLayer({ +const rasterLayer = new TileLayer({ source: new TileJSON({ url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure', crossOrigin: '' }) }); -var map = new Map({ +const map = new Map({ layers: [rasterLayer, vectorLayer], target: document.getElementById('map'), view: new View({ diff --git a/examples/icon-negative.js b/examples/icon-negative.js index bb7c22ec3d..e1c2482f9d 100644 --- a/examples/icon-negative.js +++ b/examples/icon-negative.js @@ -23,10 +23,10 @@ function createStyle(src, img) { }); } -var iconFeature = new Feature(new Point([0, 0])); +const iconFeature = new Feature(new Point([0, 0])); iconFeature.set('style', createStyle('data/icon.png', undefined)); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new Stamen({layer: 'watercolor'}) @@ -45,19 +45,19 @@ var map = new Map({ }) }); -var selectStyle = {}; -var select = new Select({ +const selectStyle = {}; +const select = new Select({ style: function(feature) { - var image = feature.get('style').getImage().getImage(); + const image = feature.get('style').getImage().getImage(); if (!selectStyle[image.src]) { - var canvas = document.createElement('canvas'); - var context = canvas.getContext('2d'); + const canvas = document.createElement('canvas'); + const context = canvas.getContext('2d'); canvas.width = image.width; canvas.height = image.height; context.drawImage(image, 0, 0, image.width, image.height); - var imageData = context.getImageData(0, 0, canvas.width, canvas.height); - var data = imageData.data; - for (var i = 0, ii = data.length; i < ii; i = i + (i % 4 == 2 ? 2 : 1)) { + const imageData = context.getImageData(0, 0, canvas.width, canvas.height); + const data = imageData.data; + for (let i = 0, ii = data.length; i < ii; i = i + (i % 4 == 2 ? 2 : 1)) { data[i] = 255 - data[i]; } context.putImageData(imageData, 0, 0); diff --git a/examples/icon-sprite-webgl.js b/examples/icon-sprite-webgl.js index 9fe2d63f08..5e08ae49e5 100644 --- a/examples/icon-sprite-webgl.js +++ b/examples/icon-sprite-webgl.js @@ -8,7 +8,7 @@ import Icon from '../src/ol/style/Icon.js'; import Style from '../src/ol/style/Style.js'; -var iconInfo = [{ +const iconInfo = [{ offset: [0, 0], opacity: 1.0, rotateWithView: true, @@ -38,12 +38,12 @@ var iconInfo = [{ size: [44, 44] }]; -var i; +let i; -var iconCount = iconInfo.length; -var icons = new Array(iconCount); +const iconCount = iconInfo.length; +const icons = new Array(iconCount); for (i = 0; i < iconCount; ++i) { - var info = iconInfo[i]; + const info = iconInfo[i]; icons[i] = new Icon({ offset: info.offset, opacity: info.opacity, @@ -56,30 +56,30 @@ for (i = 0; i < iconCount; ++i) { }); } -var featureCount = 50000; -var features = new Array(featureCount); -var feature, geometry; -var e = 25000000; +const featureCount = 50000; +const features = new Array(featureCount); +let feature, geometry; +const e = 25000000; for (i = 0; i < featureCount; ++i) { geometry = new Point( - [2 * e * Math.random() - e, 2 * e * Math.random() - e]); + [2 * e * Math.random() - e, 2 * e * Math.random() - e]); feature = new Feature(geometry); feature.setStyle( - new Style({ - image: icons[i % (iconCount - 1)] - }) + new Style({ + image: icons[i % (iconCount - 1)] + }) ); features[i] = feature; } -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ features: features }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: vectorSource }); -var map = new Map({ +const map = new Map({ renderer: /** @type {Array} */ (['webgl', 'canvas']), layers: [vector], target: document.getElementById('map'), @@ -89,9 +89,9 @@ var map = new Map({ }) }); -var overlayFeatures = []; +const overlayFeatures = []; for (i = 0; i < featureCount; i += 30) { - var clone = features[i].clone(); + const clone = features[i].clone(); clone.setStyle(null); overlayFeatures.push(clone); } @@ -107,12 +107,12 @@ new VectorLayer({ }); map.on('click', function(evt) { - var info = document.getElementById('info'); + const info = document.getElementById('info'); info.innerHTML = 'Hold on a second, while I catch those butterflies for you ...'; window.setTimeout(function() { - var features = []; + const features = []; map.forEachFeatureAtPixel(evt.pixel, function(feature) { features.push(feature); return false; @@ -132,7 +132,7 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); - var hit = map.hasFeatureAtPixel(pixel); + const pixel = map.getEventPixel(evt.originalEvent); + const hit = map.hasFeatureAtPixel(pixel); map.getTarget().style.cursor = hit ? 'pointer' : ''; }); diff --git a/examples/icon.js b/examples/icon.js index 91d2edf9ed..1367939e29 100644 --- a/examples/icon.js +++ b/examples/icon.js @@ -11,14 +11,14 @@ import Icon from '../src/ol/style/Icon.js'; import Style from '../src/ol/style/Style.js'; -var iconFeature = new Feature({ +const iconFeature = new Feature({ geometry: new Point([0, 0]), name: 'Null Island', population: 4000, rainfall: 500 }); -var iconStyle = new Style({ +const iconStyle = new Style({ image: new Icon(/** @type {olx.style.IconOptions} */ ({ anchor: [0.5, 46], anchorXUnits: 'fraction', @@ -29,22 +29,22 @@ var iconStyle = new Style({ iconFeature.setStyle(iconStyle); -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ features: [iconFeature] }); -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: vectorSource }); -var rasterLayer = new TileLayer({ +const rasterLayer = new TileLayer({ source: new TileJSON({ url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure', crossOrigin: '' }) }); -var map = new Map({ +const map = new Map({ layers: [rasterLayer, vectorLayer], target: document.getElementById('map'), view: new View({ @@ -53,9 +53,9 @@ var map = new Map({ }) }); -var element = document.getElementById('popup'); +const element = document.getElementById('popup'); -var popup = new Overlay({ +const popup = new Overlay({ element: element, positioning: 'bottom-center', stopEvent: false, @@ -65,12 +65,12 @@ map.addOverlay(popup); // display popup on click map.on('click', function(evt) { - var feature = map.forEachFeatureAtPixel(evt.pixel, - function(feature) { - return feature; - }); + const feature = map.forEachFeatureAtPixel(evt.pixel, + function(feature) { + return feature; + }); if (feature) { - var coordinates = feature.getGeometry().getCoordinates(); + const coordinates = feature.getGeometry().getCoordinates(); popup.setPosition(coordinates); $(element).popover({ 'placement': 'top', @@ -89,7 +89,7 @@ map.on('pointermove', function(e) { $(element).popover('destroy'); return; } - var pixel = map.getEventPixel(e.originalEvent); - var hit = map.hasFeatureAtPixel(pixel); + const pixel = map.getEventPixel(e.originalEvent); + const hit = map.hasFeatureAtPixel(pixel); map.getTarget().style.cursor = hit ? 'pointer' : ''; }); diff --git a/examples/igc.js b/examples/igc.js index 2e42f2e9ae..275a736ebd 100644 --- a/examples/igc.js +++ b/examples/igc.js @@ -15,7 +15,7 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var colors = { +const colors = { 'Clement Latour': 'rgba(0, 0, 255, 0.7)', 'Damien de Baesnt': 'rgba(0, 215, 255, 0.7)', 'Sylvain Dhonneur': 'rgba(0, 165, 255, 0.7)', @@ -23,10 +23,10 @@ var colors = { 'Ulrich Prinz': 'rgba(0, 215, 255, 0.7)' }; -var styleCache = {}; -var styleFunction = function(feature) { - var color = colors[feature.get('PLT')]; - var style = styleCache[color]; +const styleCache = {}; +const styleFunction = function(feature) { + const color = colors[feature.get('PLT')]; + let style = styleCache[color]; if (!style) { style = new Style({ stroke: new Stroke({ @@ -39,9 +39,9 @@ var styleFunction = function(feature) { return style; }; -var vectorSource = new VectorSource(); +const vectorSource = new VectorSource(); -var igcUrls = [ +const igcUrls = [ 'data/igc/Clement-Latour.igc', 'data/igc/Damien-de-Baenst.igc', 'data/igc/Sylvain-Dhonneur.igc', @@ -50,7 +50,7 @@ var igcUrls = [ ]; function get(url, callback) { - var client = new XMLHttpRequest(); + const client = new XMLHttpRequest(); client.open('GET', url); client.onload = function() { callback(client.responseText); @@ -58,29 +58,29 @@ function get(url, callback) { client.send(); } -var igcFormat = new IGC(); -for (var i = 0; i < igcUrls.length; ++i) { +const igcFormat = new IGC(); +for (let i = 0; i < igcUrls.length; ++i) { get(igcUrls[i], function(data) { - var features = igcFormat.readFeatures(data, - {featureProjection: 'EPSG:3857'}); + const features = igcFormat.readFeatures(data, + {featureProjection: 'EPSG:3857'}); vectorSource.addFeatures(features); }); } -var time = { +const time = { start: Infinity, stop: -Infinity, duration: 0 }; vectorSource.on('addfeature', function(event) { - var geometry = event.feature.getGeometry(); + const geometry = event.feature.getGeometry(); time.start = Math.min(time.start, geometry.getFirstCoordinate()[2]); time.stop = Math.max(time.stop, geometry.getLastCoordinate()[2]); time.duration = time.stop - time.start; }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM({ @@ -110,27 +110,27 @@ var map = new Map({ }); -var point = null; -var line = null; -var displaySnap = function(coordinate) { - var closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate); - var info = document.getElementById('info'); +let point = null; +let line = null; +const displaySnap = function(coordinate) { + const closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate); + const info = document.getElementById('info'); if (closestFeature === null) { point = null; line = null; info.innerHTML = ' '; } else { - var geometry = closestFeature.getGeometry(); - var closestPoint = geometry.getClosestPoint(coordinate); + const geometry = closestFeature.getGeometry(); + const closestPoint = geometry.getClosestPoint(coordinate); if (point === null) { point = new Point(closestPoint); } else { point.setCoordinates(closestPoint); } - var date = new Date(closestPoint[2] * 1000); + const date = new Date(closestPoint[2] * 1000); info.innerHTML = closestFeature.get('PLT') + ' (' + date.toUTCString() + ')'; - var coordinates = [coordinate, [closestPoint[0], closestPoint[1]]]; + const coordinates = [coordinate, [closestPoint[0], closestPoint[1]]]; if (line === null) { line = new LineString(coordinates); } else { @@ -144,7 +144,7 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var coordinate = map.getEventCoordinate(evt.originalEvent); + const coordinate = map.getEventCoordinate(evt.originalEvent); displaySnap(coordinate); }); @@ -152,11 +152,11 @@ map.on('click', function(evt) { displaySnap(evt.coordinate); }); -var stroke = new Stroke({ +const stroke = new Stroke({ color: 'rgba(255,0,0,0.9)', width: 1 }); -var style = new Style({ +const style = new Style({ stroke: stroke, image: new CircleStyle({ radius: 5, @@ -165,7 +165,7 @@ var style = new Style({ }) }); map.on('postcompose', function(evt) { - var vectorContext = evt.vectorContext; + const vectorContext = evt.vectorContext; vectorContext.setStyle(style); if (point !== null) { vectorContext.drawGeometry(point); @@ -175,7 +175,7 @@ map.on('postcompose', function(evt) { } }); -var featureOverlay = new VectorLayer({ +const featureOverlay = new VectorLayer({ source: new VectorSource(), map: map, style: new Style({ @@ -189,12 +189,12 @@ var featureOverlay = new VectorLayer({ }); document.getElementById('time').addEventListener('input', function() { - var value = parseInt(this.value, 10) / 100; - var m = time.start + (time.duration * value); + const value = parseInt(this.value, 10) / 100; + const m = time.start + (time.duration * value); vectorSource.forEachFeature(function(feature) { - var geometry = /** @type {ol.geom.LineString} */ (feature.getGeometry()); - var coordinate = geometry.getCoordinateAtM(m, true); - var highlight = feature.get('highlight'); + const geometry = /** @type {ol.geom.LineString} */ (feature.getGeometry()); + const coordinate = geometry.getCoordinateAtM(m, true); + let highlight = feature.get('highlight'); if (highlight === undefined) { highlight = new Feature(new Point(coordinate)); feature.set('highlight', highlight); diff --git a/examples/image-filter.js b/examples/image-filter.js index 83eb980f96..dd8db7ee9e 100644 --- a/examples/image-filter.js +++ b/examples/image-filter.js @@ -4,13 +4,13 @@ import TileLayer from '../src/ol/layer/Tile.js'; import {fromLonLat} from '../src/ol/proj.js'; import BingMaps from '../src/ol/source/BingMaps.js'; -var key = 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'; +const key = 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'; -var imagery = new TileLayer({ +const imagery = new TileLayer({ source: new BingMaps({key: key, imagerySet: 'Aerial'}) }); -var map = new Map({ +const map = new Map({ layers: [imagery], target: 'map', view: new View({ @@ -19,7 +19,7 @@ var map = new Map({ }) }); -var kernels = { +const kernels = { none: [ 0, 0, 0, 0, 1, 0, @@ -58,9 +58,9 @@ var kernels = { }; function normalize(kernel) { - var len = kernel.length; - var normal = new Array(len); - var i, sum = 0; + const len = kernel.length; + const normal = new Array(len); + let i, sum = 0; for (i = 0; i < len; ++i) { sum += kernel[i]; } @@ -76,8 +76,8 @@ function normalize(kernel) { return normal; } -var select = document.getElementById('kernel'); -var selectedKernel = normalize(kernels[select.value]); +const select = document.getElementById('kernel'); +let selectedKernel = normalize(kernels[select.value]); /** @@ -104,37 +104,37 @@ imagery.on('postcompose', function(event) { * @param {Array.} kernel Kernel. */ function convolve(context, kernel) { - var canvas = context.canvas; - var width = canvas.width; - var height = canvas.height; + const canvas = context.canvas; + const width = canvas.width; + const height = canvas.height; - var size = Math.sqrt(kernel.length); - var half = Math.floor(size / 2); + const size = Math.sqrt(kernel.length); + const half = Math.floor(size / 2); - var inputData = context.getImageData(0, 0, width, height).data; + const inputData = context.getImageData(0, 0, width, height).data; - var output = context.createImageData(width, height); - var outputData = output.data; + const output = context.createImageData(width, height); + const outputData = output.data; - for (var pixelY = 0; pixelY < height; ++pixelY) { - var pixelsAbove = pixelY * width; - for (var pixelX = 0; pixelX < width; ++pixelX) { - var r = 0, g = 0, b = 0, a = 0; - for (var kernelY = 0; kernelY < size; ++kernelY) { - for (var kernelX = 0; kernelX < size; ++kernelX) { - var weight = kernel[kernelY * size + kernelX]; - var neighborY = Math.min( - height - 1, Math.max(0, pixelY + kernelY - half)); - var neighborX = Math.min( - width - 1, Math.max(0, pixelX + kernelX - half)); - var inputIndex = (neighborY * width + neighborX) * 4; + for (let pixelY = 0; pixelY < height; ++pixelY) { + const pixelsAbove = pixelY * width; + for (let pixelX = 0; pixelX < width; ++pixelX) { + let r = 0, g = 0, b = 0, a = 0; + for (let kernelY = 0; kernelY < size; ++kernelY) { + for (let kernelX = 0; kernelX < size; ++kernelX) { + const weight = kernel[kernelY * size + kernelX]; + const neighborY = Math.min( + height - 1, Math.max(0, pixelY + kernelY - half)); + const neighborX = Math.min( + width - 1, Math.max(0, pixelX + kernelX - half)); + const inputIndex = (neighborY * width + neighborX) * 4; r += inputData[inputIndex] * weight; g += inputData[inputIndex + 1] * weight; b += inputData[inputIndex + 2] * weight; a += inputData[inputIndex + 3] * weight; } } - var outputIndex = (pixelsAbove + pixelX) * 4; + const outputIndex = (pixelsAbove + pixelX) * 4; outputData[outputIndex] = r; outputData[outputIndex + 1] = g; outputData[outputIndex + 2] = b; diff --git a/examples/image-load-events.js b/examples/image-load-events.js index 7eb36831ad..a26f724436 100644 --- a/examples/image-load-events.js +++ b/examples/image-load-events.js @@ -32,7 +32,7 @@ Progress.prototype.addLoading = function() { * Increment the count of loaded tiles. */ Progress.prototype.addLoaded = function() { - var this_ = this; + const this_ = this; setTimeout(function() { ++this_.loaded; this_.update(); @@ -44,12 +44,12 @@ Progress.prototype.addLoaded = function() { * Update the progress bar. */ Progress.prototype.update = function() { - var width = (this.loaded / this.loading * 100).toFixed(1) + '%'; + const width = (this.loaded / this.loading * 100).toFixed(1) + '%'; this.el.style.width = width; if (this.loading === this.loaded) { this.loading = 0; this.loaded = 0; - var this_ = this; + const this_ = this; setTimeout(function() { this_.hide(); }, 500); @@ -75,9 +75,9 @@ Progress.prototype.hide = function() { } }; -var progress = new Progress(document.getElementById('progress')); +const progress = new Progress(document.getElementById('progress')); -var source = new ImageWMS({ +const source = new ImageWMS({ url: 'https://ahocevar.com/geoserver/wms', params: {'LAYERS': 'topp:states'}, serverType: 'geoserver' @@ -94,7 +94,7 @@ source.on('imageloaderror', function() { progress.addLoaded(); }); -var map = new Map({ +const map = new Map({ layers: [ new ImageLayer({source: source}) ], diff --git a/examples/image-vector-layer.js b/examples/image-vector-layer.js index c42cc680de..035660acb1 100644 --- a/examples/image-vector-layer.js +++ b/examples/image-vector-layer.js @@ -9,7 +9,7 @@ import Style from '../src/ol/style/Style.js'; import Text from '../src/ol/style/Text.js'; -var style = new Style({ +const style = new Style({ fill: new Fill({ color: 'rgba(255, 255, 255, 0.6)' }), @@ -20,7 +20,7 @@ var style = new Style({ text: new Text() }); -var map = new Map({ +const map = new Map({ layers: [ new VectorLayer({ renderMode: 'image', @@ -41,7 +41,7 @@ var map = new Map({ }) }); -var featureOverlay = new VectorLayer({ +const featureOverlay = new VectorLayer({ source: new VectorSource(), map: map, style: new Style({ @@ -55,14 +55,14 @@ var featureOverlay = new VectorLayer({ }) }); -var highlight; -var displayFeatureInfo = function(pixel) { +let highlight; +const displayFeatureInfo = function(pixel) { - var feature = map.forEachFeatureAtPixel(pixel, function(feature) { + const feature = map.forEachFeatureAtPixel(pixel, function(feature) { return feature; }); - var info = document.getElementById('info'); + const info = document.getElementById('info'); if (feature) { info.innerHTML = feature.getId() + ': ' + feature.get('name'); } else { @@ -85,7 +85,7 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); + const pixel = map.getEventPixel(evt.originalEvent); displayFeatureInfo(pixel); }); diff --git a/examples/jsts.js b/examples/jsts.js index e27e638505..ece0656c23 100644 --- a/examples/jsts.js +++ b/examples/jsts.js @@ -10,22 +10,22 @@ import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var source = new VectorSource(); +const source = new VectorSource(); fetch('data/geojson/roads-seoul.geojson').then(function(response) { return response.json(); }).then(function(json) { - var format = new GeoJSON(); - var features = format.readFeatures(json, {featureProjection: 'EPSG:3857'}); + const format = new GeoJSON(); + const features = format.readFeatures(json, {featureProjection: 'EPSG:3857'}); - var parser = new jsts.io.OL3Parser(); + const parser = new jsts.io.OL3Parser(); - for (var i = 0; i < features.length; i++) { - var feature = features[i]; + for (let i = 0; i < features.length; i++) { + const feature = features[i]; // convert the OpenLayers geometry to a JSTS geometry - var jstsGeom = parser.read(feature.getGeometry()); + const jstsGeom = parser.read(feature.getGeometry()); // create a buffer of 40 meters around each line - var buffered = jstsGeom.buffer(40); + const buffered = jstsGeom.buffer(40); // convert back from JSTS and replace the geometry on the feature feature.setGeometry(parser.write(buffered)); @@ -33,15 +33,15 @@ fetch('data/geojson/roads-seoul.geojson').then(function(response) { source.addFeatures(features); }); -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: source }); -var rasterLayer = new TileLayer({ +const rasterLayer = new TileLayer({ source: new OSM() }); -var map = new Map({ +const map = new Map({ layers: [rasterLayer, vectorLayer], target: document.getElementById('map'), view: new View({ diff --git a/examples/kml-earthquakes.js b/examples/kml-earthquakes.js index e785399ae0..42a3847132 100644 --- a/examples/kml-earthquakes.js +++ b/examples/kml-earthquakes.js @@ -11,15 +11,15 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var styleCache = {}; -var styleFunction = function(feature) { +const styleCache = {}; +const styleFunction = function(feature) { // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a // standards-violating tag in each Placemark. We extract it from // the Placemark's name instead. - var name = feature.get('name'); - var magnitude = parseFloat(name.substr(2)); - var radius = 5 + 20 * (magnitude - 5); - var style = styleCache[radius]; + const name = feature.get('name'); + const magnitude = parseFloat(name.substr(2)); + const radius = 5 + 20 * (magnitude - 5); + let style = styleCache[radius]; if (!style) { style = new Style({ image: new CircleStyle({ @@ -38,7 +38,7 @@ var styleFunction = function(feature) { return style; }; -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ url: 'data/kml/2012_Earthquakes_Mag5.kml', format: new KML({ @@ -48,13 +48,13 @@ var vector = new VectorLayer({ style: styleFunction }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new Stamen({ layer: 'toner' }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ @@ -63,25 +63,25 @@ var map = new Map({ }) }); -var info = $('#info'); +const info = $('#info'); info.tooltip({ animation: false, trigger: 'manual' }); -var displayFeatureInfo = function(pixel) { +const displayFeatureInfo = function(pixel) { info.css({ left: pixel[0] + 'px', top: (pixel[1] - 15) + 'px' }); - var feature = map.forEachFeatureAtPixel(pixel, function(feature) { + const feature = map.forEachFeatureAtPixel(pixel, function(feature) { return feature; }); if (feature) { info.tooltip('hide') - .attr('data-original-title', feature.get('name')) - .tooltip('fixTitle') - .tooltip('show'); + .attr('data-original-title', feature.get('name')) + .tooltip('fixTitle') + .tooltip('show'); } else { info.tooltip('hide'); } diff --git a/examples/kml-timezones.js b/examples/kml-timezones.js index 5c6956d254..cd80734a7b 100644 --- a/examples/kml-timezones.js +++ b/examples/kml-timezones.js @@ -17,24 +17,24 @@ import Style from '../src/ol/style/Style.js'; * currently midnight would have an opacity of 0. This doesn't account for * daylight savings, so don't use it to plan your vacation. */ -var styleFunction = function(feature) { - var offset = 0; - var name = feature.get('name'); // e.g. GMT -08:30 - var match = name.match(/([\-+]\d{2}):(\d{2})$/); +const styleFunction = function(feature) { + let offset = 0; + const name = feature.get('name'); // e.g. GMT -08:30 + const match = name.match(/([\-+]\d{2}):(\d{2})$/); if (match) { - var hours = parseInt(match[1], 10); - var minutes = parseInt(match[2], 10); + const hours = parseInt(match[1], 10); + const minutes = parseInt(match[2], 10); offset = 60 * hours + minutes; } - var date = new Date(); - var local = new Date(date.getTime() + + const date = new Date(); + const local = new Date(date.getTime() + (date.getTimezoneOffset() + offset) * 60000); // offset from local noon (in hours) - var delta = Math.abs(12 - local.getHours() + (local.getMinutes() / 60)); + let delta = Math.abs(12 - local.getHours() + (local.getMinutes() / 60)); if (delta > 12) { delta = 24 - delta; } - var opacity = 0.75 * (1 - delta / 12); + const opacity = 0.75 * (1 - delta / 12); return new Style({ fill: new Fill({ color: [0xff, 0xff, 0x33, opacity] @@ -45,7 +45,7 @@ var styleFunction = function(feature) { }); }; -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ url: 'data/kml/timezones.kml', format: new KML({ @@ -55,13 +55,13 @@ var vector = new VectorLayer({ style: styleFunction }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new Stamen({ layer: 'toner' }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ @@ -70,25 +70,25 @@ var map = new Map({ }) }); -var info = $('#info'); +const info = $('#info'); info.tooltip({ animation: false, trigger: 'manual' }); -var displayFeatureInfo = function(pixel) { +const displayFeatureInfo = function(pixel) { info.css({ left: pixel[0] + 'px', top: (pixel[1] - 15) + 'px' }); - var feature = map.forEachFeatureAtPixel(pixel, function(feature) { + const feature = map.forEachFeatureAtPixel(pixel, function(feature) { return feature; }); if (feature) { info.tooltip('hide') - .attr('data-original-title', feature.get('name')) - .tooltip('fixTitle') - .tooltip('show'); + .attr('data-original-title', feature.get('name')) + .tooltip('fixTitle') + .tooltip('show'); } else { info.tooltip('hide'); } diff --git a/examples/kml.js b/examples/kml.js index 9afaf5cd92..1e50fe67fd 100644 --- a/examples/kml.js +++ b/examples/kml.js @@ -6,21 +6,21 @@ import VectorLayer from '../src/ol/layer/Vector.js'; import BingMaps from '../src/ol/source/BingMaps.js'; import VectorSource from '../src/ol/source/Vector.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new BingMaps({ imagerySet: 'Aerial', key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' }) }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ url: 'data/kml/2012-02-10.kml', format: new KML() }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: document.getElementById('map'), view: new View({ @@ -30,14 +30,14 @@ var map = new Map({ }) }); -var displayFeatureInfo = function(pixel) { - var features = []; +const displayFeatureInfo = function(pixel) { + const features = []; map.forEachFeatureAtPixel(pixel, function(feature) { features.push(feature); }); if (features.length > 0) { - var info = []; - var i, ii; + const info = []; + let i, ii; for (i = 0, ii = features.length; i < ii; ++i) { info.push(features[i].get('name')); } @@ -53,7 +53,7 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); + const pixel = map.getEventPixel(evt.originalEvent); displayFeatureInfo(pixel); }); diff --git a/examples/layer-clipping-webgl.js b/examples/layer-clipping-webgl.js index d92b474466..24241abf3d 100644 --- a/examples/layer-clipping-webgl.js +++ b/examples/layer-clipping-webgl.js @@ -6,18 +6,18 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; if (!_ol_has_.WEBGL) { - var info = document.getElementById('no-webgl'); + const info = document.getElementById('no-webgl'); /** * display error message */ info.style.display = ''; } else { - var osm = new TileLayer({ + const osm = new TileLayer({ source: new OSM() }); - var map = new Map({ + const map = new Map({ layers: [osm], renderer: /** @type {Array} */ (['webgl', 'canvas']), target: 'map', @@ -32,13 +32,13 @@ if (!_ol_has_.WEBGL) { }) }); - var fragmentShaderSource = [ + const fragmentShaderSource = [ 'precision mediump float;', 'void main() {', '}' ].join(''); - var vertexShaderSource = [ + const vertexShaderSource = [ 'attribute vec2 a_position;', 'void main() {', ' gl_Position = vec4(a_position, 0, 1);', @@ -46,17 +46,17 @@ if (!_ol_has_.WEBGL) { ].join(''); osm.on('precompose', function(event) { - var context = event.glContext; + const context = event.glContext; - var gl = context.getGL(); - var program = gl.createProgram(); + const gl = context.getGL(); + const program = gl.createProgram(); - var vertexShader = gl.createShader(gl.VERTEX_SHADER); + const vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader, vertexShaderSource); gl.compileShader(vertexShader); gl.attachShader(program, vertexShader); - var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); + const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader, fragmentShaderSource); gl.compileShader(fragmentShader); gl.attachShader(program, fragmentShader); @@ -64,14 +64,14 @@ if (!_ol_has_.WEBGL) { gl.linkProgram(program); context.useProgram(program); - var positionLocation = gl.getAttribLocation(program, 'a_position'); + const positionLocation = gl.getAttribLocation(program, 'a_position'); gl.enable(gl.STENCIL_TEST); gl.colorMask(false, false, false, false); gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE); gl.stencilFunc(gl.ALWAYS, 1, 0xff); - var buffer = gl.createBuffer(); + const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ // first band @@ -101,8 +101,8 @@ if (!_ol_has_.WEBGL) { }); osm.on('postcompose', function(event) { - var context = event.glContext; - var gl = context.getGL(); + const context = event.glContext; + const gl = context.getGL(); gl.disable(gl.STENCIL_TEST); }); } diff --git a/examples/layer-clipping.js b/examples/layer-clipping.js index ecf7618f05..f98cdc268a 100644 --- a/examples/layer-clipping.js +++ b/examples/layer-clipping.js @@ -4,11 +4,11 @@ import {defaults as defaultControls} from '../src/ol/control.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var osm = new TileLayer({ +const osm = new TileLayer({ source: new OSM() }); -var map = new Map({ +const map = new Map({ layers: [osm], target: 'map', controls: defaultControls({ @@ -23,10 +23,10 @@ var map = new Map({ }); osm.on('precompose', function(event) { - var ctx = event.context; + const ctx = event.context; ctx.save(); - var pixelRatio = event.frameState.pixelRatio; - var size = map.getSize(); + const pixelRatio = event.frameState.pixelRatio; + const size = map.getSize(); ctx.translate(size[0] / 2 * pixelRatio, size[1] / 2 * pixelRatio); ctx.scale(3 * pixelRatio, 3 * pixelRatio); ctx.translate(-75, -80); @@ -45,6 +45,6 @@ osm.on('precompose', function(event) { }); osm.on('postcompose', function(event) { - var ctx = event.context; + const ctx = event.context; ctx.restore(); }); diff --git a/examples/layer-extent.js b/examples/layer-extent.js index dd7ff5d6b7..458261f081 100644 --- a/examples/layer-extent.js +++ b/examples/layer-extent.js @@ -8,21 +8,21 @@ function transform(extent) { return transformExtent(extent, 'EPSG:4326', 'EPSG:3857'); } -var extents = { +const extents = { India: transform([68.17665, 7.96553, 97.40256, 35.49401]), Argentina: transform([-73.41544, -55.25, -53.62835, -21.83231]), Nigeria: transform([2.6917, 4.24059, 14.57718, 13.86592]), Sweden: transform([11.02737, 55.36174, 23.90338, 69.10625]) }; -var base = new TileLayer({ +const base = new TileLayer({ source: new TileJSON({ url: 'https://api.tiles.mapbox.com/v3/mapbox.world-light.json?secure', crossOrigin: 'anonymous' }) }); -var overlay = new TileLayer({ +const overlay = new TileLayer({ extent: extents.India, source: new TileJSON({ url: 'https://api.tiles.mapbox.com/v3/mapbox.world-black.json?secure', @@ -30,7 +30,7 @@ var overlay = new TileLayer({ }) }); -var map = new Map({ +const map = new Map({ layers: [base, overlay], target: 'map', view: new View({ @@ -39,7 +39,7 @@ var map = new Map({ }) }); -for (var key in extents) { +for (const key in extents) { document.getElementById(key).onclick = function(event) { overlay.setExtent(extents[event.target.id]); }; diff --git a/examples/layer-group.js b/examples/layer-group.js index c245b4cd9a..b40bc3215e 100644 --- a/examples/layer-group.js +++ b/examples/layer-group.js @@ -6,7 +6,7 @@ import {fromLonLat} from '../src/ol/proj.js'; import OSM from '../src/ol/source/OSM.js'; import TileJSON from '../src/ol/source/TileJSON.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -35,13 +35,13 @@ var map = new Map({ }); function bindInputs(layerid, layer) { - var visibilityInput = $(layerid + ' input.visible'); + const visibilityInput = $(layerid + ' input.visible'); visibilityInput.on('change', function() { layer.setVisible(this.checked); }); visibilityInput.prop('checked', layer.getVisible()); - var opacityInput = $(layerid + ' input.opacity'); + const opacityInput = $(layerid + ' input.opacity'); opacityInput.on('input change', function() { layer.setOpacity(parseFloat(this.value)); }); diff --git a/examples/layer-spy.js b/examples/layer-spy.js index 53464b978a..7020fb80f5 100644 --- a/examples/layer-spy.js +++ b/examples/layer-spy.js @@ -4,19 +4,19 @@ import TileLayer from '../src/ol/layer/Tile.js'; import {fromLonLat} from '../src/ol/proj.js'; import BingMaps from '../src/ol/source/BingMaps.js'; -var key = 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'; +const key = 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'; -var roads = new TileLayer({ +const roads = new TileLayer({ source: new BingMaps({key: key, imagerySet: 'Road'}) }); -var imagery = new TileLayer({ +const imagery = new TileLayer({ source: new BingMaps({key: key, imagerySet: 'Aerial'}) }); -var container = document.getElementById('map'); +const container = document.getElementById('map'); -var map = new Map({ +const map = new Map({ layers: [roads, imagery], target: container, view: new View({ @@ -25,7 +25,7 @@ var map = new Map({ }) }); -var radius = 75; +let radius = 75; document.addEventListener('keydown', function(evt) { if (evt.which === 38) { radius = Math.min(radius + 5, 150); @@ -39,7 +39,7 @@ document.addEventListener('keydown', function(evt) { }); // get the pixel position with every move -var mousePosition = null; +let mousePosition = null; container.addEventListener('mousemove', function(event) { mousePosition = map.getEventPixel(event); @@ -53,14 +53,14 @@ container.addEventListener('mouseout', function() { // before rendering the layer, do some clipping imagery.on('precompose', function(event) { - var ctx = event.context; - var pixelRatio = event.frameState.pixelRatio; + const ctx = event.context; + const pixelRatio = event.frameState.pixelRatio; ctx.save(); ctx.beginPath(); if (mousePosition) { // only show a circle around the mouse ctx.arc(mousePosition[0] * pixelRatio, mousePosition[1] * pixelRatio, - radius * pixelRatio, 0, 2 * Math.PI); + radius * pixelRatio, 0, 2 * Math.PI); ctx.lineWidth = 5 * pixelRatio; ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.stroke(); @@ -70,6 +70,6 @@ imagery.on('precompose', function(event) { // after rendering the layer, restore the canvas context imagery.on('postcompose', function(event) { - var ctx = event.context; + const ctx = event.context; ctx.restore(); }); diff --git a/examples/layer-swipe.js b/examples/layer-swipe.js index cff2119e48..74b3301545 100644 --- a/examples/layer-swipe.js +++ b/examples/layer-swipe.js @@ -5,17 +5,17 @@ import TileLayer from '../src/ol/layer/Tile.js'; import BingMaps from '../src/ol/source/BingMaps.js'; import OSM from '../src/ol/source/OSM.js'; -var osm = new TileLayer({ +const osm = new TileLayer({ source: new OSM() }); -var bing = new TileLayer({ +const bing = new TileLayer({ source: new BingMaps({ key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5', imagerySet: 'Aerial' }) }); -var map = new Map({ +const map = new Map({ layers: [osm, bing], target: 'map', controls: defaultControls({ @@ -29,11 +29,11 @@ var map = new Map({ }) }); -var swipe = document.getElementById('swipe'); +const swipe = document.getElementById('swipe'); bing.on('precompose', function(event) { - var ctx = event.context; - var width = ctx.canvas.width * (swipe.value / 100); + const ctx = event.context; + const width = ctx.canvas.width * (swipe.value / 100); ctx.save(); ctx.beginPath(); @@ -42,7 +42,7 @@ bing.on('precompose', function(event) { }); bing.on('postcompose', function(event) { - var ctx = event.context; + const ctx = event.context; ctx.restore(); }); diff --git a/examples/layer-z-index.js b/examples/layer-z-index.js index b20297559c..56398592a8 100644 --- a/examples/layer-z-index.js +++ b/examples/layer-z-index.js @@ -10,9 +10,9 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var stroke = new Stroke({color: 'black', width: 1}); +const stroke = new Stroke({color: 'black', width: 1}); -var styles = { +const styles = { 'square': new Style({ image: new RegularShape({ fill: new Fill({color: 'blue'}), @@ -46,14 +46,14 @@ var styles = { function createLayer(coordinates, style, zIndex) { - var feature = new Feature(new Point(coordinates)); + const feature = new Feature(new Point(coordinates)); feature.setStyle(style); - var source = new VectorSource({ + const source = new VectorSource({ features: [feature] }); - var vectorLayer = new VectorLayer({ + const vectorLayer = new VectorLayer({ source: source }); vectorLayer.setZIndex(zIndex); @@ -61,15 +61,15 @@ function createLayer(coordinates, style, zIndex) { return vectorLayer; } -var layer0 = createLayer([40, 40], styles['star'], 0); -var layer1 = createLayer([0, 0], styles['square'], 1); -var layer2 = createLayer([0, 40], styles['triangle'], 0); +const layer0 = createLayer([40, 40], styles['star'], 0); +const layer1 = createLayer([0, 0], styles['square'], 1); +const layer2 = createLayer([0, 40], styles['triangle'], 0); -var layers = []; +const layers = []; layers.push(layer1); layers.push(layer2); -var map = new Map({ +const map = new Map({ layers: layers, target: 'map', view: new View({ @@ -82,7 +82,7 @@ layer0.setMap(map); function bindInputs(id, layer) { - var idxInput = document.getElementById('idx' + id); + const idxInput = document.getElementById('idx' + id); idxInput.onchange = function() { layer.setZIndex(parseInt(this.value, 10) || 0); }; diff --git a/examples/lazy-source.js b/examples/lazy-source.js index 133a8b59b1..04a16fea66 100644 --- a/examples/lazy-source.js +++ b/examples/lazy-source.js @@ -3,11 +3,11 @@ import View from '../src/ol/View.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var source = new OSM(); +const source = new OSM(); -var layer = new TileLayer(); +const layer = new TileLayer(); -var map = new Map({ +const map = new Map({ layers: [layer], target: 'map', view: new View({ diff --git a/examples/line-arrows.js b/examples/line-arrows.js index 49801ff64d..91f01a726a 100644 --- a/examples/line-arrows.js +++ b/examples/line-arrows.js @@ -10,15 +10,15 @@ import Icon from '../src/ol/style/Icon.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var source = new VectorSource(); +const source = new VectorSource(); -var styleFunction = function(feature) { - var geometry = feature.getGeometry(); - var styles = [ +const styleFunction = function(feature) { + const geometry = feature.getGeometry(); + const styles = [ // linestring new Style({ stroke: new Stroke({ @@ -29,9 +29,9 @@ var styleFunction = function(feature) { ]; geometry.forEachSegment(function(start, end) { - var dx = end[0] - start[0]; - var dy = end[1] - start[1]; - var rotation = Math.atan2(dy, dx); + const dx = end[0] - start[0]; + const dy = end[1] - start[1]; + const rotation = Math.atan2(dy, dx); // arrows styles.push(new Style({ geometry: new Point(end), @@ -46,12 +46,12 @@ var styleFunction = function(feature) { return styles; }; -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: source, style: styleFunction }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ diff --git a/examples/localized-openstreetmap.js b/examples/localized-openstreetmap.js index 6f5a84266e..cea87b8b9d 100644 --- a/examples/localized-openstreetmap.js +++ b/examples/localized-openstreetmap.js @@ -5,7 +5,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var openCycleMapLayer = new TileLayer({ +const openCycleMapLayer = new TileLayer({ source: new OSM({ attributions: [ 'All maps © OpenCycleMap', @@ -16,7 +16,7 @@ var openCycleMapLayer = new TileLayer({ }) }); -var openSeaMapLayer = new TileLayer({ +const openSeaMapLayer = new TileLayer({ source: new OSM({ attributions: [ 'All maps © OpenSeaMap', @@ -28,7 +28,7 @@ var openSeaMapLayer = new TileLayer({ }); -var map = new Map({ +const map = new Map({ layers: [ openCycleMapLayer, openSeaMapLayer diff --git a/examples/magnify.js b/examples/magnify.js index ff3cf13606..0cf052b68e 100644 --- a/examples/magnify.js +++ b/examples/magnify.js @@ -4,15 +4,15 @@ import TileLayer from '../src/ol/layer/Tile.js'; import {fromLonLat} from '../src/ol/proj.js'; import BingMaps from '../src/ol/source/BingMaps.js'; -var key = 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'; +const key = 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'; -var imagery = new TileLayer({ +const imagery = new TileLayer({ source: new BingMaps({key: key, imagerySet: 'Aerial'}) }); -var container = document.getElementById('map'); +const container = document.getElementById('map'); -var map = new Map({ +const map = new Map({ layers: [imagery], target: container, view: new View({ @@ -21,7 +21,7 @@ var map = new Map({ }) }); -var radius = 75; +let radius = 75; document.addEventListener('keydown', function(evt) { if (evt.which === 38) { radius = Math.min(radius + 5, 150); @@ -35,7 +35,7 @@ document.addEventListener('keydown', function(evt) { }); // get the pixel position with every move -var mousePosition = null; +let mousePosition = null; container.addEventListener('mousemove', function(event) { mousePosition = map.getEventPixel(event); @@ -50,30 +50,30 @@ container.addEventListener('mouseout', function() { // after rendering the layer, show an oversampled version around the pointer imagery.on('postcompose', function(event) { if (mousePosition) { - var context = event.context; - var pixelRatio = event.frameState.pixelRatio; - var half = radius * pixelRatio; - var centerX = mousePosition[0] * pixelRatio; - var centerY = mousePosition[1] * pixelRatio; - var originX = centerX - half; - var originY = centerY - half; - var size = 2 * half + 1; - var sourceData = context.getImageData(originX, originY, size, size).data; - var dest = context.createImageData(size, size); - var destData = dest.data; - for (var j = 0; j < size; ++j) { - for (var i = 0; i < size; ++i) { - var dI = i - half; - var dJ = j - half; - var dist = Math.sqrt(dI * dI + dJ * dJ); - var sourceI = i; - var sourceJ = j; + const context = event.context; + const pixelRatio = event.frameState.pixelRatio; + const half = radius * pixelRatio; + const centerX = mousePosition[0] * pixelRatio; + const centerY = mousePosition[1] * pixelRatio; + const originX = centerX - half; + const originY = centerY - half; + const size = 2 * half + 1; + const sourceData = context.getImageData(originX, originY, size, size).data; + const dest = context.createImageData(size, size); + const destData = dest.data; + for (let j = 0; j < size; ++j) { + for (let i = 0; i < size; ++i) { + const dI = i - half; + const dJ = j - half; + const dist = Math.sqrt(dI * dI + dJ * dJ); + let sourceI = i; + let sourceJ = j; if (dist < half) { sourceI = Math.round(half + dI / 2); sourceJ = Math.round(half + dJ / 2); } - var destOffset = (j * size + i) * 4; - var sourceOffset = (sourceJ * size + sourceI) * 4; + const destOffset = (j * size + i) * 4; + const sourceOffset = (sourceJ * size + sourceI) * 4; destData[destOffset] = sourceData[sourceOffset]; destData[destOffset + 1] = sourceData[sourceOffset + 1]; destData[destOffset + 2] = sourceData[sourceOffset + 2]; diff --git a/examples/mapbox-vector-tiles-advanced.js b/examples/mapbox-vector-tiles-advanced.js index 7a48b09588..af2718af8c 100644 --- a/examples/mapbox-vector-tiles-advanced.js +++ b/examples/mapbox-vector-tiles-advanced.js @@ -12,25 +12,25 @@ import Text from '../src/ol/style/Text.js'; import TileGrid from '../src/ol/tilegrid/TileGrid.js'; -var key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiRk1kMWZaSSJ9.E5BkluenyWQMsBLsuByrmg'; +const key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiRk1kMWZaSSJ9.E5BkluenyWQMsBLsuByrmg'; // Calculation of resolutions that match zoom levels 1, 3, 5, 7, 9, 11, 13, 15. -var resolutions = []; -for (var i = 0; i <= 8; ++i) { +const resolutions = []; +for (let i = 0; i <= 8; ++i) { resolutions.push(156543.03392804097 / Math.pow(2, i * 2)); } // Calculation of tile urls for zoom levels 1, 3, 5, 7, 9, 11, 13, 15. function tileUrlFunction(tileCoord) { return ('https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' + '{z}/{x}/{y}.vector.pbf?access_token=' + key) - .replace('{z}', String(tileCoord[0] * 2 - 1)) - .replace('{x}', String(tileCoord[1])) - .replace('{y}', String(-tileCoord[2] - 1)) - .replace('{a-d}', 'abcd'.substr( - ((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1)); + .replace('{z}', String(tileCoord[0] * 2 - 1)) + .replace('{x}', String(tileCoord[1])) + .replace('{y}', String(-tileCoord[2] - 1)) + .replace('{a-d}', 'abcd'.substr( + ((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1)); } -var map = new Map({ +const map = new Map({ layers: [ new VectorTileLayer({ source: new VectorTileSource({ diff --git a/examples/mapbox-vector-tiles.js b/examples/mapbox-vector-tiles.js index 4c7ae3d7d0..33dc970fb6 100644 --- a/examples/mapbox-vector-tiles.js +++ b/examples/mapbox-vector-tiles.js @@ -10,9 +10,9 @@ import Style from '../src/ol/style/Style.js'; import Text from '../src/ol/style/Text.js'; -var key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiRk1kMWZaSSJ9.E5BkluenyWQMsBLsuByrmg'; +const key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiRk1kMWZaSSJ9.E5BkluenyWQMsBLsuByrmg'; -var map = new Map({ +const map = new Map({ layers: [ new VectorTileLayer({ declutter: true, diff --git a/examples/mapguide-untiled.js b/examples/mapguide-untiled.js index 6a10498673..0ba9bea05d 100644 --- a/examples/mapguide-untiled.js +++ b/examples/mapguide-untiled.js @@ -3,16 +3,16 @@ import View from '../src/ol/View.js'; import ImageLayer from '../src/ol/layer/Image.js'; import ImageMapGuide from '../src/ol/source/ImageMapGuide.js'; -var mdf = 'Library://Public/Samples/Sheboygan/Maps/Sheboygan.MapDefinition'; -var agentUrl = +const mdf = 'Library://Public/Samples/Sheboygan/Maps/Sheboygan.MapDefinition'; +const agentUrl = 'http://www.buoyshark.com/mapguide/mapagent/mapagent.fcgi?'; -var bounds = [ +const bounds = [ -87.865114442365922, 43.665065564837931, -87.595394059497067, 43.823852564430069 ]; -var map = new Map({ +const map = new Map({ layers: [ new ImageLayer({ extent: bounds, diff --git a/examples/measure.js b/examples/measure.js index b829c289a9..943053cdcf 100644 --- a/examples/measure.js +++ b/examples/measure.js @@ -16,13 +16,13 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var source = new VectorSource(); +const source = new VectorSource(); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: source, style: new Style({ fill: new Fill({ @@ -46,64 +46,64 @@ var vector = new VectorLayer({ * Currently drawn feature. * @type {ol.Feature} */ -var sketch; +let sketch; /** * The help tooltip element. * @type {Element} */ -var helpTooltipElement; +let helpTooltipElement; /** * Overlay to show the help messages. * @type {ol.Overlay} */ -var helpTooltip; +let helpTooltip; /** * The measure tooltip element. * @type {Element} */ -var measureTooltipElement; +let measureTooltipElement; /** * Overlay to show the measurement. * @type {ol.Overlay} */ -var measureTooltip; +let measureTooltip; /** * Message to show when the user is drawing a polygon. * @type {string} */ -var continuePolygonMsg = 'Click to continue drawing the polygon'; +const continuePolygonMsg = 'Click to continue drawing the polygon'; /** * Message to show when the user is drawing a line. * @type {string} */ -var continueLineMsg = 'Click to continue drawing the line'; +const continueLineMsg = 'Click to continue drawing the line'; /** * Handle pointer move. * @param {ol.MapBrowserEvent} evt The event. */ -var pointerMoveHandler = function(evt) { +const pointerMoveHandler = function(evt) { if (evt.dragging) { return; } /** @type {string} */ - var helpMsg = 'Click to start drawing'; + let helpMsg = 'Click to start drawing'; if (sketch) { - var geom = (sketch.getGeometry()); + const geom = (sketch.getGeometry()); if (geom instanceof Polygon) { helpMsg = continuePolygonMsg; } else if (geom instanceof LineString) { @@ -118,7 +118,7 @@ var pointerMoveHandler = function(evt) { }; -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ @@ -133,9 +133,9 @@ map.getViewport().addEventListener('mouseout', function() { helpTooltipElement.classList.add('hidden'); }); -var typeSelect = document.getElementById('type'); +const typeSelect = document.getElementById('type'); -var draw; // global so we can remove it later +let draw; // global so we can remove it later /** @@ -143,9 +143,9 @@ var draw; // global so we can remove it later * @param {ol.geom.LineString} line The line. * @return {string} The formatted length. */ -var formatLength = function(line) { - var length = getLength(line); - var output; +const formatLength = function(line) { + const length = getLength(line); + let output; if (length > 100) { output = (Math.round(length / 1000 * 100) / 100) + ' ' + 'km'; @@ -162,9 +162,9 @@ var formatLength = function(line) { * @param {ol.geom.Polygon} polygon The polygon. * @return {string} Formatted area. */ -var formatArea = function(polygon) { - var area = getArea(polygon); - var output; +const formatArea = function(polygon) { + const area = getArea(polygon); + let output; if (area > 10000) { output = (Math.round(area / 1000000 * 100) / 100) + ' ' + 'km2'; @@ -176,7 +176,7 @@ var formatArea = function(polygon) { }; function addInteraction() { - var type = (typeSelect.value == 'area' ? 'Polygon' : 'LineString'); + const type = (typeSelect.value == 'area' ? 'Polygon' : 'LineString'); draw = new Draw({ source: source, type: type, @@ -205,41 +205,41 @@ function addInteraction() { createMeasureTooltip(); createHelpTooltip(); - var listener; + let listener; draw.on('drawstart', - function(evt) { - // set sketch - sketch = evt.feature; + function(evt) { + // set sketch + sketch = evt.feature; - /** @type {ol.Coordinate|undefined} */ - var tooltipCoord = evt.coordinate; + /** @type {ol.Coordinate|undefined} */ + let tooltipCoord = evt.coordinate; - listener = sketch.getGeometry().on('change', function(evt) { - var geom = evt.target; - var output; - if (geom instanceof Polygon) { - output = formatArea(geom); - tooltipCoord = geom.getInteriorPoint().getCoordinates(); - } else if (geom instanceof LineString) { - output = formatLength(geom); - tooltipCoord = geom.getLastCoordinate(); - } - measureTooltipElement.innerHTML = output; - measureTooltip.setPosition(tooltipCoord); - }); - }, this); + listener = sketch.getGeometry().on('change', function(evt) { + const geom = evt.target; + let output; + if (geom instanceof Polygon) { + output = formatArea(geom); + tooltipCoord = geom.getInteriorPoint().getCoordinates(); + } else if (geom instanceof LineString) { + output = formatLength(geom); + tooltipCoord = geom.getLastCoordinate(); + } + measureTooltipElement.innerHTML = output; + measureTooltip.setPosition(tooltipCoord); + }); + }, this); draw.on('drawend', - function() { - measureTooltipElement.className = 'tooltip tooltip-static'; - measureTooltip.setOffset([0, -7]); - // unset sketch - sketch = null; - // unset tooltip so that a new one can be created - measureTooltipElement = null; - createMeasureTooltip(); - Observable.unByKey(listener); - }, this); + function() { + measureTooltipElement.className = 'tooltip tooltip-static'; + measureTooltip.setOffset([0, -7]); + // unset sketch + sketch = null; + // unset tooltip so that a new one can be created + measureTooltipElement = null; + createMeasureTooltip(); + Observable.unByKey(listener); + }, this); } diff --git a/examples/min-max-resolution.js b/examples/min-max-resolution.js index cd8ecd303f..5f011a1ba9 100644 --- a/examples/min-max-resolution.js +++ b/examples/min-max-resolution.js @@ -9,7 +9,7 @@ import TileJSON from '../src/ol/source/TileJSON.js'; /** * Create the map. */ -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM(), diff --git a/examples/min-zoom.js b/examples/min-zoom.js index ecc51b1cf8..f37740f9ce 100644 --- a/examples/min-zoom.js +++ b/examples/min-zoom.js @@ -3,22 +3,22 @@ import View from '../src/ol/View.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var viewport = document.getElementById('map'); +const viewport = document.getElementById('map'); function getMinZoom() { - var width = viewport.clientWidth; + const width = viewport.clientWidth; return Math.ceil(Math.LOG2E * Math.log(width / 256)); } -var initialZoom = getMinZoom(); +const initialZoom = getMinZoom(); -var view = new View({ +const view = new View({ center: [0, 0], minZoom: initialZoom, zoom: initialZoom }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -29,7 +29,7 @@ var map = new Map({ }); window.addEventListener('resize', function() { - var minZoom = getMinZoom(); + const minZoom = getMinZoom(); if (minZoom !== view.getMinZoom()) { view.setMinZoom(minZoom); } diff --git a/examples/mobile-full-screen.js b/examples/mobile-full-screen.js index 59ae12bc02..c01ce3b9e8 100644 --- a/examples/mobile-full-screen.js +++ b/examples/mobile-full-screen.js @@ -5,12 +5,12 @@ import TileLayer from '../src/ol/layer/Tile.js'; import BingMaps from '../src/ol/source/BingMaps.js'; -var view = new View({ +const view = new View({ center: [0, 0], zoom: 2 }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new BingMaps({ @@ -23,7 +23,7 @@ var map = new Map({ view: view }); -var geolocation = new Geolocation({ +const geolocation = new Geolocation({ projection: view.getProjection(), tracking: true }); diff --git a/examples/modify-features.js b/examples/modify-features.js index 33f9ea545b..35d47c0417 100644 --- a/examples/modify-features.js +++ b/examples/modify-features.js @@ -10,11 +10,11 @@ import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ url: 'data/geojson/countries.geojson', format: new GeoJSON(), @@ -22,15 +22,15 @@ var vector = new VectorLayer({ }) }); -var select = new Select({ +const select = new Select({ wrapX: false }); -var modify = new Modify({ +const modify = new Modify({ features: select.getFeatures() }); -var map = new Map({ +const map = new Map({ interactions: defaultInteractions().extend([select, modify]), layers: [raster, vector], target: 'map', diff --git a/examples/modify-test.js b/examples/modify-test.js index f6501c30c6..a01d28a87a 100644 --- a/examples/modify-test.js +++ b/examples/modify-test.js @@ -12,9 +12,9 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var styleFunction = (function() { - var styles = {}; - var image = new CircleStyle({ +const styleFunction = (function() { + const styles = {}; + const image = new CircleStyle({ radius: 5, fill: null, stroke: new Stroke({color: 'orange', width: 2}) @@ -59,7 +59,7 @@ var styleFunction = (function() { }; })(); -var geojsonObject = { +const geojsonObject = { 'type': 'FeatureCollection', 'crs': { 'type': 'name', @@ -144,17 +144,17 @@ var geojsonObject = { }] }; -var source = new VectorSource({ +const source = new VectorSource({ features: (new GeoJSON()).readFeatures(geojsonObject) }); -var layer = new VectorLayer({ +const layer = new VectorLayer({ source: source, style: styleFunction }); -var overlayStyle = (function() { - var styles = {}; +const overlayStyle = (function() { + const styles = {}; styles['Polygon'] = [ new Style({ fill: new Fill({ @@ -216,11 +216,11 @@ var overlayStyle = (function() { }; })(); -var select = new Select({ +const select = new Select({ style: overlayStyle }); -var modify = new Modify({ +const modify = new Modify({ features: select.getFeatures(), style: overlayStyle, insertVertexCondition: function() { @@ -231,7 +231,7 @@ var modify = new Modify({ } }); -var map = new Map({ +const map = new Map({ interactions: defaultInteractions().extend([select, modify]), layers: [layer], target: 'map', diff --git a/examples/mouse-position.js b/examples/mouse-position.js index 14e1433ad2..01d85baafd 100644 --- a/examples/mouse-position.js +++ b/examples/mouse-position.js @@ -6,7 +6,7 @@ import _ol_coordinate_ from '../src/ol/coordinate.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var mousePositionControl = new MousePosition({ +const mousePositionControl = new MousePosition({ coordinateFormat: _ol_coordinate_.createStringXY(4), projection: 'EPSG:4326', // comment the following two lines to have the mouse position @@ -16,7 +16,7 @@ var mousePositionControl = new MousePosition({ undefinedHTML: ' ' }); -var map = new Map({ +const map = new Map({ controls: defaultControls({ attributionOptions: { collapsible: false @@ -34,13 +34,13 @@ var map = new Map({ }) }); -var projectionSelect = document.getElementById('projection'); +const projectionSelect = document.getElementById('projection'); projectionSelect.addEventListener('change', function(event) { mousePositionControl.setProjection(event.target.value); }); -var precisionInput = document.getElementById('precision'); +const precisionInput = document.getElementById('precision'); precisionInput.addEventListener('change', function(event) { - var format = _ol_coordinate_.createStringXY(event.target.valueAsNumber); + const format = _ol_coordinate_.createStringXY(event.target.valueAsNumber); mousePositionControl.setCoordinateFormat(format); }); diff --git a/examples/mousewheel-zoom.js b/examples/mousewheel-zoom.js index a73b1b10cf..1a97f7ba54 100644 --- a/examples/mousewheel-zoom.js +++ b/examples/mousewheel-zoom.js @@ -6,7 +6,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ interactions: defaultInteractions({mouseWheelZoom: false}).extend([ new MouseWheelZoom({ constrainResolution: true // force zooming to a integer zoom diff --git a/examples/moveend.js b/examples/moveend.js index 3cfffb714b..1e304d2f62 100644 --- a/examples/moveend.js +++ b/examples/moveend.js @@ -7,7 +7,7 @@ import {toLonLat} from '../src/ol/proj.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -30,15 +30,15 @@ function display(id, value) { } function wrapLon(value) { - var worlds = Math.floor((value + 180) / 360); + const worlds = Math.floor((value + 180) / 360); return value - (worlds * 360); } function onMoveEnd(evt) { - var map = evt.map; - var extent = map.getView().calculateExtent(map.getSize()); - var bottomLeft = toLonLat(_ol_extent_.getBottomLeft(extent)); - var topRight = toLonLat(_ol_extent_.getTopRight(extent)); + const map = evt.map; + const extent = map.getView().calculateExtent(map.getSize()); + const bottomLeft = toLonLat(_ol_extent_.getBottomLeft(extent)); + const topRight = toLonLat(_ol_extent_.getTopRight(extent)); display('left', wrapLon(bottomLeft[0])); display('bottom', bottomLeft[1]); display('right', wrapLon(topRight[0])); diff --git a/examples/navigation-controls.js b/examples/navigation-controls.js index 863da95955..2cacb2f0d9 100644 --- a/examples/navigation-controls.js +++ b/examples/navigation-controls.js @@ -6,7 +6,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ controls: defaultControls({ attributionOptions: { collapsible: false diff --git a/examples/osm-vector-tiles.js b/examples/osm-vector-tiles.js index 5f0c7d332c..29f50e200d 100644 --- a/examples/osm-vector-tiles.js +++ b/examples/osm-vector-tiles.js @@ -8,15 +8,15 @@ import Fill from '../src/ol/style/Fill.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var key = 'vector-tiles-5eJz6JX'; +const key = 'vector-tiles-5eJz6JX'; -var roadStyleCache = {}; -var roadColor = { +const roadStyleCache = {}; +const roadColor = { 'major_road': '#776', 'minor_road': '#ccb', 'highway': '#f39' }; -var buildingStyle = new Style({ +const buildingStyle = new Style({ fill: new Fill({ color: '#666', opacity: 0.4 @@ -26,19 +26,19 @@ var buildingStyle = new Style({ width: 1 }) }); -var waterStyle = new Style({ +const waterStyle = new Style({ fill: new Fill({ color: '#9db9e8' }) }); -var roadStyle = function(feature) { - var kind = feature.get('kind'); - var railway = feature.get('railway'); - var sort_key = feature.get('sort_key'); - var styleKey = kind + '/' + railway + '/' + sort_key; - var style = roadStyleCache[styleKey]; +const roadStyle = function(feature) { + const kind = feature.get('kind'); + const railway = feature.get('railway'); + const sort_key = feature.get('sort_key'); + const styleKey = kind + '/' + railway + '/' + sort_key; + let style = roadStyleCache[styleKey]; if (!style) { - var color, width; + let color, width; if (railway) { color = '#7de'; width = 1; @@ -58,7 +58,7 @@ var roadStyle = function(feature) { return style; }; -var map = new Map({ +const map = new Map({ layers: [ new VectorTileLayer({ source: new VectorTileSource({ diff --git a/examples/overlay.js b/examples/overlay.js index 62e1edcaa3..69f8eb8702 100644 --- a/examples/overlay.js +++ b/examples/overlay.js @@ -7,11 +7,11 @@ import {fromLonLat, toLonLat} from '../src/ol/proj.js'; import OSM from '../src/ol/source/OSM.js'; -var layer = new TileLayer({ +const layer = new TileLayer({ source: new OSM() }); -var map = new Map({ +const map = new Map({ layers: [layer], target: 'map', view: new View({ @@ -20,10 +20,10 @@ var map = new Map({ }) }); -var pos = fromLonLat([16.3725, 48.208889]); +const pos = fromLonLat([16.3725, 48.208889]); // Vienna marker -var marker = new Overlay({ +const marker = new Overlay({ position: pos, positioning: 'center-center', element: document.getElementById('marker'), @@ -32,22 +32,22 @@ var marker = new Overlay({ map.addOverlay(marker); // Vienna label -var vienna = new Overlay({ +const vienna = new Overlay({ position: pos, element: document.getElementById('vienna') }); map.addOverlay(vienna); // Popup showing the position the user clicked -var popup = new Overlay({ +const popup = new Overlay({ element: document.getElementById('popup') }); map.addOverlay(popup); map.on('click', function(evt) { - var element = popup.getElement(); - var coordinate = evt.coordinate; - var hdms = _ol_coordinate_.toStringHDMS(toLonLat(coordinate)); + const element = popup.getElement(); + const coordinate = evt.coordinate; + const hdms = _ol_coordinate_.toStringHDMS(toLonLat(coordinate)); $(element).popover('destroy'); popup.setPosition(coordinate); diff --git a/examples/overviewmap-custom.js b/examples/overviewmap-custom.js index 0ac6a41ba3..bf525d8059 100644 --- a/examples/overviewmap-custom.js +++ b/examples/overviewmap-custom.js @@ -8,7 +8,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var overviewMapControl = new OverviewMap({ +const overviewMapControl = new OverviewMap({ // see in overviewmap-custom.html to see the custom CSS used className: 'ol-overviewmap ol-custom-overviewmap', layers: [ @@ -24,7 +24,7 @@ var overviewMapControl = new OverviewMap({ collapsed: false }); -var map = new Map({ +const map = new Map({ controls: defaultControls().extend([ overviewMapControl ]), diff --git a/examples/overviewmap.js b/examples/overviewmap.js index 131b118307..936bb90c06 100644 --- a/examples/overviewmap.js +++ b/examples/overviewmap.js @@ -5,7 +5,7 @@ import OverviewMap from '../src/ol/control/OverviewMap.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ controls: defaultControls().extend([ new OverviewMap() ]), diff --git a/examples/permalink.js b/examples/permalink.js index e2932512f5..1dd2ebe993 100644 --- a/examples/permalink.js +++ b/examples/permalink.js @@ -5,14 +5,14 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; // default zoom, center and rotation -var zoom = 2; -var center = [0, 0]; -var rotation = 0; +let zoom = 2; +let center = [0, 0]; +let rotation = 0; if (window.location.hash !== '') { // try to restore center, zoom-level and rotation from the URL - var hash = window.location.hash.replace('#map=', ''); - var parts = hash.split('/'); + const hash = window.location.hash.replace('#map=', ''); + const parts = hash.split('/'); if (parts.length === 4) { zoom = parseInt(parts[0], 10); center = [ @@ -23,7 +23,7 @@ if (window.location.hash !== '') { } } -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -42,22 +42,22 @@ var map = new Map({ }) }); -var shouldUpdate = true; -var view = map.getView(); -var updatePermalink = function() { +let shouldUpdate = true; +const view = map.getView(); +const updatePermalink = function() { if (!shouldUpdate) { // do not update the URL when the view was changed in the 'popstate' handler shouldUpdate = true; return; } - var center = view.getCenter(); - var hash = '#map=' + + const center = view.getCenter(); + const hash = '#map=' + view.getZoom() + '/' + Math.round(center[0] * 100) / 100 + '/' + Math.round(center[1] * 100) / 100 + '/' + view.getRotation(); - var state = { + const state = { zoom: view.getZoom(), center: view.getCenter(), rotation: view.getRotation() diff --git a/examples/pinch-zoom.js b/examples/pinch-zoom.js index 22d26853e3..54cd14760b 100644 --- a/examples/pinch-zoom.js +++ b/examples/pinch-zoom.js @@ -6,7 +6,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ interactions: defaultInteractions({pinchZoom: false}).extend([ new PinchZoom({ constrainResolution: true // force zooming to a integer zoom diff --git a/examples/polygon-styles.js b/examples/polygon-styles.js index 3928e95afd..4af6880961 100644 --- a/examples/polygon-styles.js +++ b/examples/polygon-styles.js @@ -9,7 +9,7 @@ import Fill from '../src/ol/style/Fill.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var styles = [ +const styles = [ /* We are using two different styles for the polygons: * - The first style is for the polygons themselves. * - The second style is to draw the vertices of the polygons. @@ -35,13 +35,13 @@ var styles = [ }), geometry: function(feature) { // return the coordinates of the first ring of the polygon - var coordinates = feature.getGeometry().getCoordinates()[0]; + const coordinates = feature.getGeometry().getCoordinates()[0]; return new MultiPoint(coordinates); } }) ]; -var geojsonObject = { +const geojsonObject = { 'type': 'FeatureCollection', 'crs': { 'type': 'name', @@ -80,16 +80,16 @@ var geojsonObject = { }] }; -var source = new VectorSource({ +const source = new VectorSource({ features: (new GeoJSON()).readFeatures(geojsonObject) }); -var layer = new VectorLayer({ +const layer = new VectorLayer({ source: source, style: styles }); -var map = new Map({ +const map = new Map({ layers: [layer], target: 'map', view: new View({ diff --git a/examples/popup.js b/examples/popup.js index c5310790cc..9230ed62fc 100644 --- a/examples/popup.js +++ b/examples/popup.js @@ -10,15 +10,15 @@ import TileJSON from '../src/ol/source/TileJSON.js'; /** * Elements that make up the popup. */ -var container = document.getElementById('popup'); -var content = document.getElementById('popup-content'); -var closer = document.getElementById('popup-closer'); +const container = document.getElementById('popup'); +const content = document.getElementById('popup-content'); +const closer = document.getElementById('popup-closer'); /** * Create an overlay to anchor the popup to the map. */ -var overlay = new Overlay({ +const overlay = new Overlay({ element: container, autoPan: true, autoPanAnimation: { @@ -41,7 +41,7 @@ closer.onclick = function() { /** * Create the map. */ -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new TileJSON({ @@ -63,8 +63,8 @@ var map = new Map({ * Add a click handler to the map to render the popup. */ map.on('singleclick', function(evt) { - var coordinate = evt.coordinate; - var hdms = _ol_coordinate_.toStringHDMS(toLonLat(coordinate)); + const coordinate = evt.coordinate; + const hdms = _ol_coordinate_.toStringHDMS(toLonLat(coordinate)); content.innerHTML = '

You clicked here:

' + hdms + ''; diff --git a/examples/preload.js b/examples/preload.js index 0981ec5af3..777b83cae6 100644 --- a/examples/preload.js +++ b/examples/preload.js @@ -4,12 +4,12 @@ import TileLayer from '../src/ol/layer/Tile.js'; import BingMaps from '../src/ol/source/BingMaps.js'; -var view = new View({ +const view = new View({ center: [-4808600, -2620936], zoom: 8 }); -var map1 = new Map({ +const map1 = new Map({ layers: [ new TileLayer({ preload: Infinity, @@ -23,7 +23,7 @@ var map1 = new Map({ view: view }); -var map2 = new Map({ +const map2 = new Map({ layers: [ new TileLayer({ preload: 0, // default value diff --git a/examples/raster.js b/examples/raster.js index a45da59206..be3c85c40d 100644 --- a/examples/raster.js +++ b/examples/raster.js @@ -7,9 +7,9 @@ import TileLayer from '../src/ol/layer/Tile.js'; import BingMaps from '../src/ol/source/BingMaps.js'; import RasterSource from '../src/ol/source/Raster.js'; -var minVgi = 0; -var maxVgi = 0.25; -var bins = 10; +const minVgi = 0; +const maxVgi = 0.25; +const bins = 10; /** @@ -19,9 +19,9 @@ var bins = 10; * @return {number} The VGI value for the given pixel. */ function vgi(pixel) { - var r = pixel[0] / 255; - var g = pixel[1] / 255; - var b = pixel[2] / 255; + const r = pixel[0] / 255; + const g = pixel[1] / 255; + const b = pixel[2] / 255; return (2 * g - r - b) / (2 * g + r + b); } @@ -32,15 +32,15 @@ function vgi(pixel) { * @param {Object} counts An object for keeping track of VGI counts. */ function summarize(value, counts) { - var min = counts.min; - var max = counts.max; - var num = counts.values.length; + const min = counts.min; + const max = counts.max; + const num = counts.values.length; if (value < min) { // do nothing } else if (value >= max) { counts.values[num - 1] += 1; } else { - var index = Math.floor((value - min) / counts.delta); + const index = Math.floor((value - min) / counts.delta); counts.values[index] += 1; } } @@ -49,7 +49,7 @@ function summarize(value, counts) { /** * Use aerial imagery as the input data for the raster source. */ -var bing = new BingMaps({ +const bing = new BingMaps({ key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5', imagerySet: 'Aerial' }); @@ -59,7 +59,7 @@ var bing = new BingMaps({ * Create a raster source where pixels with VGI values above a threshold will * be colored green. */ -var raster = new RasterSource({ +const raster = new RasterSource({ sources: [bing], /** * Run calculations on pixel data. @@ -68,8 +68,8 @@ var raster = new RasterSource({ * @return {Array} The output pixel. */ operation: function(pixels, data) { - var pixel = pixels[0]; - var value = vgi(pixel); + const pixel = pixels[0]; + const value = vgi(pixel); summarize(value, data.counts); if (value >= data.threshold) { pixel[0] = 0; @@ -89,8 +89,8 @@ var raster = new RasterSource({ raster.set('threshold', 0.1); function createCounts(min, max, num) { - var values = new Array(num); - for (var i = 0; i < num; ++i) { + const values = new Array(num); + for (let i = 0; i < num; ++i) { values[i] = 0; } return { @@ -110,7 +110,7 @@ raster.on('afteroperations', function(event) { schedulePlot(event.resolution, event.data.counts, event.data.threshold); }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: bing @@ -129,7 +129,7 @@ var map = new Map({ }); -var timer = null; +let timer = null; function schedulePlot(resolution, counts, threshold) { if (timer) { clearTimeout(timer); @@ -138,40 +138,40 @@ function schedulePlot(resolution, counts, threshold) { timer = setTimeout(plot.bind(null, resolution, counts, threshold), 1000 / 60); } -var barWidth = 15; -var plotHeight = 150; -var chart = d3.select('#plot').append('svg') - .attr('width', barWidth * bins) - .attr('height', plotHeight); +const barWidth = 15; +const plotHeight = 150; +const chart = d3.select('#plot').append('svg') + .attr('width', barWidth * bins) + .attr('height', plotHeight); -var chartRect = chart.node().getBoundingClientRect(); +const chartRect = chart.node().getBoundingClientRect(); -var tip = d3.select(document.body).append('div') - .attr('class', 'tip'); +const tip = d3.select(document.body).append('div') + .attr('class', 'tip'); function plot(resolution, counts, threshold) { - var yScale = d3.scaleLinear() - .domain([0, d3.max(counts.values)]) - .range([0, plotHeight]); + const yScale = d3.scaleLinear() + .domain([0, d3.max(counts.values)]) + .range([0, plotHeight]); - var bar = chart.selectAll('rect').data(counts.values); + const bar = chart.selectAll('rect').data(counts.values); bar.enter().append('rect'); bar.attr('class', function(count, index) { - var value = counts.min + (index * counts.delta); + const value = counts.min + (index * counts.delta); return 'bar' + (value >= threshold ? ' selected' : ''); }) - .attr('width', barWidth - 2); + .attr('width', barWidth - 2); bar.transition().attr('transform', function(value, index) { return 'translate(' + (index * barWidth) + ', ' + (plotHeight - yScale(value)) + ')'; }) - .attr('height', yScale); + .attr('height', yScale); bar.on('mousemove', function(count, index) { - var threshold = counts.min + (index * counts.delta); + const threshold = counts.min + (index * counts.delta); if (raster.get('threshold') !== threshold) { raster.set('threshold', threshold); raster.changed(); @@ -179,8 +179,8 @@ function plot(resolution, counts, threshold) { }); bar.on('mouseover', function(count, index) { - var area = 0; - for (var i = counts.values.length - 1; i >= index; --i) { + let area = 0; + for (let i = counts.values.length - 1; i >= index; --i) { area += resolution * resolution * counts.values[i]; } tip.html(message(counts.min + (index * counts.delta), area)); @@ -201,6 +201,6 @@ function plot(resolution, counts, threshold) { } function message(value, area) { - var acres = (area / 4046.86).toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ','); + const acres = (area / 4046.86).toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ','); return acres + ' acres at
' + value.toFixed(2) + ' VGI or above'; } diff --git a/examples/region-growing.js b/examples/region-growing.js index 61424e909f..8e35a48d12 100644 --- a/examples/region-growing.js +++ b/examples/region-growing.js @@ -8,38 +8,39 @@ import BingMaps from '../src/ol/source/BingMaps.js'; import RasterSource from '../src/ol/source/Raster.js'; function growRegion(inputs, data) { - var image = inputs[0]; - var seed = data.pixel; - var delta = parseInt(data.delta); + const image = inputs[0]; + let seed = data.pixel; + const delta = parseInt(data.delta); if (!seed) { return image; } seed = seed.map(Math.round); - var width = image.width; - var height = image.height; - var inputData = image.data; - var outputData = new Uint8ClampedArray(inputData); - var seedIdx = (seed[1] * width + seed[0]) * 4; - var seedR = inputData[seedIdx]; - var seedG = inputData[seedIdx + 1]; - var seedB = inputData[seedIdx + 2]; - var edge = [seed]; + const width = image.width; + const height = image.height; + const inputData = image.data; + const outputData = new Uint8ClampedArray(inputData); + const seedIdx = (seed[1] * width + seed[0]) * 4; + const seedR = inputData[seedIdx]; + const seedG = inputData[seedIdx + 1]; + const seedB = inputData[seedIdx + 2]; + let edge = [seed]; while (edge.length) { - var newedge = []; - for (var i = 0, ii = edge.length; i < ii; i++) { + const newedge = []; + for (let i = 0, ii = edge.length; i < ii; i++) { // As noted in the Raster source constructor, this function is provided // using the `lib` option. Other functions will NOT be visible unless // provided using the `lib` option. - var next = next4Edges(edge[i]); - for (var j = 0, jj = next.length; j < jj; j++) { - var s = next[j][0], t = next[j][1]; + const next = next4Edges(edge[i]); + for (let j = 0, jj = next.length; j < jj; j++) { + const s = next[j][0]; + const t = next[j][1]; if (s >= 0 && s < width && t >= 0 && t < height) { - var ci = (t * width + s) * 4; - var cr = inputData[ci]; - var cg = inputData[ci + 1]; - var cb = inputData[ci + 2]; - var ca = inputData[ci + 3]; + const ci = (t * width + s) * 4; + const cr = inputData[ci]; + const cg = inputData[ci + 1]; + const cb = inputData[ci + 2]; + const ca = inputData[ci + 3]; // if alpha is zero, carry on if (ca === 0) { continue; @@ -63,7 +64,8 @@ function growRegion(inputs, data) { } function next4Edges(edge) { - var x = edge[0], y = edge[1]; + const x = edge[0]; + const y = edge[1]; return [ [x + 1, y], [x - 1, y], @@ -72,13 +74,13 @@ function next4Edges(edge) { ]; } -var key = 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'; +const key = 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'; -var imagery = new TileLayer({ +const imagery = new TileLayer({ source: new BingMaps({key: key, imagerySet: 'Aerial'}) }); -var raster = new RasterSource({ +const raster = new RasterSource({ sources: [imagery.getSource()], operationType: 'image', operation: growRegion, @@ -89,12 +91,12 @@ var raster = new RasterSource({ } }); -var rasterImage = new ImageLayer({ +const rasterImage = new ImageLayer({ opacity: 0.7, source: raster }); -var map = new Map({ +const map = new Map({ layers: [imagery, rasterImage], target: 'map', view: new View({ @@ -103,18 +105,18 @@ var map = new Map({ }) }); -var coordinate; +let coordinate; map.on('click', function(event) { coordinate = event.coordinate; raster.changed(); }); -var thresholdControl = document.getElementById('threshold'); +const thresholdControl = document.getElementById('threshold'); raster.on('beforeoperations', function(event) { // the event.data object will be passed to operations - var data = event.data; + const data = event.data; data.delta = thresholdControl.value; if (coordinate) { data.pixel = map.getPixelFromCoordinate(coordinate); diff --git a/examples/regularshape.js b/examples/regularshape.js index 34f851515e..cefff88c2b 100644 --- a/examples/regularshape.js +++ b/examples/regularshape.js @@ -10,10 +10,10 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var stroke = new Stroke({color: 'black', width: 2}); -var fill = new Fill({color: 'red'}); +const stroke = new Stroke({color: 'black', width: 2}); +const fill = new Fill({color: 'red'}); -var styles = { +const styles = { 'square': new Style({ image: new RegularShape({ fill: fill, @@ -66,25 +66,25 @@ var styles = { }; -var styleKeys = ['x', 'cross', 'star', 'triangle', 'square']; -var count = 250; -var features = new Array(count); -var e = 4500000; -for (var i = 0; i < count; ++i) { - var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; +const styleKeys = ['x', 'cross', 'star', 'triangle', 'square']; +const count = 250; +const features = new Array(count); +const e = 4500000; +for (let i = 0; i < count; ++i) { + const coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; features[i] = new Feature(new Point(coordinates)); features[i].setStyle(styles[styleKeys[Math.floor(Math.random() * 5)]]); } -var source = new VectorSource({ +const source = new VectorSource({ features: features }); -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: source }); -var map = new Map({ +const map = new Map({ layers: [ vectorLayer ], diff --git a/examples/render-geometry.js b/examples/render-geometry.js index fc7d8450da..97f6d5a70d 100644 --- a/examples/render-geometry.js +++ b/examples/render-geometry.js @@ -8,12 +8,12 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var canvas = document.getElementById('canvas'); -var vectorContext = _ol_render_.toContext(canvas.getContext('2d'), {size: [100, 100]}); +const canvas = document.getElementById('canvas'); +const vectorContext = _ol_render_.toContext(canvas.getContext('2d'), {size: [100, 100]}); -var fill = new Fill({color: 'blue'}); -var stroke = new Stroke({color: 'black'}); -var style = new Style({ +const fill = new Fill({color: 'blue'}); +const stroke = new Stroke({color: 'black'}); +const style = new Style({ fill: fill, stroke: stroke, image: new CircleStyle({ diff --git a/examples/reprojection-by-code.js b/examples/reprojection-by-code.js index 588488189c..47a202febf 100644 --- a/examples/reprojection-by-code.js +++ b/examples/reprojection-by-code.js @@ -9,7 +9,7 @@ import TileImage from '../src/ol/source/TileImage.js'; import proj4 from 'proj4'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -24,10 +24,10 @@ var map = new Map({ }); -var queryInput = document.getElementById('epsg-query'); -var searchButton = document.getElementById('epsg-search'); -var resultSpan = document.getElementById('epsg-result'); -var renderEdgesCheckbox = document.getElementById('render-edges'); +const queryInput = document.getElementById('epsg-query'); +const searchButton = document.getElementById('epsg-search'); +const resultSpan = document.getElementById('epsg-result'); +const renderEdgesCheckbox = document.getElementById('render-edges'); function setProjection(code, name, proj4def, bbox) { if (code === null || name === null || proj4def === null || bbox === null) { @@ -42,17 +42,17 @@ function setProjection(code, name, proj4def, bbox) { resultSpan.innerHTML = '(' + code + ') ' + name; - var newProjCode = 'EPSG:' + code; + const newProjCode = 'EPSG:' + code; proj4.defs(newProjCode, proj4def); register(proj4); - var newProj = getProjection(newProjCode); - var fromLonLat = getTransform('EPSG:4326', newProj); + const newProj = getProjection(newProjCode); + const fromLonLat = getTransform('EPSG:4326', newProj); // very approximate calculation of projection extent - var extent = _ol_extent_.applyTransform( - [bbox[1], bbox[2], bbox[3], bbox[0]], fromLonLat); + const extent = _ol_extent_.applyTransform( + [bbox[1], bbox[2], bbox[3], bbox[0]], fromLonLat); newProj.setExtent(extent); - var newView = new View({ + const newView = new View({ projection: newProj }); map.setView(newView); @@ -65,13 +65,15 @@ function search(query) { fetch('https://epsg.io/?format=json&q=' + query).then(function(response) { return response.json(); }).then(function(json) { - var results = json['results']; + const results = json['results']; if (results && results.length > 0) { - for (var i = 0, ii = results.length; i < ii; i++) { - var result = results[i]; + for (let i = 0, ii = results.length; i < ii; i++) { + const result = results[i]; if (result) { - var code = result['code'], name = result['name'], - proj4def = result['proj4'], bbox = result['bbox']; + const code = result['code']; + const name = result['name']; + const proj4def = result['proj4']; + const bbox = result['bbox']; if (code && code.length > 0 && proj4def && proj4def.length > 0 && bbox && bbox.length == 4) { setProjection(code, name, proj4def, bbox); @@ -101,7 +103,7 @@ searchButton.onclick = function(event) { renderEdgesCheckbox.onchange = function() { map.getLayers().forEach(function(layer) { if (layer instanceof TileLayer) { - var source = layer.getSource(); + const source = layer.getSource(); if (source instanceof TileImage) { source.setRenderReprojectionEdges(renderEdgesCheckbox.checked); } diff --git a/examples/reprojection-image.js b/examples/reprojection-image.js index 784f389267..81498d1017 100644 --- a/examples/reprojection-image.js +++ b/examples/reprojection-image.js @@ -15,9 +15,9 @@ proj4.defs('EPSG:27700', '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 ' + '+units=m +no_defs'); register(proj4); -var imageExtent = [0, 0, 700000, 1300000]; +const imageExtent = [0, 0, 700000, 1300000]; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() diff --git a/examples/reprojection-wgs84.js b/examples/reprojection-wgs84.js index 4bb3f41d2e..0811ef85b3 100644 --- a/examples/reprojection-wgs84.js +++ b/examples/reprojection-wgs84.js @@ -3,7 +3,7 @@ import View from '../src/ol/View.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() diff --git a/examples/reprojection.js b/examples/reprojection.js index c846083841..f4746adf8d 100644 --- a/examples/reprojection.js +++ b/examples/reprojection.js @@ -34,29 +34,29 @@ proj4.defs('ESRI:54009', '+proj=moll +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 ' + '+units=m +no_defs'); register(proj4); -var proj27700 = getProjection('EPSG:27700'); +const proj27700 = getProjection('EPSG:27700'); proj27700.setExtent([0, 0, 700000, 1300000]); -var proj23032 = getProjection('EPSG:23032'); +const proj23032 = getProjection('EPSG:23032'); proj23032.setExtent([-1206118.71, 4021309.92, 1295389.00, 8051813.28]); -var proj5479 = getProjection('EPSG:5479'); +const proj5479 = getProjection('EPSG:5479'); proj5479.setExtent([6825737.53, 4189159.80, 9633741.96, 5782472.71]); -var proj21781 = getProjection('EPSG:21781'); +const proj21781 = getProjection('EPSG:21781'); proj21781.setExtent([485071.54, 75346.36, 828515.78, 299941.84]); -var proj3413 = getProjection('EPSG:3413'); +const proj3413 = getProjection('EPSG:3413'); proj3413.setExtent([-4194304, -4194304, 4194304, 4194304]); -var proj2163 = getProjection('EPSG:2163'); +const proj2163 = getProjection('EPSG:2163'); proj2163.setExtent([-8040784.5135, -2577524.9210, 3668901.4484, 4785105.1096]); -var proj54009 = getProjection('ESRI:54009'); +const proj54009 = getProjection('ESRI:54009'); proj54009.setExtent([-18e6, -9e6, 18e6, 9e6]); -var layers = {}; +const layers = {}; layers['bng'] = new TileLayer({ source: new XYZ({ @@ -97,14 +97,14 @@ layers['wms21781'] = new TileLayer({ }) }); -var parser = new _ol_format_WMTSCapabilities_(); -var url = 'https://map1.vis.earthdata.nasa.gov/wmts-arctic/' + +const parser = new _ol_format_WMTSCapabilities_(); +const url = 'https://map1.vis.earthdata.nasa.gov/wmts-arctic/' + 'wmts.cgi?SERVICE=WMTS&request=GetCapabilities'; fetch(url).then(function(response) { return response.text(); }).then(function(text) { - var result = parser.read(text); - var options = WMTS.optionsFromCapabilities(result, { + const result = parser.read(text); + const options = WMTS.optionsFromCapabilities(result, { layer: 'OSM_Land_Mask', matrixSet: 'EPSG3413_250m' }); @@ -127,10 +127,10 @@ layers['grandcanyon'] = new TileLayer({ }) }); -var startResolution = +const startResolution = _ol_extent_.getWidth(getProjection('EPSG:3857').getExtent()) / 256; -var resolutions = new Array(22); -for (var i = 0, ii = resolutions.length; i < ii; ++i) { +const resolutions = new Array(22); +for (let i = 0, ii = resolutions.length; i < ii; ++i) { resolutions[i] = startResolution / Math.pow(2, i); } @@ -150,7 +150,7 @@ layers['states'] = new TileLayer({ }); -var map = new Map({ +const map = new Map({ layers: [ layers['osm'], layers['bng'] @@ -164,16 +164,16 @@ var map = new Map({ }); -var baseLayerSelect = document.getElementById('base-layer'); -var overlayLayerSelect = document.getElementById('overlay-layer'); -var viewProjSelect = document.getElementById('view-projection'); -var renderEdgesCheckbox = document.getElementById('render-edges'); -var renderEdges = false; +const baseLayerSelect = document.getElementById('base-layer'); +const overlayLayerSelect = document.getElementById('overlay-layer'); +const viewProjSelect = document.getElementById('view-projection'); +const renderEdgesCheckbox = document.getElementById('render-edges'); +let renderEdges = false; function updateViewProjection() { - var newProj = getProjection(viewProjSelect.value); - var newProjExtent = newProj.getExtent(); - var newView = new View({ + const newProj = getProjection(viewProjSelect.value); + const newProjExtent = newProj.getExtent(); + const newView = new View({ projection: newProj, center: _ol_extent_.getCenter(newProjExtent || [0, 0, 0, 0]), zoom: 0, @@ -199,9 +199,9 @@ viewProjSelect.onchange = function() { updateViewProjection(); -var updateRenderEdgesOnLayer = function(layer) { +const updateRenderEdgesOnLayer = function(layer) { if (layer instanceof TileLayer) { - var source = layer.getSource(); + const source = layer.getSource(); if (source instanceof TileImage) { source.setRenderReprojectionEdges(renderEdges); } @@ -213,7 +213,7 @@ var updateRenderEdgesOnLayer = function(layer) { * Handle change event. */ baseLayerSelect.onchange = function() { - var layer = layers[baseLayerSelect.value]; + const layer = layers[baseLayerSelect.value]; if (layer) { layer.setOpacity(1); updateRenderEdgesOnLayer(layer); @@ -226,7 +226,7 @@ baseLayerSelect.onchange = function() { * Handle change event. */ overlayLayerSelect.onchange = function() { - var layer = layers[overlayLayerSelect.value]; + const layer = layers[overlayLayerSelect.value]; if (layer) { layer.setOpacity(0.7); updateRenderEdgesOnLayer(layer); diff --git a/examples/reusable-source.js b/examples/reusable-source.js index 45a1cc9a01..caa3221961 100644 --- a/examples/reusable-source.js +++ b/examples/reusable-source.js @@ -3,16 +3,16 @@ import View from '../src/ol/View.js'; import TileLayer from '../src/ol/layer/Tile.js'; import XYZ from '../src/ol/source/XYZ.js'; -var urls = [ +const urls = [ 'https://{a-c}.tiles.mapbox.com/v3/mapbox.blue-marble-topo-jan/{z}/{x}/{y}.png', 'https://{a-c}.tiles.mapbox.com/v3/mapbox.blue-marble-topo-bathy-jan/{z}/{x}/{y}.png', 'https://{a-c}.tiles.mapbox.com/v3/mapbox.blue-marble-topo-jul/{z}/{x}/{y}.png', 'https://{a-c}.tiles.mapbox.com/v3/mapbox.blue-marble-topo-bathy-jul/{z}/{x}/{y}.png' ]; -var source = new XYZ(); +const source = new XYZ(); -var map = new Map({ +const map = new Map({ target: 'map', layers: [ new TileLayer({ @@ -30,9 +30,9 @@ function updateUrl(index) { source.setUrl(urls[index]); } -var buttons = document.getElementsByClassName('switcher'); -for (var i = 0, ii = buttons.length; i < ii; ++i) { - var button = buttons[i]; +const buttons = document.getElementsByClassName('switcher'); +for (let i = 0, ii = buttons.length; i < ii; ++i) { + const button = buttons[i]; button.addEventListener('click', updateUrl.bind(null, Number(button.value))); } diff --git a/examples/rotation.js b/examples/rotation.js index 5e2a5f565b..529f9e2029 100644 --- a/examples/rotation.js +++ b/examples/rotation.js @@ -5,7 +5,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() diff --git a/examples/scale-line.js b/examples/scale-line.js index e8da84fd9e..8a124641be 100644 --- a/examples/scale-line.js +++ b/examples/scale-line.js @@ -6,9 +6,9 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var scaleLineControl = new ScaleLine(); +const scaleLineControl = new ScaleLine(); -var map = new Map({ +const map = new Map({ controls: defaultControls({ attributionOptions: { collapsible: false @@ -29,7 +29,7 @@ var map = new Map({ }); -var unitsSelect = document.getElementById('units'); +const unitsSelect = document.getElementById('units'); function onChange() { scaleLineControl.setUnits(unitsSelect.value); } diff --git a/examples/scaleline-indiana-east.js b/examples/scaleline-indiana-east.js index a740932ed2..d5a525baaa 100644 --- a/examples/scaleline-indiana-east.js +++ b/examples/scaleline-indiana-east.js @@ -18,7 +18,7 @@ proj4.defs('Indiana-East', 'PROJCS["IN83-EF",GEOGCS["LL83",DATUM["NAD83",' + 'UNIT["Foot_US",0.30480060960122]]'); register(proj4); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -30,7 +30,7 @@ var map = new Map({ center: fromLonLat([-85.685, 39.891], 'Indiana-East'), zoom: 7, extent: transformExtent([-172.54, 23.81, -47.74, 86.46], - 'EPSG:4326', 'Indiana-East'), + 'EPSG:4326', 'Indiana-East'), minZoom: 6 }) }); diff --git a/examples/sea-level.js b/examples/sea-level.js index ac73fcab99..c08952e1d6 100644 --- a/examples/sea-level.js +++ b/examples/sea-level.js @@ -8,9 +8,9 @@ import RasterSource from '../src/ol/source/Raster.js'; import XYZ from '../src/ol/source/XYZ.js'; function flood(pixels, data) { - var pixel = pixels[0]; + const pixel = pixels[0]; if (pixel[3]) { - var height = -10000 + ((pixel[0] * 256 * 256 + pixel[1] * 256 + pixel[2]) * 0.1); + const height = -10000 + ((pixel[0] * 256 * 256 + pixel[1] * 256 + pixel[2]) * 0.1); if (height <= data.level) { pixel[0] = 145; pixel[1] = 175; @@ -23,19 +23,19 @@ function flood(pixels, data) { return pixel; } -var key = 'pk.eyJ1IjoidHNjaGF1YiIsImEiOiJjaW5zYW5lNHkxMTNmdWttM3JyOHZtMmNtIn0.CDIBD8H-G2Gf-cPkIuWtRg'; -var elevation = new XYZ({ +const key = 'pk.eyJ1IjoidHNjaGF1YiIsImEiOiJjaW5zYW5lNHkxMTNmdWttM3JyOHZtMmNtIn0.CDIBD8H-G2Gf-cPkIuWtRg'; +const elevation = new XYZ({ url: 'https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.pngraw?access_token=' + key, crossOrigin: 'anonymous', transition: 0 }); -var raster = new RasterSource({ +const raster = new RasterSource({ sources: [elevation], operation: flood }); -var map = new Map({ +const map = new Map({ target: 'map', layers: [ new TileLayer({ @@ -54,8 +54,8 @@ var map = new Map({ }) }); -var control = document.getElementById('level'); -var output = document.getElementById('output'); +const control = document.getElementById('level'); +const output = document.getElementById('output'); control.addEventListener('input', function() { output.innerText = control.value; raster.changed(); @@ -66,14 +66,14 @@ raster.on('beforeoperations', function(event) { event.data.level = control.value; }); -var locations = document.getElementsByClassName('location'); -for (var i = 0, ii = locations.length; i < ii; ++i) { +const locations = document.getElementsByClassName('location'); +for (let i = 0, ii = locations.length; i < ii; ++i) { locations[i].addEventListener('click', relocate); } function relocate(event) { - var data = event.target.dataset; - var view = map.getView(); + const data = event.target.dataset; + const view = map.getView(); view.setCenter(fromLonLat(data.center.split(',').map(Number))); view.setZoom(Number(data.zoom)); } diff --git a/examples/select-features.js b/examples/select-features.js index 32615701f6..5edac90abf 100644 --- a/examples/select-features.js +++ b/examples/select-features.js @@ -8,18 +8,18 @@ import VectorLayer from '../src/ol/layer/Vector.js'; import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ url: 'data/geojson/countries.geojson', format: new GeoJSON() }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ @@ -28,35 +28,35 @@ var map = new Map({ }) }); -var select = null; // ref to currently selected interaction +let select = null; // ref to currently selected interaction // select interaction working on "singleclick" -var selectSingleClick = new Select(); +const selectSingleClick = new Select(); // select interaction working on "click" -var selectClick = new Select({ +const selectClick = new Select({ condition: _ol_events_condition_.click }); // select interaction working on "pointermove" -var selectPointerMove = new Select({ +const selectPointerMove = new Select({ condition: _ol_events_condition_.pointerMove }); -var selectAltClick = new Select({ +const selectAltClick = new Select({ condition: function(mapBrowserEvent) { return _ol_events_condition_.click(mapBrowserEvent) && _ol_events_condition_.altKeyOnly(mapBrowserEvent); } }); -var selectElement = document.getElementById('type'); +const selectElement = document.getElementById('type'); -var changeInteraction = function() { +const changeInteraction = function() { if (select !== null) { map.removeInteraction(select); } - var value = selectElement.value; + const value = selectElement.value; if (value == 'singleclick') { select = selectSingleClick; } else if (value == 'click') { diff --git a/examples/semi-transparent-layer.js b/examples/semi-transparent-layer.js index 50aa7039c3..c52872d304 100644 --- a/examples/semi-transparent-layer.js +++ b/examples/semi-transparent-layer.js @@ -6,7 +6,7 @@ import OSM from '../src/ol/source/OSM.js'; import TileJSON from '../src/ol/source/TileJSON.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() diff --git a/examples/shaded-relief.js b/examples/shaded-relief.js index eca8e274b7..b7a821de2f 100644 --- a/examples/shaded-relief.js +++ b/examples/shaded-relief.js @@ -16,22 +16,22 @@ import XYZ from '../src/ol/source/XYZ.js'; * @return {ImageData} Output image. */ function shade(inputs, data) { - var elevationImage = inputs[0]; - var width = elevationImage.width; - var height = elevationImage.height; - var elevationData = elevationImage.data; - var shadeData = new Uint8ClampedArray(elevationData.length); - var dp = data.resolution * 2; - var maxX = width - 1; - var maxY = height - 1; - var pixel = [0, 0, 0, 0]; - var twoPi = 2 * Math.PI; - var halfPi = Math.PI / 2; - var sunEl = Math.PI * data.sunEl / 180; - var sunAz = Math.PI * data.sunAz / 180; - var cosSunEl = Math.cos(sunEl); - var sinSunEl = Math.sin(sunEl); - var pixelX, pixelY, x0, x1, y0, y1, offset, + const elevationImage = inputs[0]; + const width = elevationImage.width; + const height = elevationImage.height; + const elevationData = elevationImage.data; + const shadeData = new Uint8ClampedArray(elevationData.length); + const dp = data.resolution * 2; + const maxX = width - 1; + const maxY = height - 1; + const pixel = [0, 0, 0, 0]; + const twoPi = 2 * Math.PI; + const halfPi = Math.PI / 2; + const sunEl = Math.PI * data.sunEl / 180; + const sunAz = Math.PI * data.sunAz / 180; + const cosSunEl = Math.cos(sunEl); + const sinSunEl = Math.sin(sunEl); + let pixelX, pixelY, x0, x1, y0, y1, offset, z0, z1, dzdx, dzdy, slope, aspect, cosIncidence, scaled; for (pixelY = 0; pixelY <= maxY; ++pixelY) { y0 = pixelY === 0 ? 0 : pixelY - 1; @@ -102,19 +102,19 @@ function shade(inputs, data) { return {data: shadeData, width: width, height: height}; } -var elevation = new XYZ({ +const elevation = new XYZ({ url: 'https://{a-d}.tiles.mapbox.com/v3/aj.sf-dem/{z}/{x}/{y}.png', crossOrigin: 'anonymous', transition: 0 }); -var raster = new RasterSource({ +const raster = new RasterSource({ sources: [elevation], operationType: 'image', operation: shade }); -var map = new Map({ +const map = new Map({ target: 'map', layers: [ new TileLayer({ @@ -134,11 +134,11 @@ var map = new Map({ }) }); -var controlIds = ['vert', 'sunEl', 'sunAz']; -var controls = {}; +const controlIds = ['vert', 'sunEl', 'sunAz']; +const controls = {}; controlIds.forEach(function(id) { - var control = document.getElementById(id); - var output = document.getElementById(id + 'Out'); + const control = document.getElementById(id); + const output = document.getElementById(id + 'Out'); control.addEventListener('input', function() { output.innerText = control.value; raster.changed(); @@ -149,9 +149,9 @@ controlIds.forEach(function(id) { raster.on('beforeoperations', function(event) { // the event.data object will be passed to operations - var data = event.data; + const data = event.data; data.resolution = event.resolution; - for (var id in controls) { + for (const id in controls) { data[id] = Number(controls[id].value); } }); diff --git a/examples/side-by-side.js b/examples/side-by-side.js index ac6bff925a..090aa8b736 100644 --- a/examples/side-by-side.js +++ b/examples/side-by-side.js @@ -4,30 +4,30 @@ import _ol_has_ from '../src/ol/has.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var layer = new TileLayer({ +const layer = new TileLayer({ source: new OSM() }); -var view = new View({ +const view = new View({ center: [0, 0], zoom: 1 }); -var map1 = new Map({ +const map1 = new Map({ target: 'canvasMap', layers: [layer], view: view }); if (_ol_has_.WEBGL) { - var map2 = new Map({ + const map2 = new Map({ target: 'webglMap', renderer: /** @type {Array} */ (['webgl', 'canvas']), layers: [layer], view: view }); } else { - var info = document.getElementById('no-webgl'); + const info = document.getElementById('no-webgl'); /** * display error message */ diff --git a/examples/simple.js b/examples/simple.js index 01bb501621..e128b8e9ec 100644 --- a/examples/simple.js +++ b/examples/simple.js @@ -4,7 +4,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() diff --git a/examples/snap.js b/examples/snap.js index 34131a79bb..15fda2ded9 100644 --- a/examples/snap.js +++ b/examples/snap.js @@ -13,11 +13,11 @@ import Fill from '../src/ol/style/Fill.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource(), style: new Style({ fill: new Fill({ @@ -36,7 +36,7 @@ var vector = new VectorLayer({ }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ @@ -45,7 +45,7 @@ var map = new Map({ }) }); -var ExampleModify = { +const ExampleModify = { init: function() { this.select = new Select(); map.addInteraction(this.select); @@ -58,7 +58,7 @@ var ExampleModify = { this.setEvents(); }, setEvents: function() { - var selectedFeatures = this.select.getFeatures(); + const selectedFeatures = this.select.getFeatures(); this.select.on('change:active', function() { selectedFeatures.forEach(selectedFeatures.remove, selectedFeatures); @@ -71,9 +71,9 @@ var ExampleModify = { }; ExampleModify.init(); -var optionsForm = document.getElementById('options-form'); +const optionsForm = document.getElementById('options-form'); -var ExampleDraw = { +const ExampleDraw = { init: function() { map.addInteraction(this.Point); this.Point.setActive(false); @@ -104,7 +104,7 @@ var ExampleDraw = { return this.activeType ? this[this.activeType].getActive() : false; }, setActive: function(active) { - var type = optionsForm.elements['draw-type'].value; + const type = optionsForm.elements['draw-type'].value; if (active) { this.activeType && this[this.activeType].setActive(false); this[type].setActive(true); @@ -123,8 +123,8 @@ ExampleDraw.init(); * @param {Event} e Change event. */ optionsForm.onchange = function(e) { - var type = e.target.getAttribute('name'); - var value = e.target.value; + const type = e.target.getAttribute('name'); + const value = e.target.value; if (type == 'draw-type') { ExampleDraw.getActive() && ExampleDraw.setActive(true); } else if (type == 'interaction') { @@ -144,7 +144,7 @@ ExampleModify.setActive(false); // The snap interaction must be added after the Modify and Draw interactions // in order for its map browser event handlers to be fired first. Its handlers // are responsible of doing the snapping. -var snap = new Snap({ +const snap = new Snap({ source: vector.getSource() }); map.addInteraction(snap); diff --git a/examples/sphere-mollweide.js b/examples/sphere-mollweide.js index 09a667a1b1..e86d0c3ab7 100644 --- a/examples/sphere-mollweide.js +++ b/examples/sphere-mollweide.js @@ -15,14 +15,14 @@ register(proj4); // Configure the Sphere Mollweide projection object with an extent, // and a world extent. These are required for the Graticule. -var sphereMollweideProjection = new Projection({ +const sphereMollweideProjection = new Projection({ code: 'ESRI:53009', extent: [-9009954.605703328, -9009954.605703328, 9009954.605703328, 9009954.605703328], worldExtent: [-179, -89.99, 179, 89.99] }); -var map = new Map({ +const map = new Map({ keyboardEventTarget: document, layers: [ new VectorLayer({ diff --git a/examples/stamen.js b/examples/stamen.js index 0a44ab490a..6b68a0eee1 100644 --- a/examples/stamen.js +++ b/examples/stamen.js @@ -5,7 +5,7 @@ import {fromLonLat} from '../src/ol/proj.js'; import Stamen from '../src/ol/source/Stamen.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new Stamen({ diff --git a/examples/static-image.js b/examples/static-image.js index 3e152094cf..3566e6f416 100644 --- a/examples/static-image.js +++ b/examples/static-image.js @@ -9,14 +9,14 @@ import Static from '../src/ol/source/ImageStatic.js'; // Map views always need a projection. Here we just want to map image // coordinates directly to map coordinates, so we create a projection that uses // the image extent in pixels. -var extent = [0, 0, 1024, 968]; -var projection = new Projection({ +const extent = [0, 0, 1024, 968]; +const projection = new Projection({ code: 'xkcd-image', units: 'pixels', extent: extent }); -var map = new Map({ +const map = new Map({ layers: [ new ImageLayer({ source: new Static({ diff --git a/examples/street-labels.js b/examples/street-labels.js index 6d7dc1ef5f..ab8f875176 100644 --- a/examples/street-labels.js +++ b/examples/street-labels.js @@ -10,7 +10,7 @@ import Fill from '../src/ol/style/Fill.js'; import Style from '../src/ol/style/Style.js'; import Text from '../src/ol/style/Text.js'; -var style = new Style({ +const style = new Style({ text: new Text({ font: 'bold 11px "Open Sans", "Arial Unicode MS", "sans-serif"', placement: 'line', @@ -20,8 +20,8 @@ var style = new Style({ }) }); -var viewExtent = [1817379, 6139595, 1827851, 6143616]; -var map = new Map({ +const viewExtent = [1817379, 6139595, 1827851, 6143616]; +const map = new Map({ layers: [new TileLayer({ source: new BingMaps({ key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5', diff --git a/examples/symbol-atlas-webgl.js b/examples/symbol-atlas-webgl.js index ceaa52a172..74f86d1302 100644 --- a/examples/symbol-atlas-webgl.js +++ b/examples/symbol-atlas-webgl.js @@ -11,13 +11,13 @@ import RegularShape from '../src/ol/style/RegularShape.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var atlasManager = new AtlasManager({ +const atlasManager = new AtlasManager({ // we increase the initial size so that all symbols fit into // a single atlas image initialSize: 512 }); -var symbolInfo = [{ +const symbolInfo = [{ opacity: 1.0, scale: 1.0, fillColor: 'rgba(255, 153, 0, 0.4)', @@ -39,12 +39,12 @@ var symbolInfo = [{ strokeColor: 'rgba(145, 43, 20, 0.2)' }]; -var radiuses = [3, 6, 9, 15, 19, 25]; -var symbolCount = symbolInfo.length * radiuses.length * 2; -var symbols = []; -var i, j; +const radiuses = [3, 6, 9, 15, 19, 25]; +const symbolCount = symbolInfo.length * radiuses.length * 2; +const symbols = []; +let i, j; for (i = 0; i < symbolInfo.length; ++i) { - var info = symbolInfo[i]; + const info = symbolInfo[i]; for (j = 0; j < radiuses.length; ++j) { // circle symbol symbols.push(new CircleStyle({ @@ -83,30 +83,30 @@ for (i = 0; i < symbolInfo.length; ++i) { } } -var featureCount = 50000; -var features = new Array(featureCount); -var feature, geometry; -var e = 25000000; +const featureCount = 50000; +const features = new Array(featureCount); +let feature, geometry; +const e = 25000000; for (i = 0; i < featureCount; ++i) { geometry = new Point( - [2 * e * Math.random() - e, 2 * e * Math.random() - e]); + [2 * e * Math.random() - e, 2 * e * Math.random() - e]); feature = new Feature(geometry); feature.setStyle( - new Style({ - image: symbols[i % symbolCount] - }) + new Style({ + image: symbols[i % symbolCount] + }) ); features[i] = feature; } -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ features: features }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: vectorSource }); -var map = new Map({ +const map = new Map({ renderer: /** @type {Array} */ (['webgl', 'canvas']), layers: [vector], target: document.getElementById('map'), diff --git a/examples/synthetic-lines.js b/examples/synthetic-lines.js index 5854ac99c0..104f6703e3 100644 --- a/examples/synthetic-lines.js +++ b/examples/synthetic-lines.js @@ -8,18 +8,18 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var count = 10000; -var features = new Array(count); +const count = 10000; +const features = new Array(count); -var startPoint = [0, 0]; -var endPoint; +let startPoint = [0, 0]; +let endPoint; -var delta, deltaX, deltaY; -var signX = 1; -var signY = -1; +let delta, deltaX, deltaY; +let signX = 1; +let signY = -1; // Create a square spiral. -var i; +let i; for (i = 0; i < count; ++i) { delta = (i + 1) * 2500; if (i % 2 === 0) { @@ -36,7 +36,7 @@ for (i = 0; i < count; ++i) { startPoint = endPoint; } -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ features: features, wrapX: false @@ -49,12 +49,12 @@ var vector = new VectorLayer({ }) }); -var view = new View({ +const view = new View({ center: [0, 0], zoom: 0 }); -var map = new Map({ +const map = new Map({ layers: [vector], target: 'map', view: view diff --git a/examples/synthetic-points.js b/examples/synthetic-points.js index a26d956984..37705d4b31 100644 --- a/examples/synthetic-points.js +++ b/examples/synthetic-points.js @@ -11,19 +11,19 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var count = 20000; -var features = new Array(count); -var e = 18000000; -for (var i = 0; i < count; ++i) { +const count = 20000; +const features = new Array(count); +const e = 18000000; +for (let i = 0; i < count; ++i) { features[i] = new Feature({ 'geometry': new Point( - [2 * e * Math.random() - e, 2 * e * Math.random() - e]), + [2 * e * Math.random() - e, 2 * e * Math.random() - e]), 'i': i, 'size': i % 2 ? 10 : 20 }); } -var styles = { +const styles = { '10': new Style({ image: new CircleStyle({ radius: 5, @@ -40,18 +40,18 @@ var styles = { }) }; -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ features: features, wrapX: false }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: vectorSource, style: function(feature) { return styles[feature.get('size')]; } }); -var map = new Map({ +const map = new Map({ layers: [vector], target: document.getElementById('map'), view: new View({ @@ -60,16 +60,16 @@ var map = new Map({ }) }); -var point = null; -var line = null; -var displaySnap = function(coordinate) { - var closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate); +let point = null; +let line = null; +const displaySnap = function(coordinate) { + const closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate); if (closestFeature === null) { point = null; line = null; } else { - var geometry = closestFeature.getGeometry(); - var closestPoint = geometry.getClosestPoint(coordinate); + const geometry = closestFeature.getGeometry(); + const closestPoint = geometry.getClosestPoint(coordinate); if (point === null) { point = new Point(closestPoint); } else { @@ -88,7 +88,7 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var coordinate = map.getEventCoordinate(evt.originalEvent); + const coordinate = map.getEventCoordinate(evt.originalEvent); displaySnap(coordinate); }); @@ -96,11 +96,11 @@ map.on('click', function(evt) { displaySnap(evt.coordinate); }); -var stroke = new Stroke({ +const stroke = new Stroke({ color: 'rgba(255,255,0,0.9)', width: 3 }); -var style = new Style({ +const style = new Style({ stroke: stroke, image: new CircleStyle({ radius: 10, @@ -109,7 +109,7 @@ var style = new Style({ }); map.on('postcompose', function(evt) { - var vectorContext = evt.vectorContext; + const vectorContext = evt.vectorContext; vectorContext.setStyle(style); if (point !== null) { vectorContext.drawGeometry(point); @@ -123,8 +123,8 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); - var hit = map.hasFeatureAtPixel(pixel); + const pixel = map.getEventPixel(evt.originalEvent); + const hit = map.hasFeatureAtPixel(pixel); if (hit) { map.getTarget().style.cursor = 'pointer'; } else { diff --git a/examples/teleport.js b/examples/teleport.js index 88785b2281..39ba91c627 100644 --- a/examples/teleport.js +++ b/examples/teleport.js @@ -5,7 +5,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -24,9 +24,9 @@ var map = new Map({ map.setTarget('map1'); -var teleportButton = document.getElementById('teleport'); +const teleportButton = document.getElementById('teleport'); teleportButton.addEventListener('click', function() { - var target = map.getTarget() === 'map1' ? 'map2' : 'map1'; + const target = map.getTarget() === 'map1' ? 'map2' : 'map1'; map.setTarget(target); }, false); diff --git a/examples/tile-load-events.js b/examples/tile-load-events.js index e8c0b20297..40a2c93da0 100644 --- a/examples/tile-load-events.js +++ b/examples/tile-load-events.js @@ -32,7 +32,7 @@ Progress.prototype.addLoading = function() { * Increment the count of loaded tiles. */ Progress.prototype.addLoaded = function() { - var this_ = this; + const this_ = this; setTimeout(function() { ++this_.loaded; this_.update(); @@ -44,12 +44,12 @@ Progress.prototype.addLoaded = function() { * Update the progress bar. */ Progress.prototype.update = function() { - var width = (this.loaded / this.loading * 100).toFixed(1) + '%'; + const width = (this.loaded / this.loading * 100).toFixed(1) + '%'; this.el.style.width = width; if (this.loading === this.loaded) { this.loading = 0; this.loaded = 0; - var this_ = this; + const this_ = this; setTimeout(function() { this_.hide(); }, 500); @@ -75,9 +75,9 @@ Progress.prototype.hide = function() { } }; -var progress = new Progress(document.getElementById('progress')); +const progress = new Progress(document.getElementById('progress')); -var source = new TileJSON({ +const source = new TileJSON({ url: 'https://api.tiles.mapbox.com/v3/mapbox.world-bright.json?secure', crossOrigin: 'anonymous' }); @@ -93,7 +93,7 @@ source.on('tileloaderror', function() { progress.addLoaded(); }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({source: source}) ], diff --git a/examples/tile-transitions.js b/examples/tile-transitions.js index 5715978741..eb0701c95f 100644 --- a/examples/tile-transitions.js +++ b/examples/tile-transitions.js @@ -3,18 +3,18 @@ import View from '../src/ol/View.js'; import TileLayer from '../src/ol/layer/Tile.js'; import XYZ from '../src/ol/source/XYZ.js'; -var url = 'https://{a-c}.tiles.mapbox.com/v3/mapbox.world-bright/{z}/{x}/{y}.png'; +const url = 'https://{a-c}.tiles.mapbox.com/v3/mapbox.world-bright/{z}/{x}/{y}.png'; -var withTransition = new TileLayer({ +const withTransition = new TileLayer({ source: new XYZ({url: url}) }); -var withoutTransition = new TileLayer({ +const withoutTransition = new TileLayer({ source: new XYZ({url: url, transition: 0}), visible: false }); -var map = new Map({ +const map = new Map({ layers: [withTransition, withoutTransition], target: 'map', view: new View({ @@ -25,7 +25,7 @@ var map = new Map({ }); document.getElementById('transition').addEventListener('change', function(event) { - var transition = event.target.checked; + const transition = event.target.checked; withTransition.setVisible(transition); withoutTransition.setVisible(!transition); }); diff --git a/examples/tilejson.js b/examples/tilejson.js index c5d01d85a6..d24a4aba8c 100644 --- a/examples/tilejson.js +++ b/examples/tilejson.js @@ -4,7 +4,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import TileJSON from '../src/ol/source/TileJSON.js'; -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new TileJSON({ diff --git a/examples/tileutfgrid.js b/examples/tileutfgrid.js index 11e1633f13..36fb17722e 100644 --- a/examples/tileutfgrid.js +++ b/examples/tileutfgrid.js @@ -5,65 +5,65 @@ import TileLayer from '../src/ol/layer/Tile.js'; import TileJSON from '../src/ol/source/TileJSON.js'; import UTFGrid from '../src/ol/source/TileUTFGrid.js'; -var key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiRk1kMWZaSSJ9.E5BkluenyWQMsBLsuByrmg'; +const key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiRk1kMWZaSSJ9.E5BkluenyWQMsBLsuByrmg'; -var mapLayer = new TileLayer({ +const mapLayer = new TileLayer({ source: new TileJSON({ url: 'https://api.tiles.mapbox.com/v4/mapbox.geography-class.json?secure&access_token=' + key }) }); -var gridSource = new UTFGrid({ +const gridSource = new UTFGrid({ url: 'https://api.tiles.mapbox.com/v4/mapbox.geography-class.json?secure&access_token=' + key }); -var gridLayer = new TileLayer({source: gridSource}); +const gridLayer = new TileLayer({source: gridSource}); -var view = new View({ +const view = new View({ center: [0, 0], zoom: 1 }); -var mapElement = document.getElementById('map'); -var map = new Map({ +const mapElement = document.getElementById('map'); +const map = new Map({ layers: [mapLayer, gridLayer], target: mapElement, view: view }); -var infoElement = document.getElementById('country-info'); -var flagElement = document.getElementById('country-flag'); -var nameElement = document.getElementById('country-name'); +const infoElement = document.getElementById('country-info'); +const flagElement = document.getElementById('country-flag'); +const nameElement = document.getElementById('country-name'); -var infoOverlay = new Overlay({ +const infoOverlay = new Overlay({ element: infoElement, offset: [15, 15], stopEvent: false }); map.addOverlay(infoOverlay); -var displayCountryInfo = function(coordinate) { - var viewResolution = /** @type {number} */ (view.getResolution()); +const displayCountryInfo = function(coordinate) { + const viewResolution = /** @type {number} */ (view.getResolution()); gridSource.forDataAtCoordinateAndResolution(coordinate, viewResolution, - function(data) { - // If you want to use the template from the TileJSON, - // load the mustache.js library separately and call - // info.innerHTML = Mustache.render(gridSource.getTemplate(), data); - mapElement.style.cursor = data ? 'pointer' : ''; - if (data) { - flagElement.src = 'data:image/png;base64,' + data['flag_png']; - nameElement.innerHTML = data['admin']; - } - infoOverlay.setPosition(data ? coordinate : undefined); - }); + function(data) { + // If you want to use the template from the TileJSON, + // load the mustache.js library separately and call + // info.innerHTML = Mustache.render(gridSource.getTemplate(), data); + mapElement.style.cursor = data ? 'pointer' : ''; + if (data) { + flagElement.src = 'data:image/png;base64,' + data['flag_png']; + nameElement.innerHTML = data['admin']; + } + infoOverlay.setPosition(data ? coordinate : undefined); + }); }; map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var coordinate = map.getEventCoordinate(evt.originalEvent); + const coordinate = map.getEventCoordinate(evt.originalEvent); displayCountryInfo(coordinate); }); diff --git a/examples/tissot.js b/examples/tissot.js index b8f2880a38..c4c7a22b33 100644 --- a/examples/tissot.js +++ b/examples/tissot.js @@ -7,15 +7,15 @@ import VectorLayer from '../src/ol/layer/Vector.js'; import TileWMS from '../src/ol/source/TileWMS.js'; import VectorSource from '../src/ol/source/Vector.js'; -var vectorLayer4326 = new VectorLayer({ +const vectorLayer4326 = new VectorLayer({ source: new VectorSource() }); -var vectorLayer3857 = new VectorLayer({ +const vectorLayer3857 = new VectorLayer({ source: new VectorSource() }); -var map4326 = new Map({ +const map4326 = new Map({ layers: [ new TileLayer({ source: new TileWMS({ @@ -36,7 +36,7 @@ var map4326 = new Map({ }) }); -var map3857 = new Map({ +const map3857 = new Map({ layers: [ new TileLayer({ source: new TileWMS({ @@ -56,12 +56,12 @@ var map3857 = new Map({ }) }); -var radius = 800000; -var x, y; +const radius = 800000; +let x, y; for (x = -180; x < 180; x += 30) { for (y = -90; y < 90; y += 30) { - var circle4326 = circularPolygon([x, y], radius, 64); - var circle3857 = circle4326.clone().transform('EPSG:4326', 'EPSG:3857'); + const circle4326 = circularPolygon([x, y], radius, 64); + const circle3857 = circle4326.clone().transform('EPSG:4326', 'EPSG:3857'); vectorLayer4326.getSource().addFeature(new Feature(circle4326)); vectorLayer3857.getSource().addFeature(new Feature(circle3857)); } diff --git a/examples/topojson.js b/examples/topojson.js index f43ca0fffb..aa539f6d00 100644 --- a/examples/topojson.js +++ b/examples/topojson.js @@ -10,13 +10,13 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new TileJSON({ url: 'https://api.tiles.mapbox.com/v3/mapbox.world-dark.json?secure' }) }); -var style = new Style({ +const style = new Style({ fill: new Fill({ color: 'rgba(255, 255, 255, 0.6)' }), @@ -26,7 +26,7 @@ var style = new Style({ }) }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ url: 'data/topojson/world-110m.json', format: new TopoJSON({ @@ -39,7 +39,7 @@ var vector = new VectorLayer({ style: style }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ diff --git a/examples/topolis.js b/examples/topolis.js index 5358056cb3..ee28f75f2e 100644 --- a/examples/topolis.js +++ b/examples/topolis.js @@ -20,15 +20,15 @@ import CircleStyle from '../src/ol/style/Circle.js'; import Text from '../src/ol/style/Text.js'; import MousePosition from '../src/ol/control/MousePosition.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var nodes = new VectorSource({wrapX: false}); -var nodesLayer = new VectorLayer({ +const nodes = new VectorSource({wrapX: false}); +const nodesLayer = new VectorLayer({ source: nodes, style: function(f) { - var style = new Style({ + const style = new Style({ image: new CircleStyle({ radius: 8, fill: new Fill({color: 'rgba(255, 0, 0, 0.2)'}), @@ -47,11 +47,11 @@ var nodesLayer = new VectorLayer({ } }); -var edges = new VectorSource({wrapX: false}); -var edgesLayer = new VectorLayer({ +const edges = new VectorSource({wrapX: false}); +const edgesLayer = new VectorLayer({ source: edges, style: function(f) { - var style = new Style({ + const style = new Style({ stroke: new Stroke({ color: 'blue', width: 1 @@ -69,11 +69,11 @@ var edgesLayer = new VectorLayer({ } }); -var faces = new VectorSource({wrapX: false}); -var facesLayer = new VectorLayer({ +const faces = new VectorSource({wrapX: false}); +const facesLayer = new VectorLayer({ source: faces, style: function(f) { - var style = new Style({ + const style = new Style({ stroke: new Stroke({ color: 'black', width: 1 @@ -95,7 +95,7 @@ var facesLayer = new VectorLayer({ } }); -var map = new Map({ +const map = new Map({ layers: [raster, facesLayer, edgesLayer, nodesLayer], target: 'map', view: new View({ @@ -104,7 +104,7 @@ var map = new Map({ }) }); -var topo = topolis.createTopology(); +const topo = topolis.createTopology(); topo.on('addnode', nodeToFeature); topo.on('removenode', function(e) { @@ -112,7 +112,7 @@ topo.on('removenode', function(e) { }); topo.on('addedge', edgeToFeature); topo.on('modedge', function(e) { - var feature = edges.getFeatureById(e.id); + const feature = edges.getFeatureById(e.id); feature.setGeometry(new LineString(e.coordinates)); }); topo.on('removeedge', function(e) { @@ -124,12 +124,12 @@ topo.on('removeface', function(e) { }); function removeElementFeature(source, element) { - var feature = source.getFeatureById(element.id); + const feature = source.getFeatureById(element.id); source.removeFeature(feature); } function nodeToFeature(node) { - var feature = new Feature({ + const feature = new Feature({ geometry: new Point(node.coordinate), node: node }); @@ -138,7 +138,7 @@ function nodeToFeature(node) { } function edgeToFeature(edge) { - var feature = new Feature({ + const feature = new Feature({ geometry: new LineString(edge.coordinates), edge: edge }); @@ -147,8 +147,8 @@ function edgeToFeature(edge) { } function faceToFeature(face) { - var coordinates = topo.getFaceGeometry(face); - var feature = new Feature({ + const coordinates = topo.getFaceGeometry(face); + const feature = new Feature({ geometry: new Polygon(coordinates), face: face }); @@ -157,8 +157,8 @@ function faceToFeature(face) { } function createNode(topo, coord) { - var node; - var existingEdge = topo.getEdgeByPoint(coord, 5)[0]; + let node; + const existingEdge = topo.getEdgeByPoint(coord, 5)[0]; if (existingEdge) { node = topo.modEdgeSplit(existingEdge, coord); } else { @@ -168,16 +168,16 @@ function createNode(topo, coord) { } function onDrawend(e) { - var edgeGeom = e.feature.getGeometry().getCoordinates(); - var startCoord = edgeGeom[0]; - var endCoord = edgeGeom[edgeGeom.length - 1]; - var start, end; + const edgeGeom = e.feature.getGeometry().getCoordinates(); + const startCoord = edgeGeom[0]; + const endCoord = edgeGeom[edgeGeom.length - 1]; + let start, end; try { start = topo.getNodeByPoint(startCoord); end = topo.getNodeByPoint(endCoord); - var edgesAtStart = topo.getEdgeByPoint(startCoord, 5); - var edgesAtEnd = topo.getEdgeByPoint(endCoord, 5); - var crossing = topo.getEdgesByLine(edgeGeom); + const edgesAtStart = topo.getEdgeByPoint(startCoord, 5); + const edgesAtEnd = topo.getEdgeByPoint(endCoord, 5); + const crossing = topo.getEdgesByLine(edgeGeom); if (crossing.length === 1 && !start && !end && edgesAtStart.length === 0 && edgesAtEnd.length === 0) { topo.remEdgeNewFace(crossing[0]); start = crossing[0].start; @@ -204,12 +204,12 @@ function onDrawend(e) { } } -var draw = new Draw({ +const draw = new Draw({ type: 'LineString' }); draw.on('drawend', onDrawend); map.addInteraction(draw); -var snap = new Snap({ +const snap = new Snap({ source: edges }); map.addInteraction(snap); diff --git a/examples/translate-features.js b/examples/translate-features.js index 1638798c9b..1b9a345f7b 100644 --- a/examples/translate-features.js +++ b/examples/translate-features.js @@ -10,24 +10,24 @@ import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ url: 'data/geojson/countries.geojson', format: new GeoJSON() }) }); -var select = new Select(); +const select = new Select(); -var translate = new _ol_interaction_Translate_({ +const translate = new _ol_interaction_Translate_({ features: select.getFeatures() }); -var map = new Map({ +const map = new Map({ interactions: defaultInteractions().extend([select, translate]), layers: [raster, vector], target: 'map', diff --git a/examples/turf.js b/examples/turf.js index a9ee78ba9e..1eae5b307c 100644 --- a/examples/turf.js +++ b/examples/turf.js @@ -10,27 +10,27 @@ import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var source = new VectorSource(); +const source = new VectorSource(); fetch('data/geojson/roads-seoul.geojson').then(function(response) { return response.json(); }).then(function(json) { - var format = new GeoJSON(); - var features = format.readFeatures(json); - var street = features[0]; + const format = new GeoJSON(); + const features = format.readFeatures(json); + const street = features[0]; // convert to a turf.js feature - var turfLine = format.writeFeatureObject(street); + const turfLine = format.writeFeatureObject(street); // show a marker every 200 meters - var distance = 0.2; + const distance = 0.2; // get the line length in kilometers - var length = turf.lineDistance(turfLine, 'kilometers'); - for (var i = 1; i <= length / distance; i++) { - var turfPoint = turf.along(turfLine, i * distance, 'kilometers'); + const length = turf.lineDistance(turfLine, 'kilometers'); + for (let i = 1; i <= length / distance; i++) { + const turfPoint = turf.along(turfLine, i * distance, 'kilometers'); // convert the generated point to a OpenLayers feature - var marker = format.readFeature(turfPoint); + const marker = format.readFeature(turfPoint); marker.getGeometry().transform('EPSG:4326', 'EPSG:3857'); source.addFeature(marker); } @@ -38,15 +38,15 @@ fetch('data/geojson/roads-seoul.geojson').then(function(response) { street.getGeometry().transform('EPSG:4326', 'EPSG:3857'); source.addFeature(street); }); -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: source }); -var rasterLayer = new TileLayer({ +const rasterLayer = new TileLayer({ source: new OSM() }); -var map = new Map({ +const map = new Map({ layers: [rasterLayer, vectorLayer], target: document.getElementById('map'), view: new View({ diff --git a/examples/vector-esri-edit.js b/examples/vector-esri-edit.js index ba9d6e8f43..d5660a5d82 100644 --- a/examples/vector-esri-edit.js +++ b/examples/vector-esri-edit.js @@ -14,15 +14,15 @@ import XYZ from '../src/ol/source/XYZ.js'; import _ol_tilegrid_ from '../src/ol/tilegrid.js'; -var serviceUrl = 'https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/' + +const serviceUrl = 'https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/' + 'services/PDX_Pedestrian_Districts/FeatureServer/'; -var layer = '0'; +const layer = '0'; -var esrijsonFormat = new EsriJSON(); +const esrijsonFormat = new EsriJSON(); -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ loader: function(extent, resolution, projection) { - var url = serviceUrl + layer + '/query/?f=json&' + + const url = serviceUrl + layer + '/query/?f=json&' + 'returnGeometry=true&spatialRel=esriSpatialRelIntersects&geometry=' + encodeURIComponent('{"xmin":' + extent[0] + ',"ymin":' + extent[1] + ',"xmax":' + extent[2] + ',"ymax":' + extent[3] + @@ -35,7 +35,7 @@ var vectorSource = new VectorSource({ response.error.details.join('\n')); } else { // dataProjection will be read from document - var features = esrijsonFormat.readFeatures(response, { + const features = esrijsonFormat.readFeatures(response, { featureProjection: projection }); if (features.length > 0) { @@ -49,11 +49,11 @@ var vectorSource = new VectorSource({ })) }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: vectorSource }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new XYZ({ attributions: 'Tiles © ArcGIS', @@ -62,21 +62,21 @@ var raster = new TileLayer({ }) }); -var draw = new Draw({ +const draw = new Draw({ source: vectorSource, type: 'Polygon' }); -var select = new Select(); +const select = new Select(); select.setActive(false); -var selected = select.getFeatures(); +const selected = select.getFeatures(); -var modify = new Modify({ +const modify = new Modify({ features: selected }); modify.setActive(false); -var map = new Map({ +const map = new Map({ interactions: defaultInteractions().extend([draw, select, modify]), layers: [raster, vector], target: document.getElementById('map'), @@ -86,7 +86,7 @@ var map = new Map({ }) }); -var typeSelect = document.getElementById('type'); +const typeSelect = document.getElementById('type'); /** @@ -98,28 +98,28 @@ typeSelect.onchange = function() { modify.setActive(typeSelect.value === 'MODIFY'); }; -var dirty = {}; +const dirty = {}; selected.on('add', function(evt) { - var feature = evt.element; + const feature = evt.element; feature.on('change', function(evt) { dirty[evt.target.getId()] = true; }); }); selected.on('remove', function(evt) { - var feature = evt.element; - var fid = feature.getId(); + const feature = evt.element; + const fid = feature.getId(); if (dirty[fid] === true) { - var payload = '[' + esrijsonFormat.writeFeature(feature, { + const payload = '[' + esrijsonFormat.writeFeature(feature, { featureProjection: map.getView().getProjection() }) + ']'; - var url = serviceUrl + layer + '/updateFeatures'; + const url = serviceUrl + layer + '/updateFeatures'; $.post(url, {f: 'json', features: payload}).done(function(data) { - var result = JSON.parse(data); + const result = JSON.parse(data); if (result.updateResults && result.updateResults.length > 0) { if (result.updateResults[0].success !== true) { - var error = result.updateResults[0].error; + const error = result.updateResults[0].error; alert(error.description + ' (' + error.code + ')'); } else { delete dirty[fid]; @@ -130,19 +130,19 @@ selected.on('remove', function(evt) { }); draw.on('drawend', function(evt) { - var feature = evt.feature; - var payload = '[' + esrijsonFormat.writeFeature(feature, { + const feature = evt.feature; + const payload = '[' + esrijsonFormat.writeFeature(feature, { featureProjection: map.getView().getProjection() }) + ']'; - var url = serviceUrl + layer + '/addFeatures'; + const url = serviceUrl + layer + '/addFeatures'; $.post(url, {f: 'json', features: payload}).done(function(data) { - var result = JSON.parse(data); + const result = JSON.parse(data); if (result.addResults && result.addResults.length > 0) { if (result.addResults[0].success === true) { feature.setId(result.addResults[0]['objectId']); vectorSource.clear(); } else { - var error = result.addResults[0].error; + const error = result.addResults[0].error; alert(error.description + ' (' + error.code + ')'); } } diff --git a/examples/vector-esri.js b/examples/vector-esri.js index de7d898d67..e3c7bfdba6 100644 --- a/examples/vector-esri.js +++ b/examples/vector-esri.js @@ -13,13 +13,13 @@ import Style from '../src/ol/style/Style.js'; import _ol_tilegrid_ from '../src/ol/tilegrid.js'; -var serviceUrl = 'https://sampleserver3.arcgisonline.com/ArcGIS/rest/services/' + +const serviceUrl = 'https://sampleserver3.arcgisonline.com/ArcGIS/rest/services/' + 'Petroleum/KSFields/FeatureServer/'; -var layer = '0'; +const layer = '0'; -var esrijsonFormat = new EsriJSON(); +const esrijsonFormat = new EsriJSON(); -var styleCache = { +const styleCache = { 'ABANDONED': new Style({ fill: new Fill({ color: 'rgba(225, 225, 225, 255)' @@ -58,9 +58,9 @@ var styleCache = { }) }; -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ loader: function(extent, resolution, projection) { - var url = serviceUrl + layer + '/query/?f=json&' + + const url = serviceUrl + layer + '/query/?f=json&' + 'returnGeometry=true&spatialRel=esriSpatialRelIntersects&geometry=' + encodeURIComponent('{"xmin":' + extent[0] + ',"ymin":' + extent[1] + ',"xmax":' + extent[2] + ',"ymax":' + extent[3] + @@ -73,7 +73,7 @@ var vectorSource = new VectorSource({ response.error.details.join('\n')); } else { // dataProjection will be read from document - var features = esrijsonFormat.readFeatures(response, { + const features = esrijsonFormat.readFeatures(response, { featureProjection: projection }); if (features.length > 0) { @@ -87,15 +87,15 @@ var vectorSource = new VectorSource({ })) }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: vectorSource, style: function(feature) { - var classify = feature.get('activeprod'); + const classify = feature.get('activeprod'); return styleCache[classify]; } }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new XYZ({ attributions: 'Tiles © ArcGIS', @@ -104,7 +104,7 @@ var raster = new TileLayer({ }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: document.getElementById('map'), view: new View({ @@ -113,14 +113,14 @@ var map = new Map({ }) }); -var displayFeatureInfo = function(pixel) { - var features = []; +const displayFeatureInfo = function(pixel) { + const features = []; map.forEachFeatureAtPixel(pixel, function(feature) { features.push(feature); }); if (features.length > 0) { - var info = []; - var i, ii; + const info = []; + let i, ii; for (i = 0, ii = features.length; i < ii; ++i) { info.push(features[i].get('field_name')); } @@ -136,7 +136,7 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); + const pixel = map.getEventPixel(evt.originalEvent); displayFeatureInfo(pixel); }); diff --git a/examples/vector-label-decluttering.js b/examples/vector-label-decluttering.js index 8daf6e326f..a7c7c6bb34 100644 --- a/examples/vector-label-decluttering.js +++ b/examples/vector-label-decluttering.js @@ -9,7 +9,7 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; import Text from '../src/ol/style/Text.js'; -var map = new Map({ +const map = new Map({ target: 'map', view: new View({ center: [0, 0], @@ -17,16 +17,16 @@ var map = new Map({ }) }); -var labelStyle = new Style({ +const labelStyle = new Style({ geometry: function(feature) { - var geometry = feature.getGeometry(); + let geometry = feature.getGeometry(); if (geometry.getType() == 'MultiPolygon') { // Only render label for the widest polygon of a multipolygon - var polygons = geometry.getPolygons(); - var widest = 0; - for (var i = 0, ii = polygons.length; i < ii; ++i) { - var polygon = polygons[i]; - var width = _ol_extent_.getWidth(polygon.getExtent()); + const polygons = geometry.getPolygons(); + let widest = 0; + for (let i = 0, ii = polygons.length; i < ii; ++i) { + const polygon = polygons[i]; + const width = _ol_extent_.getWidth(polygon.getExtent()); if (width > widest) { widest = width; geometry = polygon; @@ -47,7 +47,7 @@ var labelStyle = new Style({ }) }) }); -var countryStyle = new Style({ +const countryStyle = new Style({ fill: new Fill({ color: 'rgba(255, 255, 255, 0.6)' }), @@ -56,9 +56,9 @@ var countryStyle = new Style({ width: 1 }) }); -var style = [countryStyle, labelStyle]; +const style = [countryStyle, labelStyle]; -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: new VectorSource({ url: 'data/geojson/countries.geojson', format: new GeoJSON() diff --git a/examples/vector-labels.js b/examples/vector-labels.js index 9b1858563f..07e09350de 100644 --- a/examples/vector-labels.js +++ b/examples/vector-labels.js @@ -11,9 +11,9 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; import Text from '../src/ol/style/Text.js'; -var openSansAdded = false; +let openSansAdded = false; -var myDom = { +const myDom = { points: { text: document.getElementById('points-text'), align: document.getElementById('points-align'), @@ -67,10 +67,10 @@ var myDom = { } }; -var getText = function(feature, resolution, dom) { - var type = dom.text.value; - var maxResolution = dom.maxreso.value; - var text = feature.get('name'); +const getText = function(feature, resolution, dom) { + const type = dom.text.value; + const maxResolution = dom.maxreso.value; + let text = feature.get('name'); if (resolution > maxResolution) { text = ''; @@ -86,28 +86,28 @@ var getText = function(feature, resolution, dom) { }; -var createTextStyle = function(feature, resolution, dom) { - var align = dom.align.value; - var baseline = dom.baseline.value; - var size = dom.size.value; - var offsetX = parseInt(dom.offsetX.value, 10); - var offsetY = parseInt(dom.offsetY.value, 10); - var weight = dom.weight.value; - var placement = dom.placement ? dom.placement.value : undefined; - var maxAngle = dom.maxangle ? parseFloat(dom.maxangle.value) : undefined; - var overflow = dom.overflow ? (dom.overflow.value == 'true') : undefined; - var rotation = parseFloat(dom.rotation.value); +const createTextStyle = function(feature, resolution, dom) { + const align = dom.align.value; + const baseline = dom.baseline.value; + const size = dom.size.value; + const offsetX = parseInt(dom.offsetX.value, 10); + const offsetY = parseInt(dom.offsetY.value, 10); + const weight = dom.weight.value; + const placement = dom.placement ? dom.placement.value : undefined; + const maxAngle = dom.maxangle ? parseFloat(dom.maxangle.value) : undefined; + const overflow = dom.overflow ? (dom.overflow.value == 'true') : undefined; + const rotation = parseFloat(dom.rotation.value); if (dom.font.value == '\'Open Sans\'' && !openSansAdded) { - var openSans = document.createElement('link'); + const openSans = document.createElement('link'); openSans.href = 'https://fonts.googleapis.com/css?family=Open+Sans'; openSans.rel = 'stylesheet'; document.getElementsByTagName('head')[0].appendChild(openSans); openSansAdded = true; } - var font = weight + ' ' + size + ' ' + dom.font.value; - var fillColor = dom.color.value; - var outlineColor = dom.outline.value; - var outlineWidth = parseInt(dom.outlineWidth.value, 10); + const font = weight + ' ' + size + ' ' + dom.font.value; + const fillColor = dom.color.value; + const outlineColor = dom.outline.value; + const outlineWidth = parseInt(dom.outlineWidth.value, 10); return new Text({ textAlign: align == '' ? undefined : align, @@ -140,7 +140,7 @@ function polygonStyleFunction(feature, resolution) { }); } -var vectorPolygons = new VectorLayer({ +const vectorPolygons = new VectorLayer({ source: new VectorSource({ url: 'data/geojson/polygon-samples.geojson', format: new GeoJSON() @@ -160,7 +160,7 @@ function lineStyleFunction(feature, resolution) { }); } -var vectorLines = new VectorLayer({ +const vectorLines = new VectorLayer({ source: new VectorSource({ url: 'data/geojson/line-samples.geojson', format: new GeoJSON() @@ -181,7 +181,7 @@ function pointStyleFunction(feature, resolution) { }); } -var vectorPoints = new VectorLayer({ +const vectorPoints = new VectorLayer({ source: new VectorSource({ url: 'data/geojson/point-samples.geojson', format: new GeoJSON() @@ -189,7 +189,7 @@ var vectorPoints = new VectorLayer({ style: pointStyleFunction }); -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM() @@ -206,19 +206,19 @@ var map = new Map({ }); document.getElementById('refresh-points') - .addEventListener('click', function() { - vectorPoints.setStyle(pointStyleFunction); - }); + .addEventListener('click', function() { + vectorPoints.setStyle(pointStyleFunction); + }); document.getElementById('refresh-lines') - .addEventListener('click', function() { - vectorLines.setStyle(lineStyleFunction); - }); + .addEventListener('click', function() { + vectorLines.setStyle(lineStyleFunction); + }); document.getElementById('refresh-polygons') - .addEventListener('click', function() { - vectorPolygons.setStyle(polygonStyleFunction); - }); + .addEventListener('click', function() { + vectorPolygons.setStyle(polygonStyleFunction); + }); /** @@ -234,18 +234,18 @@ String.prototype.trunc = String.prototype.trunc || // http://stackoverflow.com/questions/14484787/wrap-text-in-javascript function stringDivider(str, width, spaceReplacer) { if (str.length > width) { - var p = width; + let p = width; while (p > 0 && (str[p] != ' ' && str[p] != '-')) { p--; } if (p > 0) { - var left; + let left; if (str.substring(p, p + 1) == '-') { left = str.substring(0, p + 1); } else { left = str.substring(0, p); } - var right = str.substring(p + 1); + const right = str.substring(p + 1); return left + spaceReplacer + stringDivider(right, width, spaceReplacer); } } diff --git a/examples/vector-layer.js b/examples/vector-layer.js index 66b9b8bab2..b942d86873 100644 --- a/examples/vector-layer.js +++ b/examples/vector-layer.js @@ -9,7 +9,7 @@ import Style from '../src/ol/style/Style.js'; import Text from '../src/ol/style/Text.js'; -var style = new Style({ +const style = new Style({ fill: new Fill({ color: 'rgba(255, 255, 255, 0.6)' }), @@ -29,7 +29,7 @@ var style = new Style({ }) }); -var vectorLayer = new VectorLayer({ +const vectorLayer = new VectorLayer({ source: new VectorSource({ url: 'data/geojson/countries.geojson', format: new GeoJSON() @@ -40,7 +40,7 @@ var vectorLayer = new VectorLayer({ } }); -var map = new Map({ +const map = new Map({ layers: [vectorLayer], target: 'map', view: new View({ @@ -49,7 +49,7 @@ var map = new Map({ }) }); -var highlightStyle = new Style({ +const highlightStyle = new Style({ stroke: new Stroke({ color: '#f00', width: 1 @@ -69,7 +69,7 @@ var highlightStyle = new Style({ }) }); -var featureOverlay = new VectorLayer({ +const featureOverlay = new VectorLayer({ source: new VectorSource(), map: map, style: function(feature) { @@ -78,14 +78,14 @@ var featureOverlay = new VectorLayer({ } }); -var highlight; -var displayFeatureInfo = function(pixel) { +let highlight; +const displayFeatureInfo = function(pixel) { - var feature = map.forEachFeatureAtPixel(pixel, function(feature) { + const feature = map.forEachFeatureAtPixel(pixel, function(feature) { return feature; }); - var info = document.getElementById('info'); + const info = document.getElementById('info'); if (feature) { info.innerHTML = feature.getId() + ': ' + feature.get('name'); } else { @@ -108,7 +108,7 @@ map.on('pointermove', function(evt) { if (evt.dragging) { return; } - var pixel = map.getEventPixel(evt.originalEvent); + const pixel = map.getEventPixel(evt.originalEvent); displayFeatureInfo(pixel); }); diff --git a/examples/vector-osm.js b/examples/vector-osm.js index 2026eee098..c4669f721f 100644 --- a/examples/vector-osm.js +++ b/examples/vector-osm.js @@ -13,9 +13,9 @@ import Fill from '../src/ol/style/Fill.js'; import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var map; +let map = null; -var styles = { +const styles = { 'amenity': { 'parking': new Style({ stroke: new Stroke({ @@ -77,19 +77,19 @@ var styles = { } }; -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ format: new OSMXML(), loader: function(extent, resolution, projection) { - var epsg4326Extent = transformExtent(extent, projection, 'EPSG:4326'); - var client = new XMLHttpRequest(); + const epsg4326Extent = transformExtent(extent, projection, 'EPSG:4326'); + const client = new XMLHttpRequest(); client.open('POST', 'https://overpass-api.de/api/interpreter'); client.addEventListener('load', function() { - var features = new OSMXML().readFeatures(client.responseText, { + const features = new OSMXML().readFeatures(client.responseText, { featureProjection: map.getView().getProjection() }); vectorSource.addFeatures(features); }); - var query = '(node(' + + const query = '(node(' + epsg4326Extent[1] + ',' + epsg4326Extent[0] + ',' + epsg4326Extent[3] + ',' + epsg4326Extent[2] + ');rel(bn)->.foo;way(bn);node(w)->.foo;rel(bw););out meta;'; @@ -98,13 +98,13 @@ var vectorSource = new VectorSource({ strategy: _ol_loadingstrategy_.bbox }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: vectorSource, style: function(feature) { - for (var key in styles) { - var value = feature.get(key); + for (const key in styles) { + const value = feature.get(key); if (value !== undefined) { - for (var regexp in styles[key]) { + for (const regexp in styles[key]) { if (new RegExp(regexp).test(value)) { return styles[key][regexp]; } @@ -115,7 +115,7 @@ var vector = new VectorLayer({ } }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new BingMaps({ imagerySet: 'Aerial', key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' diff --git a/examples/vector-tile-info.js b/examples/vector-tile-info.js index 01fff8070c..b117a1519e 100644 --- a/examples/vector-tile-info.js +++ b/examples/vector-tile-info.js @@ -4,7 +4,7 @@ import MVT from '../src/ol/format/MVT.js'; import VectorTileLayer from '../src/ol/layer/VectorTile.js'; import VectorTileSource from '../src/ol/source/VectorTile.js'; -var map = new Map({ +const map = new Map({ target: 'map', view: new View({ center: [0, 0], @@ -20,15 +20,15 @@ var map = new Map({ map.on('pointermove', showInfo); -var info = document.getElementById('info'); +const info = document.getElementById('info'); function showInfo(event) { - var features = map.getFeaturesAtPixel(event.pixel); + const features = map.getFeaturesAtPixel(event.pixel); if (!features) { info.innerText = ''; info.style.opacity = 0; return; } - var properties = features[0].getProperties(); + const properties = features[0].getProperties(); info.innerText = JSON.stringify(properties, null, 2); info.style.opacity = 1; } diff --git a/examples/vector-wfs-getfeature.js b/examples/vector-wfs-getfeature.js index 9b8b530f57..81921ca813 100644 --- a/examples/vector-wfs-getfeature.js +++ b/examples/vector-wfs-getfeature.js @@ -11,8 +11,8 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var vectorSource = new VectorSource(); -var vector = new VectorLayer({ +const vectorSource = new VectorSource(); +const vector = new VectorLayer({ source: vectorSource, style: new Style({ stroke: new Stroke({ @@ -22,14 +22,14 @@ var vector = new VectorLayer({ }) }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new BingMaps({ imagerySet: 'Aerial', key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: document.getElementById('map'), view: new View({ @@ -40,15 +40,15 @@ var map = new Map({ }); // generate a GetFeature request -var featureRequest = new WFS().writeGetFeature({ +const featureRequest = new WFS().writeGetFeature({ srsName: 'EPSG:3857', featureNS: 'http://openstreemap.org', featurePrefix: 'osm', featureTypes: ['water_areas'], outputFormat: 'application/json', filter: _ol_format_filter_.and( - _ol_format_filter_.like('name', 'Mississippi*'), - _ol_format_filter_.equalTo('waterway', 'riverbank') + _ol_format_filter_.like('name', 'Mississippi*'), + _ol_format_filter_.equalTo('waterway', 'riverbank') ) }); @@ -59,7 +59,7 @@ fetch('https://ahocevar.com/geoserver/wfs', { }).then(function(response) { return response.json(); }).then(function(json) { - var features = new GeoJSON().readFeatures(json); + const features = new GeoJSON().readFeatures(json); vectorSource.addFeatures(features); map.getView().fit(vectorSource.getExtent()); }); diff --git a/examples/vector-wfs.js b/examples/vector-wfs.js index 59275be629..1dd7f5bbb4 100644 --- a/examples/vector-wfs.js +++ b/examples/vector-wfs.js @@ -10,7 +10,7 @@ import Stroke from '../src/ol/style/Stroke.js'; import Style from '../src/ol/style/Style.js'; -var vectorSource = new VectorSource({ +const vectorSource = new VectorSource({ format: new GeoJSON(), url: function(extent) { return 'https://ahocevar.com/geoserver/wfs?service=WFS&' + @@ -22,7 +22,7 @@ var vectorSource = new VectorSource({ }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: vectorSource, style: new Style({ stroke: new Stroke({ @@ -32,14 +32,14 @@ var vector = new VectorLayer({ }) }); -var raster = new TileLayer({ +const raster = new TileLayer({ source: new BingMaps({ imagerySet: 'Aerial', key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: document.getElementById('map'), view: new View({ diff --git a/examples/webpack/config.js b/examples/webpack/config.js index 5fe6dcf727..2a8d1d4ee9 100644 --- a/examples/webpack/config.js +++ b/examples/webpack/config.js @@ -9,8 +9,8 @@ const webpack = require('webpack'); const src = path.join(__dirname, '..'); const examples = fs.readdirSync(src) - .filter(name => /^(?!index).*\.html$/.test(name)) - .map(name => name.replace(/\.html$/, '')); + .filter(name => /^(?!index).*\.html$/.test(name)) + .map(name => name.replace(/\.html$/, '')); const entry = {}; examples.forEach(example => { @@ -49,7 +49,7 @@ const main = { const dev = { plugins: [ new webpack.EnvironmentPlugin( - Object.assign({NODE_ENV: 'development'}, process.env) + Object.assign({NODE_ENV: 'development'}, process.env) ) ] }; @@ -58,7 +58,7 @@ const dev = { const prod = { plugins: [ new webpack.EnvironmentPlugin( - Object.assign({NODE_ENV: 'production'}, process.env) + Object.assign({NODE_ENV: 'production'}, process.env) ), new MinifyPlugin() ] diff --git a/examples/webpack/example-builder.js b/examples/webpack/example-builder.js index 49b2b23f0b..398c6483a2 100644 --- a/examples/webpack/example-builder.js +++ b/examples/webpack/example-builder.js @@ -37,7 +37,7 @@ function createWordIndex(exampleData) { if (Array.isArray(text)) { text = text.join(' '); } - let words = text ? text.split(/\W+/) : []; + const words = text ? text.split(/\W+/) : []; words.forEach(word => { if (word) { word = word.toLowerCase(); @@ -79,7 +79,7 @@ function ExampleBuilder(config) { ExampleBuilder.prototype.apply = function(compiler) { compiler.plugin('emit', async (compilation, callback) => { const chunks = compilation.getStats().toJson().chunks - .filter(chunk => chunk.names[0] !== this.common); + .filter(chunk => chunk.names[0] !== this.common); const exampleData = []; const promises = chunks.map(async chunk => { diff --git a/examples/wkt.js b/examples/wkt.js index 2a90fd956d..72023313f1 100644 --- a/examples/wkt.js +++ b/examples/wkt.js @@ -6,28 +6,28 @@ import VectorLayer from '../src/ol/layer/Vector.js'; import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; -var raster = new TileLayer({ +const raster = new TileLayer({ source: new OSM() }); -var wkt = 'POLYGON((10.689 -25.092, 34.595 ' + +const wkt = 'POLYGON((10.689 -25.092, 34.595 ' + '-20.170, 38.814 -35.639, 13.502 ' + '-39.155, 10.689 -25.092))'; -var format = new WKT(); +const format = new WKT(); -var feature = format.readFeature(wkt, { +const feature = format.readFeature(wkt, { dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' }); -var vector = new VectorLayer({ +const vector = new VectorLayer({ source: new VectorSource({ features: [feature] }) }); -var map = new Map({ +const map = new Map({ layers: [raster, vector], target: 'map', view: new View({ diff --git a/examples/wms-capabilities.js b/examples/wms-capabilities.js index 53ab1cafc8..22ff6ab91c 100644 --- a/examples/wms-capabilities.js +++ b/examples/wms-capabilities.js @@ -1,10 +1,10 @@ import WMSCapabilities from '../src/ol/format/WMSCapabilities.js'; -var parser = new WMSCapabilities(); +const parser = new WMSCapabilities(); fetch('data/ogcsample.xml').then(function(response) { return response.text(); }).then(function(text) { - var result = parser.read(text); + const result = parser.read(text); document.getElementById('log').innerText = JSON.stringify(result, null, 2); }); diff --git a/examples/wms-custom-proj.js b/examples/wms-custom-proj.js index 918b165547..80bf4e5cc2 100644 --- a/examples/wms-custom-proj.js +++ b/examples/wms-custom-proj.js @@ -13,7 +13,7 @@ import TileWMS from '../src/ol/source/TileWMS.js'; // ol.proj.addProjection to make it available to the library for lookup by its // code. -var projection = new Projection({ +const projection = new Projection({ code: 'EPSG:21781', // The extent is used to determine zoom level 0. Recommended values for a // projection's validity extent can be found at https://epsg.io/. @@ -27,21 +27,21 @@ addProjection(projection); // for setting the view's initial center (see below). addCoordinateTransforms('EPSG:4326', projection, - function(coordinate) { - return [ - WGStoCHy(coordinate[1], coordinate[0]), - WGStoCHx(coordinate[1], coordinate[0]) - ]; - }, - function(coordinate) { - return [ - CHtoWGSlng(coordinate[0], coordinate[1]), - CHtoWGSlat(coordinate[0], coordinate[1]) - ]; - }); + function(coordinate) { + return [ + WGStoCHy(coordinate[1], coordinate[0]), + WGStoCHx(coordinate[1], coordinate[0]) + ]; + }, + function(coordinate) { + return [ + CHtoWGSlng(coordinate[0], coordinate[1]), + CHtoWGSlat(coordinate[0], coordinate[1]) + ]; + }); -var extent = [420000, 30000, 900000, 350000]; -var layers = [ +const extent = [420000, 30000, 900000, 350000]; +const layers = [ new TileLayer({ extent: extent, source: new TileWMS({ @@ -69,7 +69,7 @@ var layers = [ }) ]; -var map = new Map({ +const map = new Map({ controls: defaultControls().extend([ new ScaleLine({ units: 'metric' @@ -103,11 +103,11 @@ function WGStoCHy(lat, lng) { lng = DEGtoSEC(lng); // Axiliary values (% Bern) - var lat_aux = (lat - 169028.66) / 10000; - var lng_aux = (lng - 26782.5) / 10000; + const lat_aux = (lat - 169028.66) / 10000; + const lng_aux = (lng - 26782.5) / 10000; // Process Y - var y = 600072.37 + + const y = 600072.37 + 211455.93 * lng_aux - 10938.51 * lng_aux * lat_aux - 0.36 * lng_aux * Math.pow(lat_aux, 2) - @@ -128,11 +128,11 @@ function WGStoCHx(lat, lng) { lng = DEGtoSEC(lng); // Axiliary values (% Bern) - var lat_aux = (lat - 169028.66) / 10000; - var lng_aux = (lng - 26782.5) / 10000; + const lat_aux = (lat - 169028.66) / 10000; + const lng_aux = (lng - 26782.5) / 10000; // Process X - var x = 200147.07 + + const x = 200147.07 + 308807.95 * lat_aux + 3745.25 * Math.pow(lng_aux, 2) + 76.63 * Math.pow(lat_aux, 2) - @@ -149,11 +149,11 @@ function CHtoWGSlat(y, x) { // Converts militar to civil and to unit = 1000km // Axiliary values (% Bern) - var y_aux = (y - 600000) / 1000000; - var x_aux = (x - 200000) / 1000000; + const y_aux = (y - 600000) / 1000000; + const x_aux = (x - 200000) / 1000000; // Process lat - var lat = 16.9023892 + + let lat = 16.9023892 + 3.238272 * x_aux - 0.270978 * Math.pow(y_aux, 2) - 0.002528 * Math.pow(x_aux, 2) - @@ -172,11 +172,11 @@ function CHtoWGSlng(y, x) { // Converts militar to civil and to unit = 1000km // Axiliary values (% Bern) - var y_aux = (y - 600000) / 1000000; - var x_aux = (x - 200000) / 1000000; + const y_aux = (y - 600000) / 1000000; + const x_aux = (x - 200000) / 1000000; // Process long - var lng = 2.6779094 + + let lng = 2.6779094 + 4.728982 * y_aux + 0.791484 * y_aux * x_aux + 0.1306 * y_aux * Math.pow(x_aux, 2) - @@ -194,9 +194,9 @@ function CHtoWGSlng(y, x) { function DECtoSEX(angle) { // Extract DMS - var deg = parseInt(angle, 10); - var min = parseInt((angle - deg) * 60, 10); - var sec = (((angle - deg) * 60) - min) * 60; + const deg = parseInt(angle, 10); + const min = parseInt((angle - deg) * 60, 10); + const sec = (((angle - deg) * 60) - min) * 60; // Result in degrees sex (dd.mmss) return deg + min / 100 + sec / 10000; @@ -207,12 +207,12 @@ function DECtoSEX(angle) { function DEGtoSEC(angle) { // Extract DMS - var deg = parseInt(angle, 10); - var min = parseInt((angle - deg) * 100, 10); - var sec = (((angle - deg) * 100) - min) * 100; + const deg = parseInt(angle, 10); + let min = parseInt((angle - deg) * 100, 10); + let sec = (((angle - deg) * 100) - min) * 100; // Avoid rounding problems with seconds=0 - var parts = String(angle).split('.'); + const parts = String(angle).split('.'); if (parts.length == 2 && parts[1].length == 2) { min = Number(parts[1]); sec = 0; diff --git a/examples/wms-custom-tilegrid-512x256.js b/examples/wms-custom-tilegrid-512x256.js index 304fc90b49..db334e5987 100644 --- a/examples/wms-custom-tilegrid-512x256.js +++ b/examples/wms-custom-tilegrid-512x256.js @@ -8,19 +8,19 @@ import TileWMS from '../src/ol/source/TileWMS.js'; import TileGrid from '../src/ol/tilegrid/TileGrid.js'; -var projExtent = getProjection('EPSG:3857').getExtent(); -var startResolution = _ol_extent_.getWidth(projExtent) / 256; -var resolutions = new Array(22); -for (var i = 0, ii = resolutions.length; i < ii; ++i) { +const projExtent = getProjection('EPSG:3857').getExtent(); +const startResolution = _ol_extent_.getWidth(projExtent) / 256; +const resolutions = new Array(22); +for (let i = 0, ii = resolutions.length; i < ii; ++i) { resolutions[i] = startResolution / Math.pow(2, i); } -var tileGrid = new TileGrid({ +const tileGrid = new TileGrid({ extent: [-13884991, 2870341, -7455066, 6338219], resolutions: resolutions, tileSize: [512, 256] }); -var layers = [ +const layers = [ new TileLayer({ source: new OSM() }), @@ -33,7 +33,7 @@ var layers = [ }) }) ]; -var map = new Map({ +const map = new Map({ layers: layers, target: 'map', view: new View({ diff --git a/examples/wms-image-custom-proj.js b/examples/wms-image-custom-proj.js index e01e64c903..680deb20a3 100644 --- a/examples/wms-image-custom-proj.js +++ b/examples/wms-image-custom-proj.js @@ -24,18 +24,18 @@ import proj4 from 'proj4'; // projection's validity extent can be found at https://epsg.io/. proj4.defs('EPSG:21781', - '+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 ' + + '+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 ' + '+x_0=600000 +y_0=200000 +ellps=bessel ' + '+towgs84=660.077,13.551,369.344,2.484,1.783,2.939,5.66 +units=m +no_defs'); register(proj4); -var projection = new Projection({ +const projection = new Projection({ code: 'EPSG:21781', extent: [485869.5728, 76443.1884, 837076.5648, 299941.7864] }); -var extent = [420000, 30000, 900000, 350000]; -var layers = [ +const extent = [420000, 30000, 900000, 350000]; +const layers = [ new ImageLayer({ extent: extent, source: new ImageWMS({ @@ -63,7 +63,7 @@ var layers = [ }) ]; -var map = new Map({ +const map = new Map({ controls: defaultControls().extend([ new ScaleLine() ]), diff --git a/examples/wms-image.js b/examples/wms-image.js index fab2683e10..fa5492c103 100644 --- a/examples/wms-image.js +++ b/examples/wms-image.js @@ -6,7 +6,7 @@ import ImageWMS from '../src/ol/source/ImageWMS.js'; import OSM from '../src/ol/source/OSM.js'; -var layers = [ +const layers = [ new TileLayer({ source: new OSM() }), @@ -20,7 +20,7 @@ var layers = [ }) }) ]; -var map = new Map({ +const map = new Map({ layers: layers, target: 'map', view: new View({ diff --git a/examples/wms-no-proj.js b/examples/wms-no-proj.js index 2acc62144e..c0afc8834e 100644 --- a/examples/wms-no-proj.js +++ b/examples/wms-no-proj.js @@ -7,7 +7,7 @@ import ImageWMS from '../src/ol/source/ImageWMS.js'; import TileWMS from '../src/ol/source/TileWMS.js'; -var layers = [ +const layers = [ new TileLayer({ source: new TileWMS({ attributions: '© ' }); -var ign = new TileLayer({ +const ign = new TileLayer({ source: ign_source }); diff --git a/examples/wmts-layer-from-capabilities.js b/examples/wmts-layer-from-capabilities.js index 8756778b77..bd0ec2467c 100644 --- a/examples/wmts-layer-from-capabilities.js +++ b/examples/wmts-layer-from-capabilities.js @@ -5,14 +5,14 @@ import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; import WMTS from '../src/ol/source/WMTS.js'; -var parser = new _ol_format_WMTSCapabilities_(); -var map; +const parser = new _ol_format_WMTSCapabilities_(); +let map; fetch('data/WMTSCapabilities.xml').then(function(response) { return response.text(); }).then(function(text) { - var result = parser.read(text); - var options = WMTS.optionsFromCapabilities(result, { + const result = parser.read(text); + const options = WMTS.optionsFromCapabilities(result, { layer: 'layer-7328', matrixSet: 'EPSG:3857' }); diff --git a/examples/wmts.js b/examples/wmts.js index 228c26c958..1c017ee50b 100644 --- a/examples/wmts.js +++ b/examples/wmts.js @@ -9,18 +9,18 @@ import WMTS from '../src/ol/source/WMTS.js'; import WMTSTileGrid from '../src/ol/tilegrid/WMTS.js'; -var projection = getProjection('EPSG:3857'); -var projectionExtent = projection.getExtent(); -var size = _ol_extent_.getWidth(projectionExtent) / 256; -var resolutions = new Array(14); -var matrixIds = new Array(14); -for (var z = 0; z < 14; ++z) { +const projection = getProjection('EPSG:3857'); +const projectionExtent = projection.getExtent(); +const size = _ol_extent_.getWidth(projectionExtent) / 256; +const resolutions = new Array(14); +const matrixIds = new Array(14); +for (let z = 0; z < 14; ++z) { // generate resolutions and matrixIds arrays for this WMTS resolutions[z] = size / Math.pow(2, z); matrixIds[z] = z; } -var map = new Map({ +const map = new Map({ layers: [ new TileLayer({ source: new OSM(), diff --git a/examples/xyz-esri-4326-512.js b/examples/xyz-esri-4326-512.js index 47d329173c..4d6e5ab5da 100644 --- a/examples/xyz-esri-4326-512.js +++ b/examples/xyz-esri-4326-512.js @@ -4,12 +4,12 @@ import TileLayer from '../src/ol/layer/Tile.js'; import XYZ from '../src/ol/source/XYZ.js'; // The tile size supported by the ArcGIS tile service. -var tileSize = 512; +const tileSize = 512; -var urlTemplate = 'https://services.arcgisonline.com/arcgis/rest/services/' + +const urlTemplate = 'https://services.arcgisonline.com/arcgis/rest/services/' + 'ESRI_Imagery_World_2D/MapServer/tile/{z}/{y}/{x}'; -var map = new Map({ +const map = new Map({ target: 'map', layers: [ new TileLayer({ @@ -20,8 +20,8 @@ var map = new Map({ tileSize: tileSize, tileUrlFunction: function(tileCoord) { return urlTemplate.replace('{z}', (tileCoord[0] - 1).toString()) - .replace('{x}', tileCoord[1].toString()) - .replace('{y}', (-tileCoord[2] - 1).toString()); + .replace('{x}', tileCoord[1].toString()) + .replace('{y}', (-tileCoord[2] - 1).toString()); }, wrapX: true }) diff --git a/examples/xyz-esri.js b/examples/xyz-esri.js index 653ef9b102..3e2ed8989d 100644 --- a/examples/xyz-esri.js +++ b/examples/xyz-esri.js @@ -5,7 +5,7 @@ import {fromLonLat} from '../src/ol/proj.js'; import XYZ from '../src/ol/source/XYZ.js'; -var map = new Map({ +const map = new Map({ target: 'map', layers: [ new TileLayer({ diff --git a/examples/xyz-retina.js b/examples/xyz-retina.js index 2cf03502b4..da93d9b099 100644 --- a/examples/xyz-retina.js +++ b/examples/xyz-retina.js @@ -5,11 +5,11 @@ import {transform, transformExtent} from '../src/ol/proj.js'; import OSM from '../src/ol/source/OSM.js'; import XYZ from '../src/ol/source/XYZ.js'; -var mapMinZoom = 1; -var mapMaxZoom = 15; -var mapExtent = [-112.261791, 35.983744, -112.113981, 36.132062]; +const mapMinZoom = 1; +const mapMaxZoom = 15; +const mapExtent = [-112.261791, 35.983744, -112.113981, 36.132062]; -var map = new Map({ +const map = new Map({ target: 'map', layers: [ new TileLayer({ @@ -30,7 +30,7 @@ var map = new Map({ view: new View({ projection: 'EPSG:3857', center: transform([-112.18688965, 36.057944835], - 'EPSG:4326', 'EPSG:3857'), + 'EPSG:4326', 'EPSG:3857'), zoom: 12 }) }); diff --git a/examples/xyz.js b/examples/xyz.js index 2f06344a5a..d687f69685 100644 --- a/examples/xyz.js +++ b/examples/xyz.js @@ -4,7 +4,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import XYZ from '../src/ol/source/XYZ.js'; -var map = new Map({ +const map = new Map({ target: 'map', layers: [ new TileLayer({ diff --git a/examples/zoom-constrained.js b/examples/zoom-constrained.js index bac04ed040..fbb628ed83 100644 --- a/examples/zoom-constrained.js +++ b/examples/zoom-constrained.js @@ -4,7 +4,7 @@ import TileLayer from '../src/ol/layer/Tile.js'; import BingMaps from '../src/ol/source/BingMaps.js'; -var map = new Map({ +const map = new Map({ target: 'map', layers: [ new TileLayer({ diff --git a/examples/zoomify.js b/examples/zoomify.js index 5b2589135e..5afb3d1484 100644 --- a/examples/zoomify.js +++ b/examples/zoomify.js @@ -3,14 +3,14 @@ import View from '../src/ol/View.js'; import TileLayer from '../src/ol/layer/Tile.js'; import Zoomify from '../src/ol/source/Zoomify.js'; -var imgWidth = 9911; -var imgHeight = 6100; +const imgWidth = 9911; +const imgHeight = 6100; -var zoomifyUrl = 'http://vips.vtech.fr/cgi-bin/iipsrv.fcgi?zoomify=' + +const zoomifyUrl = 'http://vips.vtech.fr/cgi-bin/iipsrv.fcgi?zoomify=' + '/mnt/MD1/AD00/plan_CHU-4HD-01/FOND.TIF/'; -var iipUrl = 'http://vips.vtech.fr/cgi-bin/iipsrv.fcgi?FIF=' + '/mnt/MD1/AD00/plan_CHU-4HD-01/FOND.TIF' + '&JTL={z},{tileIndex}'; +const iipUrl = 'http://vips.vtech.fr/cgi-bin/iipsrv.fcgi?FIF=' + '/mnt/MD1/AD00/plan_CHU-4HD-01/FOND.TIF' + '&JTL={z},{tileIndex}'; -var layer = new TileLayer({ +const layer = new TileLayer({ source: new Zoomify({ url: zoomifyUrl, size: [imgWidth, imgHeight], @@ -18,9 +18,9 @@ var layer = new TileLayer({ }) }); -var extent = [0, -imgHeight, imgWidth, 0]; +const extent = [0, -imgHeight, imgWidth, 0]; -var map = new Map({ +const map = new Map({ layers: [layer], target: 'map', view: new View({ @@ -32,9 +32,9 @@ var map = new Map({ }); map.getView().fit(extent); -var control = document.getElementById('zoomifyProtocol'); +const control = document.getElementById('zoomifyProtocol'); control.addEventListener('change', function(event) { - var value = event.currentTarget.value; + const value = event.currentTarget.value; if (value === 'iip') { layer.setSource(new Zoomify({ url: iipUrl, diff --git a/examples/zoomslider.js b/examples/zoomslider.js index 4de9afab22..0bfe6ded26 100644 --- a/examples/zoomslider.js +++ b/examples/zoomslider.js @@ -11,14 +11,12 @@ import OSM from '../src/ol/source/OSM.js'; * @param {string} divId The id of the div for the map. * @return {ol.PluggableMap} The ol.Map instance. */ -var createMap = function(divId) { - var source, layer, map, zoomslider; - - source = new OSM(); - layer = new TileLayer({ +function createMap(divId) { + const source = new OSM(); + const layer = new TileLayer({ source: source }); - map = new Map({ + const map = new Map({ layers: [layer], target: divId, view: new View({ @@ -26,11 +24,11 @@ var createMap = function(divId) { zoom: 2 }) }); - zoomslider = new ZoomSlider(); + const zoomslider = new ZoomSlider(); map.addControl(zoomslider); return map; -}; +} -var map1 = createMap('map1'); -var map2 = createMap('map2'); -var map3 = createMap('map3'); +const map1 = createMap('map1'); +const map2 = createMap('map2'); +const map3 = createMap('map3'); diff --git a/package.json b/package.json index 5b15127411..8ee9c99bae 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,7 @@ "copy-webpack-plugin": "^4.0.1", "coveralls": "3.0.0", "eslint": "4.15.0", - "eslint-config-openlayers": "7.0.0", + "eslint-config-openlayers": "^9.0.0", "expect.js": "0.3.1", "front-matter": "^2.1.2", "fs-extra": "5.0.0", @@ -74,42 +74,6 @@ "webpack-merge": "4.1.1" }, "eslintConfig": { - "extends": "openlayers", - "parserOptions": { - "sourceType": "module" - }, - "globals": { - "ArrayBuffer": false, - "Float32Array": false, - "Uint16Array": false, - "Uint32Array": false, - "Uint8Array": false, - "Uint8ClampedArray": false, - "ol": false, - "proj4": false - }, - "rules": { - "no-constant-condition": 0, - "indent": [ - 2, - 2, - { - "VariableDeclarator": 2, - "SwitchCase": 1, - "MemberExpression": 2, - "FunctionDeclaration": { - "parameters": 2, - "body": 1 - }, - "FunctionExpression": { - "parameters": 2, - "body": 1 - }, - "CallExpression": { - "arguments": 2 - } - } - ] - } + "extends": "openlayers" } } diff --git a/src/ol/AssertionError.js b/src/ol/AssertionError.js index 6b1bcc4ac3..1f8b3704fd 100644 --- a/src/ol/AssertionError.js +++ b/src/ol/AssertionError.js @@ -12,9 +12,9 @@ import {VERSION, inherits} from './index.js'; * @implements {oli.AssertionError} * @param {number} code Error code. */ -var AssertionError = function(code) { +const AssertionError = function(code) { - var path = VERSION ? VERSION.split('-')[0] : 'latest'; + const path = VERSION ? VERSION.split('-')[0] : 'latest'; /** * @type {string} diff --git a/src/ol/CanvasMap.js b/src/ol/CanvasMap.js index 4360fc1931..678fe549ba 100644 --- a/src/ol/CanvasMap.js +++ b/src/ol/CanvasMap.js @@ -72,7 +72,7 @@ registerMultiple(PluginType.LAYER_RENDERER, [ * @fires ol.render.Event#precompose * @api */ -var _ol_CanvasMap_ = function(options) { +const _ol_CanvasMap_ = function(options) { options = _ol_obj_.assign({}, options); delete options.renderer; if (!options.controls) { diff --git a/src/ol/CenterConstraint.js b/src/ol/CenterConstraint.js index 2b8b67a0b0..a9201fb59e 100644 --- a/src/ol/CenterConstraint.js +++ b/src/ol/CenterConstraint.js @@ -2,7 +2,7 @@ * @module ol/CenterConstraint */ import {clamp} from './math.js'; -var CenterConstraint = {}; +const CenterConstraint = {}; /** diff --git a/src/ol/Collection.js b/src/ol/Collection.js index c39d984504..9a4eba9533 100644 --- a/src/ol/Collection.js +++ b/src/ol/Collection.js @@ -12,7 +12,7 @@ import Event from './events/Event.js'; * @enum {string} * @private */ -var Property = { +const Property = { LENGTH: 'length' }; @@ -20,7 +20,7 @@ var Property = { /** * @typedef {{unique: (boolean|undefined)}} */ -export var CollectionOptions; +export let CollectionOptions; /** @@ -41,11 +41,11 @@ export var CollectionOptions; * @template T * @api */ -var Collection = function(opt_array, opt_options) { +const Collection = function(opt_array, opt_options) { BaseObject.call(this); - var options = opt_options || {}; + const options = opt_options || {}; /** * @private @@ -60,7 +60,7 @@ var Collection = function(opt_array, opt_options) { this.array_ = opt_array ? opt_array : []; if (this.unique_) { - for (var i = 0, ii = this.array_.length; i < ii; ++i) { + for (let i = 0, ii = this.array_.length; i < ii; ++i) { this.assertUnique_(this.array_[i], i); } } @@ -91,7 +91,7 @@ Collection.prototype.clear = function() { * @api */ Collection.prototype.extend = function(arr) { - var i, ii; + let i, ii; for (i = 0, ii = arr.length; i < ii; ++i) { this.push(arr[i]); } @@ -107,8 +107,8 @@ Collection.prototype.extend = function(arr) { * @api */ Collection.prototype.forEach = function(f) { - var array = this.array_; - for (var i = 0, ii = array.length; i < ii; ++i) { + const array = this.array_; + for (let i = 0, ii = array.length; i < ii; ++i) { f(array[i], i, array); } }; @@ -162,7 +162,7 @@ Collection.prototype.insertAt = function(index, elem) { this.array_.splice(index, 0, elem); this.updateLength_(); this.dispatchEvent( - new Collection.Event(CollectionEventType.ADD, elem)); + new Collection.Event(CollectionEventType.ADD, elem)); }; @@ -187,7 +187,7 @@ Collection.prototype.push = function(elem) { if (this.unique_) { this.assertUnique_(elem); } - var n = this.getLength(); + const n = this.getLength(); this.insertAt(n, elem); return this.getLength(); }; @@ -200,8 +200,8 @@ Collection.prototype.push = function(elem) { * @api */ Collection.prototype.remove = function(elem) { - var arr = this.array_; - var i, ii; + const arr = this.array_; + let i, ii; for (i = 0, ii = arr.length; i < ii; ++i) { if (arr[i] === elem) { return this.removeAt(i); @@ -219,11 +219,11 @@ Collection.prototype.remove = function(elem) { * @api */ Collection.prototype.removeAt = function(index) { - var prev = this.array_[index]; + const prev = this.array_[index]; this.array_.splice(index, 1); this.updateLength_(); this.dispatchEvent( - new Collection.Event(CollectionEventType.REMOVE, prev)); + new Collection.Event(CollectionEventType.REMOVE, prev)); return prev; }; @@ -235,19 +235,19 @@ Collection.prototype.removeAt = function(index) { * @api */ Collection.prototype.setAt = function(index, elem) { - var n = this.getLength(); + const n = this.getLength(); if (index < n) { if (this.unique_) { this.assertUnique_(elem, index); } - var prev = this.array_[index]; + const prev = this.array_[index]; this.array_[index] = elem; this.dispatchEvent( - new Collection.Event(CollectionEventType.REMOVE, prev)); + new Collection.Event(CollectionEventType.REMOVE, prev)); this.dispatchEvent( - new Collection.Event(CollectionEventType.ADD, elem)); + new Collection.Event(CollectionEventType.ADD, elem)); } else { - var j; + let j; for (j = n; j < index; ++j) { this.insertAt(j, undefined); } @@ -270,7 +270,7 @@ Collection.prototype.updateLength_ = function() { * @param {number=} opt_except Optional index to ignore. */ Collection.prototype.assertUnique_ = function(elem, opt_except) { - for (var i = 0, ii = this.array_.length; i < ii; ++i) { + for (let i = 0, ii = this.array_.length; i < ii; ++i) { if (this.array_[i] === elem && i !== opt_except) { throw new AssertionError(58); } diff --git a/src/ol/Disposable.js b/src/ol/Disposable.js index 3b6137c234..633e2017aa 100644 --- a/src/ol/Disposable.js +++ b/src/ol/Disposable.js @@ -7,7 +7,7 @@ import {nullFunction} from './index.js'; * Objects that need to clean up after themselves. * @constructor */ -var Disposable = function() {}; +const Disposable = function() {}; /** * The object has already been disposed. diff --git a/src/ol/Feature.js b/src/ol/Feature.js index 639aa36210..c771b15e34 100644 --- a/src/ol/Feature.js +++ b/src/ol/Feature.js @@ -54,7 +54,7 @@ import Style from './style/Style.js'; * include a Geometry associated with a `geometry` key. * @api */ -var Feature = function(opt_geometryOrProperties) { +const Feature = function(opt_geometryOrProperties) { BaseObject.call(this); @@ -91,17 +91,17 @@ var Feature = function(opt_geometryOrProperties) { this.geometryChangeKey_ = null; _ol_events_.listen( - this, BaseObject.getChangeEventType(this.geometryName_), - this.handleGeometryChanged_, this); + this, BaseObject.getChangeEventType(this.geometryName_), + this.handleGeometryChanged_, this); if (opt_geometryOrProperties !== undefined) { if (opt_geometryOrProperties instanceof Geometry || !opt_geometryOrProperties) { - var geometry = opt_geometryOrProperties; + const geometry = opt_geometryOrProperties; this.setGeometry(geometry); } else { /** @type {Object.} */ - var properties = opt_geometryOrProperties; + const properties = opt_geometryOrProperties; this.setProperties(properties); } } @@ -117,13 +117,13 @@ inherits(Feature, BaseObject); * @api */ Feature.prototype.clone = function() { - var clone = new Feature(this.getProperties()); + const clone = new Feature(this.getProperties()); clone.setGeometryName(this.getGeometryName()); - var geometry = this.getGeometry(); + const geometry = this.getGeometry(); if (geometry) { clone.setGeometry(geometry.clone()); } - var style = this.getStyle(); + const style = this.getStyle(); if (style) { clone.setStyle(style); } @@ -208,10 +208,10 @@ Feature.prototype.handleGeometryChanged_ = function() { _ol_events_.unlistenByKey(this.geometryChangeKey_); this.geometryChangeKey_ = null; } - var geometry = this.getGeometry(); + const geometry = this.getGeometry(); if (geometry) { this.geometryChangeKey_ = _ol_events_.listen(geometry, - EventType.CHANGE, this.handleGeometryChange_, this); + EventType.CHANGE, this.handleGeometryChange_, this); } this.changed(); }; @@ -270,12 +270,12 @@ Feature.prototype.setId = function(id) { */ Feature.prototype.setGeometryName = function(name) { _ol_events_.unlisten( - this, BaseObject.getChangeEventType(this.geometryName_), - this.handleGeometryChanged_, this); + this, BaseObject.getChangeEventType(this.geometryName_), + this.handleGeometryChanged_, this); this.geometryName_ = name; _ol_events_.listen( - this, BaseObject.getChangeEventType(this.geometryName_), - this.handleGeometryChanged_, this); + this, BaseObject.getChangeEventType(this.geometryName_), + this.handleGeometryChanged_, this); this.handleGeometryChanged_(); }; @@ -289,7 +289,7 @@ Feature.prototype.setGeometryName = function(name) { * @return {ol.FeatureStyleFunction} A style function. */ Feature.createStyleFunction = function(obj) { - var styleFunction; + let styleFunction; if (typeof obj === 'function') { if (obj.length == 2) { @@ -303,12 +303,12 @@ Feature.createStyleFunction = function(obj) { /** * @type {Array.} */ - var styles; + let styles; if (Array.isArray(obj)) { styles = obj; } else { assert(obj instanceof Style, - 41); // Expected an `ol.style.Style` or an array of `ol.style.Style` + 41); // Expected an `ol.style.Style` or an array of `ol.style.Style` styles = [obj]; } styleFunction = function() { diff --git a/src/ol/Geolocation.js b/src/ol/Geolocation.js index a111d5259c..1431514806 100644 --- a/src/ol/Geolocation.js +++ b/src/ol/Geolocation.js @@ -17,7 +17,7 @@ import {get as getProjection, getTransformFromProjections, identityTransform} fr * trackingOptions: (GeolocationPositionOptions|undefined), * projection: ol.ProjectionLike}} */ -export var GeolocationOptions; +export let GeolocationOptions; /** @@ -53,11 +53,11 @@ export var GeolocationOptions; * is reported in. * @api */ -var Geolocation = function(opt_options) { +const Geolocation = function(opt_options) { BaseObject.call(this); - var options = opt_options || {}; + const options = opt_options || {}; /** * The unprojected (EPSG:4326) device position. @@ -79,11 +79,11 @@ var Geolocation = function(opt_options) { this.watchId_ = undefined; _ol_events_.listen( - this, BaseObject.getChangeEventType(GeolocationProperty.PROJECTION), - this.handleProjectionChanged_, this); + this, BaseObject.getChangeEventType(GeolocationProperty.PROJECTION), + this.handleProjectionChanged_, this); _ol_events_.listen( - this, BaseObject.getChangeEventType(GeolocationProperty.TRACKING), - this.handleTrackingChanged_, this); + this, BaseObject.getChangeEventType(GeolocationProperty.TRACKING), + this.handleTrackingChanged_, this); if (options.projection !== undefined) { this.setProjection(options.projection); @@ -112,10 +112,10 @@ Geolocation.prototype.disposeInternal = function() { * @private */ Geolocation.prototype.handleProjectionChanged_ = function() { - var projection = this.getProjection(); + const projection = this.getProjection(); if (projection) { this.transform_ = getTransformFromProjections( - getProjection('EPSG:4326'), projection); + getProjection('EPSG:4326'), projection); if (this.position_) { this.set(GeolocationProperty.POSITION, this.transform_(this.position_)); } @@ -128,12 +128,12 @@ Geolocation.prototype.handleProjectionChanged_ = function() { */ Geolocation.prototype.handleTrackingChanged_ = function() { if (_ol_has_.GEOLOCATION) { - var tracking = this.getTracking(); + const tracking = this.getTracking(); if (tracking && this.watchId_ === undefined) { this.watchId_ = navigator.geolocation.watchPosition( - this.positionChange_.bind(this), - this.positionError_.bind(this), - this.getTrackingOptions()); + this.positionChange_.bind(this), + this.positionError_.bind(this), + this.getTrackingOptions()); } else if (!tracking && this.watchId_ !== undefined) { navigator.geolocation.clearWatch(this.watchId_); this.watchId_ = undefined; @@ -147,13 +147,13 @@ Geolocation.prototype.handleTrackingChanged_ = function() { * @param {GeolocationPosition} position position event. */ Geolocation.prototype.positionChange_ = function(position) { - var coords = position.coords; + const coords = position.coords; this.set(GeolocationProperty.ACCURACY, coords.accuracy); this.set(GeolocationProperty.ALTITUDE, - coords.altitude === null ? undefined : coords.altitude); + coords.altitude === null ? undefined : coords.altitude); this.set(GeolocationProperty.ALTITUDE_ACCURACY, - coords.altitudeAccuracy === null ? - undefined : coords.altitudeAccuracy); + coords.altitudeAccuracy === null ? + undefined : coords.altitudeAccuracy); this.set(GeolocationProperty.HEADING, coords.heading === null ? undefined : toRadians(coords.heading)); if (!this.position_) { @@ -162,11 +162,11 @@ Geolocation.prototype.positionChange_ = function(position) { this.position_[0] = coords.longitude; this.position_[1] = coords.latitude; } - var projectedPosition = this.transform_(this.position_); + const projectedPosition = this.transform_(this.position_); this.set(GeolocationProperty.POSITION, projectedPosition); this.set(GeolocationProperty.SPEED, - coords.speed === null ? undefined : coords.speed); - var geometry = circularPolygon(this.position_, coords.accuracy); + coords.speed === null ? undefined : coords.speed); + const geometry = circularPolygon(this.position_, coords.accuracy); geometry.applyTransform(this.transform_); this.set(GeolocationProperty.ACCURACY_GEOMETRY, geometry); this.changed(); diff --git a/src/ol/Graticule.js b/src/ol/Graticule.js index ff950a4095..0fe38b2e58 100644 --- a/src/ol/Graticule.js +++ b/src/ol/Graticule.js @@ -20,7 +20,7 @@ import Text from './style/Text.js'; * @private * @const */ -var DEFAULT_STROKE_STYLE = new Stroke({ +const DEFAULT_STROKE_STYLE = new Stroke({ color: 'rgba(0,0,0,0.2)' }); @@ -29,7 +29,7 @@ var DEFAULT_STROKE_STYLE = new Stroke({ * @type {Array.} * @private */ -var INTERVALS = [ +const INTERVALS = [ 90, 45, 30, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.01, 0.005, 0.002, 0.001 ]; @@ -47,7 +47,7 @@ var INTERVALS = [ * lonLabelStyle: (ol.style.Text|undefined), * latLabelStyle: (ol.style.Text|undefined)}} */ -export var GraticuleOptions; +export let GraticuleOptions; /** @@ -119,8 +119,8 @@ export var GraticuleOptions; * of the viewport. * @api */ -var Graticule = function(opt_options) { - var options = opt_options || {}; +const Graticule = function(opt_options) { + const options = opt_options || {}; /** * @type {ol.PluggableMap} @@ -244,7 +244,7 @@ var Graticule = function(opt_options) { this.parallelsLabels_ = null; if (options.showLabels == true) { - var degreesToString = _ol_coordinate_.degreesToStringHDMS; + const degreesToString = _ol_coordinate_.degreesToStringHDMS; /** * @type {null|function(number):string} @@ -331,11 +331,11 @@ var Graticule = function(opt_options) { * @private */ Graticule.prototype.addMeridian_ = function(lon, minLat, maxLat, squaredTolerance, extent, index) { - var lineString = this.getMeridian_(lon, minLat, maxLat, - squaredTolerance, index); + const lineString = this.getMeridian_(lon, minLat, maxLat, + squaredTolerance, index); if (intersects(lineString.getExtent(), extent)) { if (this.meridiansLabels_) { - var textPoint = this.getMeridianPoint_(lineString, extent, index); + const textPoint = this.getMeridianPoint_(lineString, extent, index); this.meridiansLabels_[index] = { geom: textPoint, text: this.lonLabelFormatter_(lon) @@ -354,14 +354,14 @@ Graticule.prototype.addMeridian_ = function(lon, minLat, maxLat, squaredToleranc * @private */ Graticule.prototype.getMeridianPoint_ = function(lineString, extent, index) { - var flatCoordinates = lineString.getFlatCoordinates(); - var clampedBottom = Math.max(extent[1], flatCoordinates[1]); - var clampedTop = Math.min(extent[3], flatCoordinates[flatCoordinates.length - 1]); - var lat = clamp( - extent[1] + Math.abs(extent[1] - extent[3]) * this.lonLabelPosition_, - clampedBottom, clampedTop); - var coordinate = [flatCoordinates[0], lat]; - var point = this.meridiansLabels_[index] !== undefined ? + const flatCoordinates = lineString.getFlatCoordinates(); + const clampedBottom = Math.max(extent[1], flatCoordinates[1]); + const clampedTop = Math.min(extent[3], flatCoordinates[flatCoordinates.length - 1]); + const lat = clamp( + extent[1] + Math.abs(extent[1] - extent[3]) * this.lonLabelPosition_, + clampedBottom, clampedTop); + const coordinate = [flatCoordinates[0], lat]; + const point = this.meridiansLabels_[index] !== undefined ? this.meridiansLabels_[index].geom : new Point(null); point.setCoordinates(coordinate); return point; @@ -379,11 +379,11 @@ Graticule.prototype.getMeridianPoint_ = function(lineString, extent, index) { * @private */ Graticule.prototype.addParallel_ = function(lat, minLon, maxLon, squaredTolerance, extent, index) { - var lineString = this.getParallel_(lat, minLon, maxLon, squaredTolerance, - index); + const lineString = this.getParallel_(lat, minLon, maxLon, squaredTolerance, + index); if (intersects(lineString.getExtent(), extent)) { if (this.parallelsLabels_) { - var textPoint = this.getParallelPoint_(lineString, extent, index); + const textPoint = this.getParallelPoint_(lineString, extent, index); this.parallelsLabels_[index] = { geom: textPoint, text: this.latLabelFormatter_(lat) @@ -403,14 +403,14 @@ Graticule.prototype.addParallel_ = function(lat, minLon, maxLon, squaredToleranc * @private */ Graticule.prototype.getParallelPoint_ = function(lineString, extent, index) { - var flatCoordinates = lineString.getFlatCoordinates(); - var clampedLeft = Math.max(extent[0], flatCoordinates[0]); - var clampedRight = Math.min(extent[2], flatCoordinates[flatCoordinates.length - 2]); - var lon = clamp( - extent[0] + Math.abs(extent[0] - extent[2]) * this.latLabelPosition_, - clampedLeft, clampedRight); - var coordinate = [lon, flatCoordinates[1]]; - var point = this.parallelsLabels_[index] !== undefined ? + const flatCoordinates = lineString.getFlatCoordinates(); + const clampedLeft = Math.max(extent[0], flatCoordinates[0]); + const clampedRight = Math.min(extent[2], flatCoordinates[flatCoordinates.length - 2]); + const lon = clamp( + extent[0] + Math.abs(extent[0] - extent[2]) * this.latLabelPosition_, + clampedLeft, clampedRight); + const coordinate = [lon, flatCoordinates[1]]; + const point = this.parallelsLabels_[index] !== undefined ? this.parallelsLabels_[index].geom : new Point(null); point.setCoordinates(coordinate); return point; @@ -426,7 +426,7 @@ Graticule.prototype.getParallelPoint_ = function(lineString, extent, index) { */ Graticule.prototype.createGraticule_ = function(extent, center, resolution, squaredTolerance) { - var interval = this.getInterval_(resolution); + const interval = this.getInterval_(resolution); if (interval == -1) { this.meridians_.length = this.parallels_.length = 0; if (this.meridiansLabels_) { @@ -438,13 +438,13 @@ Graticule.prototype.createGraticule_ = function(extent, center, resolution, squa return; } - var centerLonLat = this.toLonLatTransform_(center); - var centerLon = centerLonLat[0]; - var centerLat = centerLonLat[1]; - var maxLines = this.maxLines_; - var cnt, idx, lat, lon; + const centerLonLat = this.toLonLatTransform_(center); + let centerLon = centerLonLat[0]; + let centerLat = centerLonLat[1]; + const maxLines = this.maxLines_; + let cnt, idx, lat, lon; - var validExtent = [ + let validExtent = [ Math.max(extent[0], this.minLonP_), Math.max(extent[1], this.minLatP_), Math.min(extent[2], this.maxLonP_), @@ -452,11 +452,11 @@ Graticule.prototype.createGraticule_ = function(extent, center, resolution, squa ]; validExtent = transformExtent(validExtent, this.projection_, - 'EPSG:4326'); - var maxLat = validExtent[3]; - var maxLon = validExtent[2]; - var minLat = validExtent[1]; - var minLon = validExtent[0]; + 'EPSG:4326'); + const maxLat = validExtent[3]; + const maxLon = validExtent[2]; + const minLat = validExtent[1]; + const minLon = validExtent[0]; // Create meridians @@ -519,15 +519,15 @@ Graticule.prototype.createGraticule_ = function(extent, center, resolution, squa * @private */ Graticule.prototype.getInterval_ = function(resolution) { - var centerLon = this.projectionCenterLonLat_[0]; - var centerLat = this.projectionCenterLonLat_[1]; - var interval = -1; - var i, ii, delta, dist; - var target = Math.pow(this.targetSize_ * resolution, 2); + const centerLon = this.projectionCenterLonLat_[0]; + const centerLat = this.projectionCenterLonLat_[1]; + let interval = -1; + let i, ii, delta, dist; + const target = Math.pow(this.targetSize_ * resolution, 2); /** @type {Array.} **/ - var p1 = []; + const p1 = []; /** @type {Array.} **/ - var p2 = []; + const p2 = []; for (i = 0, ii = INTERVALS.length; i < ii; ++i) { delta = INTERVALS[i] / 2; p1[0] = centerLon - delta; @@ -566,10 +566,10 @@ Graticule.prototype.getMap = function() { * @private */ Graticule.prototype.getMeridian_ = function(lon, minLat, maxLat, - squaredTolerance, index) { - var flatCoordinates = _ol_geom_flat_geodesic_.meridian(lon, - minLat, maxLat, this.projection_, squaredTolerance); - var lineString = this.meridians_[index] !== undefined ? + squaredTolerance, index) { + const flatCoordinates = _ol_geom_flat_geodesic_.meridian(lon, + minLat, maxLat, this.projection_, squaredTolerance); + const lineString = this.meridians_[index] !== undefined ? this.meridians_[index] : new LineString(null); lineString.setFlatCoordinates(GeometryLayout.XY, flatCoordinates); return lineString; @@ -596,10 +596,10 @@ Graticule.prototype.getMeridians = function() { * @private */ Graticule.prototype.getParallel_ = function(lat, minLon, maxLon, - squaredTolerance, index) { - var flatCoordinates = _ol_geom_flat_geodesic_.parallel(lat, - minLon, maxLon, this.projection_, squaredTolerance); - var lineString = this.parallels_[index] !== undefined ? + squaredTolerance, index) { + const flatCoordinates = _ol_geom_flat_geodesic_.parallel(lat, + minLon, maxLon, this.projection_, squaredTolerance); + const lineString = this.parallels_[index] !== undefined ? this.parallels_[index] : new LineString(null); lineString.setFlatCoordinates(GeometryLayout.XY, flatCoordinates); return lineString; @@ -621,18 +621,18 @@ Graticule.prototype.getParallels = function() { * @private */ Graticule.prototype.handlePostCompose_ = function(e) { - var vectorContext = e.vectorContext; - var frameState = e.frameState; - var extent = frameState.extent; - var viewState = frameState.viewState; - var center = viewState.center; - var projection = viewState.projection; - var resolution = viewState.resolution; - var pixelRatio = frameState.pixelRatio; - var squaredTolerance = + const vectorContext = e.vectorContext; + const frameState = e.frameState; + const extent = frameState.extent; + const viewState = frameState.viewState; + const center = viewState.center; + const projection = viewState.projection; + const resolution = viewState.resolution; + const pixelRatio = frameState.pixelRatio; + const squaredTolerance = resolution * resolution / (4 * pixelRatio * pixelRatio); - var updateProjectionInfo = !this.projection_ || + const updateProjectionInfo = !this.projection_ || !equivalentProjection(this.projection_, projection); if (updateProjectionInfo) { @@ -643,7 +643,7 @@ Graticule.prototype.handlePostCompose_ = function(e) { // Draw the lines vectorContext.setFillStrokeStyle(null, this.strokeStyle_); - var i, l, line; + let i, l, line; for (i = 0, l = this.meridians_.length; i < l; ++i) { line = this.meridians_[i]; vectorContext.drawGeometry(line); @@ -652,7 +652,7 @@ Graticule.prototype.handlePostCompose_ = function(e) { line = this.parallels_[i]; vectorContext.drawGeometry(line); } - var labelData; + let labelData; if (this.meridiansLabels_) { for (i = 0, l = this.meridiansLabels_.length; i < l; ++i) { labelData = this.meridiansLabels_[i]; @@ -677,22 +677,22 @@ Graticule.prototype.handlePostCompose_ = function(e) { * @private */ Graticule.prototype.updateProjectionInfo_ = function(projection) { - var epsg4326Projection = getProjection('EPSG:4326'); + const epsg4326Projection = getProjection('EPSG:4326'); - var extent = projection.getExtent(); - var worldExtent = projection.getWorldExtent(); - var worldExtentP = transformExtent(worldExtent, - epsg4326Projection, projection); + const extent = projection.getExtent(); + const worldExtent = projection.getWorldExtent(); + const worldExtentP = transformExtent(worldExtent, + epsg4326Projection, projection); - var maxLat = worldExtent[3]; - var maxLon = worldExtent[2]; - var minLat = worldExtent[1]; - var minLon = worldExtent[0]; + const maxLat = worldExtent[3]; + const maxLon = worldExtent[2]; + const minLat = worldExtent[1]; + const minLon = worldExtent[0]; - var maxLatP = worldExtentP[3]; - var maxLonP = worldExtentP[2]; - var minLatP = worldExtentP[1]; - var minLonP = worldExtentP[0]; + const maxLatP = worldExtentP[3]; + const maxLonP = worldExtentP[2]; + const minLatP = worldExtentP[1]; + const minLonP = worldExtentP[0]; this.maxLat_ = maxLat; this.maxLon_ = maxLon; diff --git a/src/ol/Image.js b/src/ol/Image.js index 86142a86fc..5138898842 100644 --- a/src/ol/Image.js +++ b/src/ol/Image.js @@ -18,7 +18,7 @@ import {getHeight} from './extent.js'; * @param {?string} crossOrigin Cross origin. * @param {ol.ImageLoadFunctionType} imageLoadFunction Image load function. */ -var _ol_Image_ = function(extent, resolution, pixelRatio, src, crossOrigin, imageLoadFunction) { +const _ol_Image_ = function(extent, resolution, pixelRatio, src, crossOrigin, imageLoadFunction) { _ol_ImageBase_.call(this, extent, resolution, pixelRatio, ImageState.IDLE); @@ -109,9 +109,9 @@ _ol_Image_.prototype.load = function() { this.changed(); this.imageListenerKeys_ = [ _ol_events_.listenOnce(this.image_, EventType.ERROR, - this.handleImageError_, this), + this.handleImageError_, this), _ol_events_.listenOnce(this.image_, EventType.LOAD, - this.handleImageLoad_, this) + this.handleImageLoad_, this) ]; this.imageLoadFunction_(this, this.src_); } diff --git a/src/ol/ImageBase.js b/src/ol/ImageBase.js index 58128dd6b6..2c2b1c14fc 100644 --- a/src/ol/ImageBase.js +++ b/src/ol/ImageBase.js @@ -14,7 +14,7 @@ import EventType from './events/EventType.js'; * @param {number} pixelRatio Pixel ratio. * @param {ol.ImageState} state State. */ -var _ol_ImageBase_ = function(extent, resolution, pixelRatio, state) { +const _ol_ImageBase_ = function(extent, resolution, pixelRatio, state) { EventTarget.call(this); diff --git a/src/ol/ImageCanvas.js b/src/ol/ImageCanvas.js index 0a35034f0b..23a431de33 100644 --- a/src/ol/ImageCanvas.js +++ b/src/ol/ImageCanvas.js @@ -15,7 +15,7 @@ import ImageState from './ImageState.js'; * @param {ol.ImageCanvasLoader=} opt_loader Optional loader function to * support asynchronous canvas drawing. */ -var ImageCanvas = function(extent, resolution, pixelRatio, canvas, opt_loader) { +const ImageCanvas = function(extent, resolution, pixelRatio, canvas, opt_loader) { /** * Optional canvas loader function. @@ -24,7 +24,7 @@ var ImageCanvas = function(extent, resolution, pixelRatio, canvas, opt_loader) { */ this.loader_ = opt_loader !== undefined ? opt_loader : null; - var state = opt_loader !== undefined ? ImageState.IDLE : ImageState.LOADED; + const state = opt_loader !== undefined ? ImageState.IDLE : ImageState.LOADED; _ol_ImageBase_.call(this, extent, resolution, pixelRatio, state); diff --git a/src/ol/ImageTile.js b/src/ol/ImageTile.js index 7767926f41..0b2d4f0829 100644 --- a/src/ol/ImageTile.js +++ b/src/ol/ImageTile.js @@ -18,7 +18,7 @@ import EventType from './events/EventType.js'; * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function. * @param {olx.TileOptions=} opt_options Tile options. */ -var ImageTile = function(tileCoord, state, src, crossOrigin, tileLoadFunction, opt_options) { +const ImageTile = function(tileCoord, state, src, crossOrigin, tileLoadFunction, opt_options) { Tile.call(this, tileCoord, state, opt_options); @@ -143,9 +143,9 @@ ImageTile.prototype.load = function() { this.changed(); this.imageListenerKeys_ = [ _ol_events_.listenOnce(this.image_, EventType.ERROR, - this.handleImageError_, this), + this.handleImageError_, this), _ol_events_.listenOnce(this.image_, EventType.LOAD, - this.handleImageLoad_, this) + this.handleImageLoad_, this) ]; this.tileLoadFunction_(this, this.src_); } @@ -168,7 +168,7 @@ ImageTile.prototype.unlistenImage_ = function() { * @return {HTMLCanvasElement} Blank image. */ ImageTile.getBlankImage = function() { - var ctx = createCanvasContext2D(1, 1); + const ctx = createCanvasContext2D(1, 1); ctx.fillStyle = 'rgba(0,0,0,0)'; ctx.fillRect(0, 0, 1, 1); return ctx.canvas; diff --git a/src/ol/Kinetic.js b/src/ol/Kinetic.js index 500d10c234..8449e1b690 100644 --- a/src/ol/Kinetic.js +++ b/src/ol/Kinetic.js @@ -14,7 +14,7 @@ * @struct * @api */ -var Kinetic = function(decay, minVelocity, delay) { +const Kinetic = function(decay, minVelocity, delay) { /** * @private @@ -82,8 +82,8 @@ Kinetic.prototype.end = function() { // in the array) return false; } - var delay = Date.now() - this.delay_; - var lastIndex = this.points_.length - 3; + const delay = Date.now() - this.delay_; + const lastIndex = this.points_.length - 3; if (this.points_[lastIndex + 2] < delay) { // the last tracked point is too old, which means that the user stopped // panning before releasing the map @@ -91,12 +91,12 @@ Kinetic.prototype.end = function() { } // get the first point which still falls into the delay time - var firstIndex = lastIndex - 3; + let firstIndex = lastIndex - 3; while (firstIndex > 0 && this.points_[firstIndex + 2] > delay) { firstIndex -= 3; } - var duration = this.points_[lastIndex + 2] - this.points_[firstIndex + 2]; + const duration = this.points_[lastIndex + 2] - this.points_[firstIndex + 2]; // we don't want a duration of 0 (divide by zero) // we also make sure the user panned for a duration of at least one frame // (1/60s) to compute sane displacement values @@ -104,8 +104,8 @@ Kinetic.prototype.end = function() { return false; } - var dx = this.points_[lastIndex] - this.points_[firstIndex]; - var dy = this.points_[lastIndex + 1] - this.points_[firstIndex + 1]; + const dx = this.points_[lastIndex] - this.points_[firstIndex]; + const dy = this.points_[lastIndex + 1] - this.points_[firstIndex + 1]; this.angle_ = Math.atan2(dy, dx); this.initialVelocity_ = Math.sqrt(dx * dx + dy * dy) / duration; return this.initialVelocity_ > this.minVelocity_; diff --git a/src/ol/Map.js b/src/ol/Map.js index d3a04dc4c1..c4a6647883 100644 --- a/src/ol/Map.js +++ b/src/ol/Map.js @@ -84,7 +84,7 @@ registerMultiple(PluginType.LAYER_RENDERER, [ * @fires ol.render.Event#precompose * @api */ -var Map = function(options) { +const Map = function(options) { options = _ol_obj_.assign({}, options); if (!options.controls) { options.controls = defaultControls(); diff --git a/src/ol/MapBrowserEvent.js b/src/ol/MapBrowserEvent.js index 13f6abb801..518323dfa0 100644 --- a/src/ol/MapBrowserEvent.js +++ b/src/ol/MapBrowserEvent.js @@ -18,8 +18,8 @@ import MapEvent from './MapEvent.js'; * @param {boolean=} opt_dragging Is the map currently being dragged? * @param {?olx.FrameState=} opt_frameState Frame state. */ -var MapBrowserEvent = function(type, map, browserEvent, opt_dragging, - opt_frameState) { +const MapBrowserEvent = function(type, map, browserEvent, opt_dragging, + opt_frameState) { MapEvent.call(this, type, map, opt_frameState); diff --git a/src/ol/MapBrowserEventHandler.js b/src/ol/MapBrowserEventHandler.js index 5bb188e837..f68d668b48 100644 --- a/src/ol/MapBrowserEventHandler.js +++ b/src/ol/MapBrowserEventHandler.js @@ -16,7 +16,7 @@ import PointerEventHandler from './pointer/PointerEventHandler.js'; * @constructor * @extends {ol.events.EventTarget} */ -var MapBrowserEventHandler = function(map, moveTolerance) { +const MapBrowserEventHandler = function(map, moveTolerance) { EventTarget.call(this); @@ -60,7 +60,7 @@ var MapBrowserEventHandler = function(map, moveTolerance) { */ this.down_ = null; - var element = this.map_.getViewport(); + const element = this.map_.getViewport(); /** * @type {number} @@ -97,16 +97,16 @@ var MapBrowserEventHandler = function(map, moveTolerance) { * @private */ this.pointerdownListenerKey_ = _ol_events_.listen(this.pointerEventHandler_, - PointerEventType.POINTERDOWN, - this.handlePointerDown_, this); + PointerEventType.POINTERDOWN, + this.handlePointerDown_, this); /** * @type {?ol.EventsKey} * @private */ this.relayedListenerKey_ = _ol_events_.listen(this.pointerEventHandler_, - PointerEventType.POINTERMOVE, - this.relayEvent_, this); + PointerEventType.POINTERMOVE, + this.relayEvent_, this); }; @@ -118,22 +118,22 @@ inherits(MapBrowserEventHandler, EventTarget); * @private */ MapBrowserEventHandler.prototype.emulateClick_ = function(pointerEvent) { - var newEvent = new MapBrowserPointerEvent( - MapBrowserEventType.CLICK, this.map_, pointerEvent); + let newEvent = new MapBrowserPointerEvent( + MapBrowserEventType.CLICK, this.map_, pointerEvent); this.dispatchEvent(newEvent); if (this.clickTimeoutId_ !== 0) { // double-click clearTimeout(this.clickTimeoutId_); this.clickTimeoutId_ = 0; newEvent = new MapBrowserPointerEvent( - MapBrowserEventType.DBLCLICK, this.map_, pointerEvent); + MapBrowserEventType.DBLCLICK, this.map_, pointerEvent); this.dispatchEvent(newEvent); } else { // click this.clickTimeoutId_ = setTimeout(function() { this.clickTimeoutId_ = 0; - var newEvent = new MapBrowserPointerEvent( - MapBrowserEventType.SINGLECLICK, this.map_, pointerEvent); + const newEvent = new MapBrowserPointerEvent( + MapBrowserEventType.SINGLECLICK, this.map_, pointerEvent); this.dispatchEvent(newEvent); }.bind(this), 250); } @@ -147,7 +147,7 @@ MapBrowserEventHandler.prototype.emulateClick_ = function(pointerEvent) { * @private */ MapBrowserEventHandler.prototype.updateActivePointers_ = function(pointerEvent) { - var event = pointerEvent; + const event = pointerEvent; if (event.type == MapBrowserEventType.POINTERUP || event.type == MapBrowserEventType.POINTERCANCEL) { @@ -165,8 +165,8 @@ MapBrowserEventHandler.prototype.updateActivePointers_ = function(pointerEvent) */ MapBrowserEventHandler.prototype.handlePointerUp_ = function(pointerEvent) { this.updateActivePointers_(pointerEvent); - var newEvent = new MapBrowserPointerEvent( - MapBrowserEventType.POINTERUP, this.map_, pointerEvent); + const newEvent = new MapBrowserPointerEvent( + MapBrowserEventType.POINTERUP, this.map_, pointerEvent); this.dispatchEvent(newEvent); // We emulate click events on left mouse button click, touch contact, and pen @@ -206,8 +206,8 @@ MapBrowserEventHandler.prototype.isMouseActionButton_ = function(pointerEvent) { */ MapBrowserEventHandler.prototype.handlePointerDown_ = function(pointerEvent) { this.updateActivePointers_(pointerEvent); - var newEvent = new MapBrowserPointerEvent( - MapBrowserEventType.POINTERDOWN, this.map_, pointerEvent); + const newEvent = new MapBrowserPointerEvent( + MapBrowserEventType.POINTERDOWN, this.map_, pointerEvent); this.dispatchEvent(newEvent); this.down_ = pointerEvent; @@ -221,13 +221,13 @@ MapBrowserEventHandler.prototype.handlePointerDown_ = function(pointerEvent) { new PointerEventHandler(document); this.dragListenerKeys_.push( - _ol_events_.listen(this.documentPointerEventHandler_, - MapBrowserEventType.POINTERMOVE, - this.handlePointerMove_, this), - _ol_events_.listen(this.documentPointerEventHandler_, - MapBrowserEventType.POINTERUP, - this.handlePointerUp_, this), - /* Note that the listener for `pointercancel is set up on + _ol_events_.listen(this.documentPointerEventHandler_, + MapBrowserEventType.POINTERMOVE, + this.handlePointerMove_, this), + _ol_events_.listen(this.documentPointerEventHandler_, + MapBrowserEventType.POINTERUP, + this.handlePointerUp_, this), + /* Note that the listener for `pointercancel is set up on * `pointerEventHandler_` and not `documentPointerEventHandler_` like * the `pointerup` and `pointermove` listeners. * @@ -240,9 +240,9 @@ MapBrowserEventHandler.prototype.handlePointerDown_ = function(pointerEvent) { * only receive a `touchcancel` from `pointerEventHandler_`, because it is * only registered there. */ - _ol_events_.listen(this.pointerEventHandler_, - MapBrowserEventType.POINTERCANCEL, - this.handlePointerUp_, this) + _ol_events_.listen(this.pointerEventHandler_, + MapBrowserEventType.POINTERCANCEL, + this.handlePointerUp_, this) ); } }; @@ -258,9 +258,9 @@ MapBrowserEventHandler.prototype.handlePointerMove_ = function(pointerEvent) { // moved a significant distance. if (this.isMoving_(pointerEvent)) { this.dragging_ = true; - var newEvent = new MapBrowserPointerEvent( - MapBrowserEventType.POINTERDRAG, this.map_, pointerEvent, - this.dragging_); + const newEvent = new MapBrowserPointerEvent( + MapBrowserEventType.POINTERDRAG, this.map_, pointerEvent, + this.dragging_); this.dispatchEvent(newEvent); } @@ -279,9 +279,9 @@ MapBrowserEventHandler.prototype.handlePointerMove_ = function(pointerEvent) { * @private */ MapBrowserEventHandler.prototype.relayEvent_ = function(pointerEvent) { - var dragging = !!(this.down_ && this.isMoving_(pointerEvent)); + const dragging = !!(this.down_ && this.isMoving_(pointerEvent)); this.dispatchEvent(new MapBrowserPointerEvent( - pointerEvent.type, this.map_, pointerEvent, dragging)); + pointerEvent.type, this.map_, pointerEvent, dragging)); }; diff --git a/src/ol/MapBrowserPointerEvent.js b/src/ol/MapBrowserPointerEvent.js index d08523582a..e5a4a97bce 100644 --- a/src/ol/MapBrowserPointerEvent.js +++ b/src/ol/MapBrowserPointerEvent.js @@ -13,11 +13,11 @@ import MapBrowserEvent from './MapBrowserEvent.js'; * @param {boolean=} opt_dragging Is the map currently being dragged? * @param {?olx.FrameState=} opt_frameState Frame state. */ -var MapBrowserPointerEvent = function(type, map, pointerEvent, opt_dragging, - opt_frameState) { +const MapBrowserPointerEvent = function(type, map, pointerEvent, opt_dragging, + opt_frameState) { MapBrowserEvent.call(this, type, map, pointerEvent.originalEvent, opt_dragging, - opt_frameState); + opt_frameState); /** * @const diff --git a/src/ol/MapEvent.js b/src/ol/MapEvent.js index 5071a13078..af64662b1b 100644 --- a/src/ol/MapEvent.js +++ b/src/ol/MapEvent.js @@ -16,7 +16,7 @@ import Event from './events/Event.js'; * @param {ol.PluggableMap} map Map. * @param {?olx.FrameState=} opt_frameState Frame state. */ -var MapEvent = function(type, map, opt_frameState) { +const MapEvent = function(type, map, opt_frameState) { Event.call(this, type); diff --git a/src/ol/Object.js b/src/ol/Object.js index 227061bdcb..f8d3b7d785 100644 --- a/src/ol/Object.js +++ b/src/ol/Object.js @@ -52,7 +52,7 @@ import _ol_obj_ from './obj.js'; * @fires ol.Object.Event * @api */ -var BaseObject = function(opt_values) { +const BaseObject = function(opt_values) { Observable.call(this); // Call ol.getUid to ensure that the order of objects' ids is the same as @@ -100,7 +100,7 @@ BaseObject.getChangeEventType = function(key) { * @api */ BaseObject.prototype.get = function(key) { - var value; + let value; if (this.values_.hasOwnProperty(key)) { value = this.values_[key]; } @@ -133,7 +133,7 @@ BaseObject.prototype.getProperties = function() { * @param {*} oldValue Old value. */ BaseObject.prototype.notify = function(key, oldValue) { - var eventType; + let eventType; eventType = BaseObject.getChangeEventType(key); this.dispatchEvent(new BaseObject.Event(eventType, key, oldValue)); eventType = ObjectEventType.PROPERTYCHANGE; @@ -152,7 +152,7 @@ BaseObject.prototype.set = function(key, value, opt_silent) { if (opt_silent) { this.values_[key] = value; } else { - var oldValue = this.values_[key]; + const oldValue = this.values_[key]; this.values_[key] = value; if (oldValue !== value) { this.notify(key, oldValue); @@ -169,7 +169,7 @@ BaseObject.prototype.set = function(key, value, opt_silent) { * @api */ BaseObject.prototype.setProperties = function(values, opt_silent) { - var key; + let key; for (key in values) { this.set(key, values[key], opt_silent); } @@ -184,7 +184,7 @@ BaseObject.prototype.setProperties = function(values, opt_silent) { */ BaseObject.prototype.unset = function(key, opt_silent) { if (key in this.values_) { - var oldValue = this.values_[key]; + const oldValue = this.values_[key]; delete this.values_[key]; if (!opt_silent) { this.notify(key, oldValue); diff --git a/src/ol/Observable.js b/src/ol/Observable.js index 53ea102ed3..2cffbba385 100644 --- a/src/ol/Observable.js +++ b/src/ol/Observable.js @@ -20,7 +20,7 @@ import EventType from './events/EventType.js'; * @struct * @api */ -var Observable = function() { +const Observable = function() { EventTarget.call(this); @@ -43,7 +43,7 @@ inherits(Observable, EventTarget); */ Observable.unByKey = function(key) { if (Array.isArray(key)) { - for (var i = 0, ii = key.length; i < ii; ++i) { + for (let i = 0, ii = key.length; i < ii; ++i) { _ol_events_.unlistenByKey(key[i]); } } else { @@ -98,15 +98,15 @@ Observable.prototype.getRevision = function() { */ Observable.prototype.on = function(type, listener) { if (Array.isArray(type)) { - var len = type.length; - var keys = new Array(len); - for (var i = 0; i < len; ++i) { + const len = type.length; + const keys = new Array(len); + for (let i = 0; i < len; ++i) { keys[i] = _ol_events_.listen(this, type[i], listener); } return keys; } else { return _ol_events_.listen( - this, /** @type {string} */ (type), listener); + this, /** @type {string} */ (type), listener); } }; @@ -122,15 +122,15 @@ Observable.prototype.on = function(type, listener) { */ Observable.prototype.once = function(type, listener) { if (Array.isArray(type)) { - var len = type.length; - var keys = new Array(len); - for (var i = 0; i < len; ++i) { + const len = type.length; + const keys = new Array(len); + for (let i = 0; i < len; ++i) { keys[i] = _ol_events_.listenOnce(this, type[i], listener); } return keys; } else { return _ol_events_.listenOnce( - this, /** @type {string} */ (type), listener); + this, /** @type {string} */ (type), listener); } }; @@ -143,7 +143,7 @@ Observable.prototype.once = function(type, listener) { */ Observable.prototype.un = function(type, listener) { if (Array.isArray(type)) { - for (var i = 0, ii = type.length; i < ii; ++i) { + for (let i = 0, ii = type.length; i < ii; ++i) { _ol_events_.unlisten(this, type[i], listener); } return; diff --git a/src/ol/Overlay.js b/src/ol/Overlay.js index e331f33881..1a937290b7 100644 --- a/src/ol/Overlay.js +++ b/src/ol/Overlay.js @@ -15,7 +15,7 @@ import {containsExtent} from './extent.js'; * @enum {string} * @protected */ -var Property = { +const Property = { ELEMENT: 'element', MAP: 'map', OFFSET: 'offset', @@ -45,7 +45,7 @@ var Property = { * @param {olx.OverlayOptions} options Overlay options. * @api */ -var Overlay = function(options) { +const Overlay = function(options) { BaseObject.call(this); @@ -126,24 +126,24 @@ var Overlay = function(options) { this.mapPostrenderListenerKey = null; _ol_events_.listen( - this, BaseObject.getChangeEventType(Property.ELEMENT), - this.handleElementChanged, this); + this, BaseObject.getChangeEventType(Property.ELEMENT), + this.handleElementChanged, this); _ol_events_.listen( - this, BaseObject.getChangeEventType(Property.MAP), - this.handleMapChanged, this); + this, BaseObject.getChangeEventType(Property.MAP), + this.handleMapChanged, this); _ol_events_.listen( - this, BaseObject.getChangeEventType(Property.OFFSET), - this.handleOffsetChanged, this); + this, BaseObject.getChangeEventType(Property.OFFSET), + this.handleOffsetChanged, this); _ol_events_.listen( - this, BaseObject.getChangeEventType(Property.POSITION), - this.handlePositionChanged, this); + this, BaseObject.getChangeEventType(Property.POSITION), + this.handlePositionChanged, this); _ol_events_.listen( - this, BaseObject.getChangeEventType(Property.POSITIONING), - this.handlePositioningChanged, this); + this, BaseObject.getChangeEventType(Property.POSITIONING), + this.handlePositioningChanged, this); if (options.element !== undefined) { this.setElement(options.element); @@ -236,7 +236,7 @@ Overlay.prototype.getPositioning = function() { */ Overlay.prototype.handleElementChanged = function() { removeChildren(this.element); - var element = this.getElement(); + const element = this.getElement(); if (element) { this.element.appendChild(element); } @@ -252,12 +252,12 @@ Overlay.prototype.handleMapChanged = function() { _ol_events_.unlistenByKey(this.mapPostrenderListenerKey); this.mapPostrenderListenerKey = null; } - var map = this.getMap(); + const map = this.getMap(); if (map) { this.mapPostrenderListenerKey = _ol_events_.listen(map, - MapEventType.POSTRENDER, this.render, this); + MapEventType.POSTRENDER, this.render, this); this.updatePixelPosition(); - var container = this.stopEvent ? + const container = this.stopEvent ? map.getOverlayContainerStopEvent() : map.getOverlayContainer(); if (this.insertFirst) { container.insertBefore(this.element, container.childNodes[0] || null); @@ -355,25 +355,25 @@ Overlay.prototype.setPosition = function(position) { * @protected */ Overlay.prototype.panIntoView = function() { - var map = this.getMap(); + const map = this.getMap(); if (!map || !map.getTargetElement()) { return; } - var mapRect = this.getRect(map.getTargetElement(), map.getSize()); - var element = /** @type {!Element} */ (this.getElement()); - var overlayRect = this.getRect(element, [outerWidth(element), outerHeight(element)]); + const mapRect = this.getRect(map.getTargetElement(), map.getSize()); + const element = /** @type {!Element} */ (this.getElement()); + const overlayRect = this.getRect(element, [outerWidth(element), outerHeight(element)]); - var margin = this.autoPanMargin; + const margin = this.autoPanMargin; if (!containsExtent(mapRect, overlayRect)) { // the overlay is not completely inside the viewport, so pan the map - var offsetLeft = overlayRect[0] - mapRect[0]; - var offsetRight = mapRect[2] - overlayRect[2]; - var offsetTop = overlayRect[1] - mapRect[1]; - var offsetBottom = mapRect[3] - overlayRect[3]; + const offsetLeft = overlayRect[0] - mapRect[0]; + const offsetRight = mapRect[2] - overlayRect[2]; + const offsetTop = overlayRect[1] - mapRect[1]; + const offsetBottom = mapRect[3] - overlayRect[3]; - var delta = [0, 0]; + const delta = [0, 0]; if (offsetLeft < 0) { // move map to the left delta[0] = offsetLeft - margin; @@ -390,9 +390,9 @@ Overlay.prototype.panIntoView = function() { } if (delta[0] !== 0 || delta[1] !== 0) { - var center = /** @type {ol.Coordinate} */ (map.getView().getCenter()); - var centerPx = map.getPixelFromCoordinate(center); - var newCenterPx = [ + const center = /** @type {ol.Coordinate} */ (map.getView().getCenter()); + const centerPx = map.getPixelFromCoordinate(center); + const newCenterPx = [ centerPx[0] + delta[0], centerPx[1] + delta[1] ]; @@ -415,9 +415,9 @@ Overlay.prototype.panIntoView = function() { * @protected */ Overlay.prototype.getRect = function(element, size) { - var box = element.getBoundingClientRect(); - var offsetX = box.left + window.pageXOffset; - var offsetY = box.top + window.pageYOffset; + const box = element.getBoundingClientRect(); + const offsetX = box.left + window.pageXOffset; + const offsetY = box.top + window.pageYOffset; return [ offsetX, offsetY, @@ -457,15 +457,15 @@ Overlay.prototype.setVisible = function(visible) { * @protected */ Overlay.prototype.updatePixelPosition = function() { - var map = this.getMap(); - var position = this.getPosition(); + const map = this.getMap(); + const position = this.getPosition(); if (!map || !map.isRendered() || !position) { this.setVisible(false); return; } - var pixel = map.getPixelFromCoordinate(position); - var mapSize = map.getSize(); + const pixel = map.getPixelFromCoordinate(position); + const mapSize = map.getSize(); this.updateRenderedPosition(pixel, mapSize); }; @@ -476,22 +476,22 @@ Overlay.prototype.updatePixelPosition = function() { * @protected */ Overlay.prototype.updateRenderedPosition = function(pixel, mapSize) { - var style = this.element.style; - var offset = this.getOffset(); + const style = this.element.style; + const offset = this.getOffset(); - var positioning = this.getPositioning(); + const positioning = this.getPositioning(); this.setVisible(true); - var offsetX = offset[0]; - var offsetY = offset[1]; + let offsetX = offset[0]; + let offsetY = offset[1]; if (positioning == OverlayPositioning.BOTTOM_RIGHT || positioning == OverlayPositioning.CENTER_RIGHT || positioning == OverlayPositioning.TOP_RIGHT) { if (this.rendered.left_ !== '') { this.rendered.left_ = style.left = ''; } - var right = Math.round(mapSize[0] - pixel[0] - offsetX) + 'px'; + const right = Math.round(mapSize[0] - pixel[0] - offsetX) + 'px'; if (this.rendered.right_ != right) { this.rendered.right_ = style.right = right; } @@ -504,7 +504,7 @@ Overlay.prototype.updateRenderedPosition = function(pixel, mapSize) { positioning == OverlayPositioning.TOP_CENTER) { offsetX -= this.element.offsetWidth / 2; } - var left = Math.round(pixel[0] + offsetX) + 'px'; + const left = Math.round(pixel[0] + offsetX) + 'px'; if (this.rendered.left_ != left) { this.rendered.left_ = style.left = left; } @@ -515,7 +515,7 @@ Overlay.prototype.updateRenderedPosition = function(pixel, mapSize) { if (this.rendered.top_ !== '') { this.rendered.top_ = style.top = ''; } - var bottom = Math.round(mapSize[1] - pixel[1] - offsetY) + 'px'; + const bottom = Math.round(mapSize[1] - pixel[1] - offsetY) + 'px'; if (this.rendered.bottom_ != bottom) { this.rendered.bottom_ = style.bottom = bottom; } @@ -528,7 +528,7 @@ Overlay.prototype.updateRenderedPosition = function(pixel, mapSize) { positioning == OverlayPositioning.CENTER_RIGHT) { offsetY -= this.element.offsetHeight / 2; } - var top = Math.round(pixel[1] + offsetY) + 'px'; + const top = Math.round(pixel[1] + offsetY) + 'px'; if (this.rendered.top_ != top) { this.rendered.top_ = style.top = top; } diff --git a/src/ol/PluggableMap.js b/src/ol/PluggableMap.js index e0c76532ee..187d1b1fdf 100644 --- a/src/ol/PluggableMap.js +++ b/src/ol/PluggableMap.js @@ -46,7 +46,7 @@ import _ol_transform_ from './transform.js'; * target: (Element|string|undefined), * view: (ol.View|undefined)}} */ -export var MapOptions; +export let MapOptions; /** @@ -109,11 +109,11 @@ export var MapOptions; * @fires ol.render.Event#precompose * @api */ -var PluggableMap = function(options) { +const PluggableMap = function(options) { BaseObject.call(this); - var optionsInternal = createOptionsInternal(options); + const optionsInternal = createOptionsInternal(options); /** * @type {boolean} @@ -229,7 +229,7 @@ var PluggableMap = function(options) { */ this.overlayContainerStopEvent_ = document.createElement('DIV'); this.overlayContainerStopEvent_.className = 'ol-overlaycontainer-stopevent'; - var overlayEvents = [ + const overlayEvents = [ EventType.CLICK, EventType.DBLCLICK, EventType.MOUSEDOWN, @@ -239,9 +239,9 @@ var PluggableMap = function(options) { EventType.MOUSEWHEEL, EventType.WHEEL ]; - for (var i = 0, ii = overlayEvents.length; i < ii; ++i) { + for (let i = 0, ii = overlayEvents.length; i < ii; ++i) { _ol_events_.listen(this.overlayContainerStopEvent_, overlayEvents[i], - Event.stopPropagation); + Event.stopPropagation); } this.viewport_.appendChild(this.overlayContainerStopEvent_); @@ -250,9 +250,9 @@ var PluggableMap = function(options) { * @type {ol.MapBrowserEventHandler} */ this.mapBrowserEventHandler_ = new MapBrowserEventHandler(this, options.moveTolerance); - for (var key in MapBrowserEventType) { + for (const key in MapBrowserEventType) { _ol_events_.listen(this.mapBrowserEventHandler_, MapBrowserEventType[key], - this.handleMapBrowserEvent, this); + this.handleMapBrowserEvent, this); } /** @@ -268,9 +268,9 @@ var PluggableMap = function(options) { this.keyHandlerKeys_ = null; _ol_events_.listen(this.viewport_, EventType.WHEEL, - this.handleBrowserEvent, this); + this.handleBrowserEvent, this); _ol_events_.listen(this.viewport_, EventType.MOUSEWHEEL, - this.handleBrowserEvent, this); + this.handleBrowserEvent, this); /** * @type {ol.Collection.} @@ -326,8 +326,8 @@ var PluggableMap = function(options) { * @type {ol.TileQueue} */ this.tileQueue_ = new TileQueue( - this.getTilePriority.bind(this), - this.handleTileChange_.bind(this)); + this.getTilePriority.bind(this), + this.handleTileChange_.bind(this)); /** * Uids of features to skip at rendering time. @@ -337,91 +337,91 @@ var PluggableMap = function(options) { this.skippedFeatureUids_ = {}; _ol_events_.listen( - this, BaseObject.getChangeEventType(MapProperty.LAYERGROUP), - this.handleLayerGroupChanged_, this); + this, BaseObject.getChangeEventType(MapProperty.LAYERGROUP), + this.handleLayerGroupChanged_, this); _ol_events_.listen(this, BaseObject.getChangeEventType(MapProperty.VIEW), - this.handleViewChanged_, this); + this.handleViewChanged_, this); _ol_events_.listen(this, BaseObject.getChangeEventType(MapProperty.SIZE), - this.handleSizeChanged_, this); + this.handleSizeChanged_, this); _ol_events_.listen(this, BaseObject.getChangeEventType(MapProperty.TARGET), - this.handleTargetChanged_, this); + this.handleTargetChanged_, this); // setProperties will trigger the rendering of the map if the map // is "defined" already. this.setProperties(optionsInternal.values); this.controls.forEach( - /** + /** * @param {ol.control.Control} control Control. * @this {ol.PluggableMap} */ - function(control) { - control.setMap(this); - }.bind(this)); + function(control) { + control.setMap(this); + }.bind(this)); _ol_events_.listen(this.controls, CollectionEventType.ADD, - /** + /** * @param {ol.Collection.Event} event Collection event. */ - function(event) { - event.element.setMap(this); - }, this); + function(event) { + event.element.setMap(this); + }, this); _ol_events_.listen(this.controls, CollectionEventType.REMOVE, - /** + /** * @param {ol.Collection.Event} event Collection event. */ - function(event) { - event.element.setMap(null); - }, this); + function(event) { + event.element.setMap(null); + }, this); this.interactions.forEach( - /** + /** * @param {ol.interaction.Interaction} interaction Interaction. * @this {ol.PluggableMap} */ - function(interaction) { - interaction.setMap(this); - }.bind(this)); + function(interaction) { + interaction.setMap(this); + }.bind(this)); _ol_events_.listen(this.interactions, CollectionEventType.ADD, - /** + /** * @param {ol.Collection.Event} event Collection event. */ - function(event) { - event.element.setMap(this); - }, this); + function(event) { + event.element.setMap(this); + }, this); _ol_events_.listen(this.interactions, CollectionEventType.REMOVE, - /** + /** * @param {ol.Collection.Event} event Collection event. */ - function(event) { - event.element.setMap(null); - }, this); + function(event) { + event.element.setMap(null); + }, this); this.overlays_.forEach(this.addOverlayInternal_.bind(this)); _ol_events_.listen(this.overlays_, CollectionEventType.ADD, - /** + /** * @param {ol.Collection.Event} event Collection event. */ - function(event) { - this.addOverlayInternal_(/** @type {ol.Overlay} */ (event.element)); - }, this); + function(event) { + this.addOverlayInternal_(/** @type {ol.Overlay} */ (event.element)); + }, this); _ol_events_.listen(this.overlays_, CollectionEventType.REMOVE, - /** + /** * @param {ol.Collection.Event} event Collection event. */ - function(event) { - var overlay = /** @type {ol.Overlay} */ (event.element); - var id = overlay.getId(); - if (id !== undefined) { - delete this.overlayIdIndex_[id.toString()]; - } - event.element.setMap(null); - }, this); + function(event) { + const overlay = /** @type {ol.Overlay} */ (event.element); + const id = overlay.getId(); + if (id !== undefined) { + delete this.overlayIdIndex_[id.toString()]; + } + event.element.setMap(null); + }, this); }; @@ -456,7 +456,7 @@ PluggableMap.prototype.addInteraction = function(interaction) { * @api */ PluggableMap.prototype.addLayer = function(layer) { - var layers = this.getLayerGroup().getLayers(); + const layers = this.getLayerGroup().getLayers(); layers.push(layer); }; @@ -477,7 +477,7 @@ PluggableMap.prototype.addOverlay = function(overlay) { * @private */ PluggableMap.prototype.addOverlayInternal_ = function(overlay) { - var id = overlay.getId(); + const id = overlay.getId(); if (id !== undefined) { this.overlayIdIndex_[id.toString()] = overlay; } @@ -492,12 +492,12 @@ PluggableMap.prototype.addOverlayInternal_ = function(overlay) { PluggableMap.prototype.disposeInternal = function() { this.mapBrowserEventHandler_.dispose(); _ol_events_.unlisten(this.viewport_, EventType.WHEEL, - this.handleBrowserEvent, this); + this.handleBrowserEvent, this); _ol_events_.unlisten(this.viewport_, EventType.MOUSEWHEEL, - this.handleBrowserEvent, this); + this.handleBrowserEvent, this); if (this.handleResize_ !== undefined) { window.removeEventListener(EventType.RESIZE, - this.handleResize_, false); + this.handleResize_, false); this.handleResize_ = undefined; } if (this.animationDelayKey_) { @@ -532,15 +532,15 @@ PluggableMap.prototype.forEachFeatureAtPixel = function(pixel, callback, opt_opt if (!this.frameState_) { return; } - var coordinate = this.getCoordinateFromPixel(pixel); + const coordinate = this.getCoordinateFromPixel(pixel); opt_options = opt_options !== undefined ? opt_options : {}; - var hitTolerance = opt_options.hitTolerance !== undefined ? + const hitTolerance = opt_options.hitTolerance !== undefined ? opt_options.hitTolerance * this.frameState_.pixelRatio : 0; - var layerFilter = opt_options.layerFilter !== undefined ? + const layerFilter = opt_options.layerFilter !== undefined ? opt_options.layerFilter : TRUE; return this.renderer_.forEachFeatureAtCoordinate( - coordinate, this.frameState_, hitTolerance, callback, null, - layerFilter, null); + coordinate, this.frameState_, hitTolerance, callback, null, + layerFilter, null); }; @@ -553,7 +553,7 @@ PluggableMap.prototype.forEachFeatureAtPixel = function(pixel, callback, opt_opt * @api */ PluggableMap.prototype.getFeaturesAtPixel = function(pixel, opt_options) { - var features = null; + let features = null; this.forEachFeatureAtPixel(pixel, function(feature) { if (!features) { features = []; @@ -591,12 +591,12 @@ PluggableMap.prototype.forEachLayerAtPixel = function(pixel, callback, opt_this, if (!this.frameState_) { return; } - var thisArg = opt_this !== undefined ? opt_this : null; - var layerFilter = opt_layerFilter !== undefined ? opt_layerFilter : TRUE; - var thisArg2 = opt_this2 !== undefined ? opt_this2 : null; + const thisArg = opt_this !== undefined ? opt_this : null; + const layerFilter = opt_layerFilter !== undefined ? opt_layerFilter : TRUE; + const thisArg2 = opt_this2 !== undefined ? opt_this2 : null; return this.renderer_.forEachLayerAtPixel( - pixel, this.frameState_, callback, thisArg, - layerFilter, thisArg2); + pixel, this.frameState_, callback, thisArg, + layerFilter, thisArg2); }; @@ -613,13 +613,13 @@ PluggableMap.prototype.hasFeatureAtPixel = function(pixel, opt_options) { if (!this.frameState_) { return false; } - var coordinate = this.getCoordinateFromPixel(pixel); + const coordinate = this.getCoordinateFromPixel(pixel); opt_options = opt_options !== undefined ? opt_options : {}; - var layerFilter = opt_options.layerFilter !== undefined ? opt_options.layerFilter : TRUE; - var hitTolerance = opt_options.hitTolerance !== undefined ? + const layerFilter = opt_options.layerFilter !== undefined ? opt_options.layerFilter : TRUE; + const hitTolerance = opt_options.hitTolerance !== undefined ? opt_options.hitTolerance * this.frameState_.pixelRatio : 0; return this.renderer_.hasFeatureAtCoordinate( - coordinate, this.frameState_, hitTolerance, layerFilter, null); + coordinate, this.frameState_, hitTolerance, layerFilter, null); }; @@ -641,8 +641,8 @@ PluggableMap.prototype.getEventCoordinate = function(event) { * @api */ PluggableMap.prototype.getEventPixel = function(event) { - var viewportPosition = this.viewport_.getBoundingClientRect(); - var eventPosition = event.changedTouches ? event.changedTouches[0] : event; + const viewportPosition = this.viewport_.getBoundingClientRect(); + const eventPosition = event.changedTouches ? event.changedTouches[0] : event; return [ eventPosition.clientX - viewportPosition.left, eventPosition.clientY - viewportPosition.top @@ -674,7 +674,7 @@ PluggableMap.prototype.getTarget = function() { * @api */ PluggableMap.prototype.getTargetElement = function() { - var target = this.getTarget(); + const target = this.getTarget(); if (target !== undefined) { return typeof target === 'string' ? document.getElementById(target) : @@ -693,7 +693,7 @@ PluggableMap.prototype.getTargetElement = function() { * @api */ PluggableMap.prototype.getCoordinateFromPixel = function(pixel) { - var frameState = this.frameState_; + const frameState = this.frameState_; if (!frameState) { return null; } else { @@ -733,7 +733,7 @@ PluggableMap.prototype.getOverlays = function() { * @api */ PluggableMap.prototype.getOverlayById = function(id) { - var overlay = this.overlayIdIndex_[id.toString()]; + const overlay = this.overlayIdIndex_[id.toString()]; return overlay !== undefined ? overlay : null; }; @@ -770,7 +770,7 @@ PluggableMap.prototype.getLayerGroup = function() { * @api */ PluggableMap.prototype.getLayers = function() { - var layers = this.getLayerGroup().getLayers(); + const layers = this.getLayerGroup().getLayers(); return layers; }; @@ -783,12 +783,12 @@ PluggableMap.prototype.getLayers = function() { * @api */ PluggableMap.prototype.getPixelFromCoordinate = function(coordinate) { - var frameState = this.frameState_; + const frameState = this.frameState_; if (!frameState) { return null; } else { return _ol_transform_.apply(frameState.coordinateToPixelTransform, - coordinate.slice(0, 2)); + coordinate.slice(0, 2)); } }; @@ -873,7 +873,7 @@ PluggableMap.prototype.getOverlayContainerStopEvent = function() { PluggableMap.prototype.getTilePriority = function(tile, tileSourceKey, tileCenter, tileResolution) { // Filter out tiles at higher zoom levels than the current zoom level, or that // are outside the visible extent. - var frameState = this.frameState_; + const frameState = this.frameState_; if (!frameState || !(tileSourceKey in frameState.wantedTiles)) { return PriorityQueue.DROP; } @@ -886,8 +886,8 @@ PluggableMap.prototype.getTilePriority = function(tile, tileSourceKey, tileCente // between the center of the tile and the focus. The factor of 65536 means // that the prioritization should behave as desired for tiles up to // 65536 * Math.log(2) = 45426 pixels from the focus. - var deltaX = tileCenter[0] - frameState.focus[0]; - var deltaY = tileCenter[1] - frameState.focus[1]; + const deltaX = tileCenter[0] - frameState.focus[0]; + const deltaY = tileCenter[1] - frameState.focus[1]; return 65536 * Math.log(tileResolution) + Math.sqrt(deltaX * deltaX + deltaY * deltaY) / tileResolution; }; @@ -898,8 +898,8 @@ PluggableMap.prototype.getTilePriority = function(tile, tileSourceKey, tileCente * @param {string=} opt_type Type. */ PluggableMap.prototype.handleBrowserEvent = function(browserEvent, opt_type) { - var type = opt_type || browserEvent.type; - var mapBrowserEvent = new MapBrowserEvent(type, this, browserEvent); + const type = opt_type || browserEvent.type; + const mapBrowserEvent = new MapBrowserEvent(type, this, browserEvent); this.handleMapBrowserEvent(mapBrowserEvent); }; @@ -915,15 +915,15 @@ PluggableMap.prototype.handleMapBrowserEvent = function(mapBrowserEvent) { } this.focus_ = mapBrowserEvent.coordinate; mapBrowserEvent.frameState = this.frameState_; - var interactionsArray = this.getInteractions().getArray(); - var i; + const interactionsArray = this.getInteractions().getArray(); + let i; if (this.dispatchEvent(mapBrowserEvent) !== false) { for (i = interactionsArray.length - 1; i >= 0; i--) { - var interaction = interactionsArray[i]; + const interaction = interactionsArray[i]; if (!interaction.getActive()) { continue; } - var cont = interaction.handleEvent(mapBrowserEvent); + const cont = interaction.handleEvent(mapBrowserEvent); if (!cont) { break; } @@ -937,7 +937,7 @@ PluggableMap.prototype.handleMapBrowserEvent = function(mapBrowserEvent) { */ PluggableMap.prototype.handlePostRender = function() { - var frameState = this.frameState_; + const frameState = this.frameState_; // Manage the tile queue // Image loads are expensive and a limited resource, so try to use them @@ -948,12 +948,12 @@ PluggableMap.prototype.handlePostRender = function() { // the maximum number of loads per frame and limit the number of parallel // tile loads to remain reactive to view changes and to reduce the chance of // loading tiles that will quickly disappear from view. - var tileQueue = this.tileQueue_; + const tileQueue = this.tileQueue_; if (!tileQueue.isEmpty()) { - var maxTotalLoading = 16; - var maxNewLoads = maxTotalLoading; + let maxTotalLoading = 16; + let maxNewLoads = maxTotalLoading; if (frameState) { - var hints = frameState.viewHints; + const hints = frameState.viewHints; if (hints[ViewHint.ANIMATING]) { maxTotalLoading = this.loadTilesWhileAnimating_ ? 8 : 0; maxNewLoads = 2; @@ -969,8 +969,8 @@ PluggableMap.prototype.handlePostRender = function() { } } - var postRenderFunctions = this.postRenderFunctions_; - var i, ii; + const postRenderFunctions = this.postRenderFunctions_; + let i, ii; for (i = 0, ii = postRenderFunctions.length; i < ii; ++i) { postRenderFunctions[i](this, frameState); } @@ -995,13 +995,13 @@ PluggableMap.prototype.handleTargetChanged_ = function() { // If it's not now an Element we remove the viewport from the DOM. // If it's an Element we append the viewport element to it. - var targetElement; + let targetElement; if (this.getTarget()) { targetElement = this.getTargetElement(); } if (this.keyHandlerKeys_) { - for (var i = 0, ii = this.keyHandlerKeys_.length; i < ii; ++i) { + for (let i = 0, ii = this.keyHandlerKeys_.length; i < ii; ++i) { _ol_events_.unlistenByKey(this.keyHandlerKeys_[i]); } this.keyHandlerKeys_ = null; @@ -1012,25 +1012,25 @@ PluggableMap.prototype.handleTargetChanged_ = function() { removeNode(this.viewport_); if (this.handleResize_ !== undefined) { window.removeEventListener(EventType.RESIZE, - this.handleResize_, false); + this.handleResize_, false); this.handleResize_ = undefined; } } else { targetElement.appendChild(this.viewport_); - var keyboardEventTarget = !this.keyboardEventTarget_ ? + const keyboardEventTarget = !this.keyboardEventTarget_ ? targetElement : this.keyboardEventTarget_; this.keyHandlerKeys_ = [ _ol_events_.listen(keyboardEventTarget, EventType.KEYDOWN, - this.handleBrowserEvent, this), + this.handleBrowserEvent, this), _ol_events_.listen(keyboardEventTarget, EventType.KEYPRESS, - this.handleBrowserEvent, this) + this.handleBrowserEvent, this) ]; if (!this.handleResize_) { this.handleResize_ = this.updateSize.bind(this); window.addEventListener(EventType.RESIZE, - this.handleResize_, false); + this.handleResize_, false); } } @@ -1068,15 +1068,15 @@ PluggableMap.prototype.handleViewChanged_ = function() { _ol_events_.unlistenByKey(this.viewChangeListenerKey_); this.viewChangeListenerKey_ = null; } - var view = this.getView(); + const view = this.getView(); if (view) { this.viewport_.setAttribute('data-view', getUid(view)); this.viewPropertyListenerKey_ = _ol_events_.listen( - view, ObjectEventType.PROPERTYCHANGE, - this.handleViewPropertyChanged_, this); + view, ObjectEventType.PROPERTYCHANGE, + this.handleViewPropertyChanged_, this); this.viewChangeListenerKey_ = _ol_events_.listen( - view, EventType.CHANGE, - this.handleViewPropertyChanged_, this); + view, EventType.CHANGE, + this.handleViewPropertyChanged_, this); } this.render(); }; @@ -1090,15 +1090,15 @@ PluggableMap.prototype.handleLayerGroupChanged_ = function() { this.layerGroupPropertyListenerKeys_.forEach(_ol_events_.unlistenByKey); this.layerGroupPropertyListenerKeys_ = null; } - var layerGroup = this.getLayerGroup(); + const layerGroup = this.getLayerGroup(); if (layerGroup) { this.layerGroupPropertyListenerKeys_ = [ _ol_events_.listen( - layerGroup, ObjectEventType.PROPERTYCHANGE, - this.render, this), + layerGroup, ObjectEventType.PROPERTYCHANGE, + this.render, this), _ol_events_.listen( - layerGroup, EventType.CHANGE, - this.render, this) + layerGroup, EventType.CHANGE, + this.render, this) ]; } this.render(); @@ -1132,7 +1132,7 @@ PluggableMap.prototype.renderSync = function() { PluggableMap.prototype.render = function() { if (this.animationDelayKey_ === undefined) { this.animationDelayKey_ = requestAnimationFrame( - this.animationDelay_); + this.animationDelay_); } }; @@ -1169,7 +1169,7 @@ PluggableMap.prototype.removeInteraction = function(interaction) { * @api */ PluggableMap.prototype.removeLayer = function(layer) { - var layers = this.getLayerGroup().getLayers(); + const layers = this.getLayerGroup().getLayers(); return layers.remove(layer); }; @@ -1191,24 +1191,24 @@ PluggableMap.prototype.removeOverlay = function(overlay) { * @private */ PluggableMap.prototype.renderFrame_ = function(time) { - var i, ii, viewState; + let i, ii, viewState; - var size = this.getSize(); - var view = this.getView(); - var extent = createEmpty(); - var previousFrameState = this.frameState_; + const size = this.getSize(); + const view = this.getView(); + const extent = createEmpty(); + const previousFrameState = this.frameState_; /** @type {?olx.FrameState} */ - var frameState = null; + let frameState = null; if (size !== undefined && _ol_size_.hasArea(size) && view && view.isDef()) { - var viewHints = view.getHints(this.frameState_ ? this.frameState_.viewHints : undefined); - var layerStatesArray = this.getLayerGroup().getLayerStatesArray(); - var layerStates = {}; + const viewHints = view.getHints(this.frameState_ ? this.frameState_.viewHints : undefined); + const layerStatesArray = this.getLayerGroup().getLayerStatesArray(); + const layerStates = {}; for (i = 0, ii = layerStatesArray.length; i < ii; ++i) { layerStates[getUid(layerStatesArray[i].layer)] = layerStatesArray[i]; } viewState = view.getState(); - var center = viewState.center; - var pixelResolution = viewState.resolution / this.pixelRatio_; + const center = viewState.center; + const pixelResolution = viewState.resolution / this.pixelRatio_; center[0] = Math.round(center[0] / pixelResolution) * pixelResolution; center[1] = Math.round(center[1] / pixelResolution) * pixelResolution; frameState = /** @type {olx.FrameState} */ ({ @@ -1235,7 +1235,7 @@ PluggableMap.prototype.renderFrame_ = function(time) { if (frameState) { frameState.extent = getForViewAndSize(viewState.center, - viewState.resolution, viewState.rotation, frameState.size, extent); + viewState.resolution, viewState.rotation, frameState.size, extent); } this.frameState_ = frameState; @@ -1246,33 +1246,33 @@ PluggableMap.prototype.renderFrame_ = function(time) { this.render(); } Array.prototype.push.apply( - this.postRenderFunctions_, frameState.postRenderFunctions); + this.postRenderFunctions_, frameState.postRenderFunctions); if (previousFrameState) { - var moveStart = !this.previousExtent_ || + const moveStart = !this.previousExtent_ || (!isEmpty(this.previousExtent_) && !equals(frameState.extent, this.previousExtent_)); if (moveStart) { this.dispatchEvent( - new MapEvent(MapEventType.MOVESTART, this, previousFrameState)); + new MapEvent(MapEventType.MOVESTART, this, previousFrameState)); this.previousExtent_ = createOrUpdateEmpty(this.previousExtent_); } } - var idle = this.previousExtent_ && + const idle = this.previousExtent_ && !frameState.viewHints[ViewHint.ANIMATING] && !frameState.viewHints[ViewHint.INTERACTING] && !equals(frameState.extent, this.previousExtent_); if (idle) { this.dispatchEvent( - new MapEvent(MapEventType.MOVEEND, this, frameState)); + new MapEvent(MapEventType.MOVEEND, this, frameState)); clone(frameState.extent, this.previousExtent_); } } this.dispatchEvent( - new MapEvent(MapEventType.POSTRENDER, this, frameState)); + new MapEvent(MapEventType.POSTRENDER, this, frameState)); setTimeout(this.handlePostRender.bind(this), 0); @@ -1329,7 +1329,7 @@ PluggableMap.prototype.setView = function(view) { * @param {ol.Feature} feature Feature. */ PluggableMap.prototype.skipFeature = function(feature) { - var featureUid = getUid(feature).toString(); + const featureUid = getUid(feature).toString(); this.skippedFeatureUids_[featureUid] = true; this.render(); }; @@ -1341,12 +1341,12 @@ PluggableMap.prototype.skipFeature = function(feature) { * @api */ PluggableMap.prototype.updateSize = function() { - var targetElement = this.getTargetElement(); + const targetElement = this.getTargetElement(); if (!targetElement) { this.setSize(undefined); } else { - var computedStyle = getComputedStyle(targetElement); + const computedStyle = getComputedStyle(targetElement); this.setSize([ targetElement.offsetWidth - parseFloat(computedStyle['borderLeftWidth']) - @@ -1367,7 +1367,7 @@ PluggableMap.prototype.updateSize = function() { * @param {ol.Feature} feature Feature. */ PluggableMap.prototype.unskipFeature = function(feature) { - var featureUid = getUid(feature).toString(); + const featureUid = getUid(feature).toString(); delete this.skippedFeatureUids_[featureUid]; this.render(); }; @@ -1377,7 +1377,7 @@ PluggableMap.prototype.unskipFeature = function(feature) { * @type {Array.} * @const */ -var DEFAULT_RENDERER_TYPES = [ +const DEFAULT_RENDERER_TYPES = [ RendererType.CANVAS, RendererType.WEBGL ]; @@ -1392,7 +1392,7 @@ function createOptionsInternal(options) { /** * @type {Element|Document} */ - var keyboardEventTarget = null; + let keyboardEventTarget = null; if (options.keyboardEventTarget !== undefined) { keyboardEventTarget = typeof options.keyboardEventTarget === 'string' ? document.getElementById(options.keyboardEventTarget) : @@ -1402,9 +1402,9 @@ function createOptionsInternal(options) { /** * @type {Object.} */ - var values = {}; + const values = {}; - var layerGroup = (options.layers instanceof LayerGroup) ? + const layerGroup = (options.layers instanceof LayerGroup) ? options.layers : new LayerGroup({layers: options.layers}); values[MapProperty.LAYERGROUP] = layerGroup; @@ -1416,7 +1416,7 @@ function createOptionsInternal(options) { /** * @type {Array.} */ - var rendererTypes; + let rendererTypes; if (options.renderer !== undefined) { if (Array.isArray(options.renderer)) { @@ -1436,13 +1436,13 @@ function createOptionsInternal(options) { /** * @type {olx.MapRendererPlugin} */ - var mapRendererPlugin; + let mapRendererPlugin; - var mapRendererPlugins = getMapRendererPlugins(); - outer: for (var i = 0, ii = rendererTypes.length; i < ii; ++i) { - var rendererType = rendererTypes[i]; - for (var j = 0, jj = mapRendererPlugins.length; j < jj; ++j) { - var candidate = mapRendererPlugins[j]; + const mapRendererPlugins = getMapRendererPlugins(); + outer: for (let i = 0, ii = rendererTypes.length; i < ii; ++i) { + const rendererType = rendererTypes[i]; + for (let j = 0, jj = mapRendererPlugins.length; j < jj; ++j) { + const candidate = mapRendererPlugins[j]; if (candidate['handles'](rendererType)) { mapRendererPlugin = candidate; break outer; @@ -1454,35 +1454,35 @@ function createOptionsInternal(options) { throw new Error('Unable to create a map renderer for types: ' + rendererTypes.join(', ')); } - var controls; + let controls; if (options.controls !== undefined) { if (Array.isArray(options.controls)) { controls = new Collection(options.controls.slice()); } else { assert(options.controls instanceof Collection, - 47); // Expected `controls` to be an array or an `ol.Collection` + 47); // Expected `controls` to be an array or an `ol.Collection` controls = options.controls; } } - var interactions; + let interactions; if (options.interactions !== undefined) { if (Array.isArray(options.interactions)) { interactions = new Collection(options.interactions.slice()); } else { assert(options.interactions instanceof Collection, - 48); // Expected `interactions` to be an array or an `ol.Collection` + 48); // Expected `interactions` to be an array or an `ol.Collection` interactions = options.interactions; } } - var overlays; + let overlays; if (options.overlays !== undefined) { if (Array.isArray(options.overlays)) { overlays = new Collection(options.overlays.slice()); } else { assert(options.overlays instanceof Collection, - 49); // Expected `overlays` to be an array or an `ol.Collection` + 49); // Expected `overlays` to be an array or an `ol.Collection` overlays = options.overlays; } } else { diff --git a/src/ol/ResolutionConstraint.js b/src/ol/ResolutionConstraint.js index 567d60a643..5b54b6a2e8 100644 --- a/src/ol/ResolutionConstraint.js +++ b/src/ol/ResolutionConstraint.js @@ -3,7 +3,7 @@ */ import {linearFindNearest} from './array.js'; import {clamp} from './math.js'; -var ResolutionConstraint = {}; +const ResolutionConstraint = {}; /** @@ -20,11 +20,11 @@ ResolutionConstraint.createSnapToResolutions = function(resolutions) { */ function(resolution, delta, direction) { if (resolution !== undefined) { - var z = linearFindNearest(resolutions, resolution, direction); + let z = linearFindNearest(resolutions, resolution, direction); z = clamp(z + delta, 0, resolutions.length - 1); - var index = Math.floor(z); + const index = Math.floor(z); if (z != index && index < resolutions.length - 1) { - var power = resolutions[index] / resolutions[index + 1]; + const power = resolutions[index] / resolutions[index + 1]; return resolutions[index] / Math.pow(power, z - index); } else { return resolutions[index]; @@ -53,10 +53,10 @@ ResolutionConstraint.createSnapToPower = function(power, maxResolution, opt_maxL */ function(resolution, delta, direction) { if (resolution !== undefined) { - var offset = -direction / 2 + 0.5; - var oldLevel = Math.floor( - Math.log(maxResolution / resolution) / Math.log(power) + offset); - var newLevel = Math.max(oldLevel + delta, 0); + const offset = -direction / 2 + 0.5; + const oldLevel = Math.floor( + Math.log(maxResolution / resolution) / Math.log(power) + offset); + let newLevel = Math.max(oldLevel + delta, 0); if (opt_maxLevel !== undefined) { newLevel = Math.min(newLevel, opt_maxLevel); } diff --git a/src/ol/RotationConstraint.js b/src/ol/RotationConstraint.js index 4bfab05c8f..caa99d38d5 100644 --- a/src/ol/RotationConstraint.js +++ b/src/ol/RotationConstraint.js @@ -2,7 +2,7 @@ * @module ol/RotationConstraint */ import {toRadians} from './math.js'; -var RotationConstraint = {}; +const RotationConstraint = {}; /** @@ -38,7 +38,7 @@ RotationConstraint.none = function(rotation, delta) { * @return {ol.RotationConstraintType} Rotation constraint. */ RotationConstraint.createSnapToN = function(n) { - var theta = 2 * Math.PI / n; + const theta = 2 * Math.PI / n; return ( /** * @param {number|undefined} rotation Rotation. @@ -61,7 +61,7 @@ RotationConstraint.createSnapToN = function(n) { * @return {ol.RotationConstraintType} Rotation constraint. */ RotationConstraint.createSnapToZero = function(opt_tolerance) { - var tolerance = opt_tolerance || toRadians(5); + const tolerance = opt_tolerance || toRadians(5); return ( /** * @param {number|undefined} rotation Rotation. diff --git a/src/ol/Tile.js b/src/ol/Tile.js index 4497d29423..7399ccd868 100644 --- a/src/ol/Tile.js +++ b/src/ol/Tile.js @@ -18,10 +18,10 @@ import EventType from './events/EventType.js'; * @param {ol.TileState} state State. * @param {olx.TileOptions=} opt_options Tile options. */ -var Tile = function(tileCoord, state, opt_options) { +const Tile = function(tileCoord, state, opt_options) { EventTarget.call(this); - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @type {ol.TileCoord} @@ -95,7 +95,7 @@ Tile.prototype.getInterimTile = function() { //empty chain return this; } - var tile = this.interimTile; + let tile = this.interimTile; // find the first loaded tile and return it. Since the chain is sorted in // decreasing order of creation time, there is no need to search the remainder @@ -121,8 +121,8 @@ Tile.prototype.refreshInterimChain = function() { return; } - var tile = this.interimTile; - var prev = this; + let tile = this.interimTile; + let prev = this; do { if (tile.getState() == TileState.LOADED) { @@ -191,7 +191,7 @@ Tile.prototype.getAlpha = function(id, time) { return 1; } - var start = this.transitionStarts_[id]; + let start = this.transitionStarts_[id]; if (!start) { start = time; this.transitionStarts_[id] = start; @@ -199,7 +199,7 @@ Tile.prototype.getAlpha = function(id, time) { return 1; } - var delta = time - start + (1000 / 60); // avoid rendering at 0 + const delta = time - start + (1000 / 60); // avoid rendering at 0 if (delta >= this.transition_) { return 1; } diff --git a/src/ol/TileCache.js b/src/ol/TileCache.js index e6eeaacc71..6dea78fe11 100644 --- a/src/ol/TileCache.js +++ b/src/ol/TileCache.js @@ -11,7 +11,7 @@ import _ol_tilecoord_ from './tilecoord.js'; * @param {number=} opt_highWaterMark High water mark. * @struct */ -var TileCache = function(opt_highWaterMark) { +const TileCache = function(opt_highWaterMark) { LRUCache.call(this, opt_highWaterMark); @@ -24,7 +24,7 @@ inherits(TileCache, LRUCache); * @param {Object.} usedTiles Used tiles. */ TileCache.prototype.expireCache = function(usedTiles) { - var tile, zKey; + let tile, zKey; while (this.canExpireCache()) { tile = this.peekLast(); zKey = tile.tileCoord[0].toString(); @@ -44,9 +44,9 @@ TileCache.prototype.pruneExceptNewestZ = function() { if (this.getCount() === 0) { return; } - var key = this.peekFirstKey(); - var tileCoord = _ol_tilecoord_.fromKey(key); - var z = tileCoord[0]; + const key = this.peekFirstKey(); + const tileCoord = _ol_tilecoord_.fromKey(key); + const z = tileCoord[0]; this.forEach(function(tile) { if (tile.tileCoord[0] !== z) { this.remove(_ol_tilecoord_.getKey(tile.tileCoord)); diff --git a/src/ol/TileQueue.js b/src/ol/TileQueue.js index 1788dd0eff..2e26d5bcfc 100644 --- a/src/ol/TileQueue.js +++ b/src/ol/TileQueue.js @@ -16,24 +16,24 @@ import PriorityQueue from './structs/PriorityQueue.js'; * Function called on each tile change event. * @struct */ -var TileQueue = function(tilePriorityFunction, tileChangeCallback) { +const TileQueue = function(tilePriorityFunction, tileChangeCallback) { PriorityQueue.call( - this, - /** + this, + /** * @param {Array} element Element. * @return {number} Priority. */ - function(element) { - return tilePriorityFunction.apply(null, element); - }, - /** + function(element) { + return tilePriorityFunction.apply(null, element); + }, + /** * @param {Array} element Element. * @return {string} Key. */ - function(element) { - return /** @type {ol.Tile} */ (element[0]).getKey(); - }); + function(element) { + return /** @type {ol.Tile} */ (element[0]).getKey(); + }); /** * @private @@ -62,11 +62,11 @@ inherits(TileQueue, PriorityQueue); * @inheritDoc */ TileQueue.prototype.enqueue = function(element) { - var added = PriorityQueue.prototype.enqueue.call(this, element); + const added = PriorityQueue.prototype.enqueue.call(this, element); if (added) { - var tile = element[0]; + const tile = element[0]; _ol_events_.listen(tile, EventType.CHANGE, - this.handleTileChange, this); + this.handleTileChange, this); } return added; }; @@ -85,13 +85,13 @@ TileQueue.prototype.getTilesLoading = function() { * @protected */ TileQueue.prototype.handleTileChange = function(event) { - var tile = /** @type {ol.Tile} */ (event.target); - var state = tile.getState(); + const tile = /** @type {ol.Tile} */ (event.target); + const state = tile.getState(); if (state === TileState.LOADED || state === TileState.ERROR || state === TileState.EMPTY || state === TileState.ABORT) { _ol_events_.unlisten(tile, EventType.CHANGE, - this.handleTileChange, this); - var tileKey = tile.getKey(); + this.handleTileChange, this); + const tileKey = tile.getKey(); if (tileKey in this.tilesLoadingKeys_) { delete this.tilesLoadingKeys_[tileKey]; --this.tilesLoading_; @@ -106,9 +106,9 @@ TileQueue.prototype.handleTileChange = function(event) { * @param {number} maxNewLoads Maximum number of new tiles to load. */ TileQueue.prototype.loadMoreTiles = function(maxTotalLoading, maxNewLoads) { - var newLoads = 0; - var abortedTiles = false; - var state, tile, tileKey; + let newLoads = 0; + let abortedTiles = false; + let state, tile, tileKey; while (this.tilesLoading_ < maxTotalLoading && newLoads < maxNewLoads && this.getCount() > 0) { tile = /** @type {ol.Tile} */ (this.dequeue()[0]); diff --git a/src/ol/TileRange.js b/src/ol/TileRange.js index b4bed1f182..57f3930df3 100644 --- a/src/ol/TileRange.js +++ b/src/ol/TileRange.js @@ -12,7 +12,7 @@ * @param {number} maxY Maximum Y. * @struct */ -var TileRange = function(minX, maxX, minY, maxY) { +const TileRange = function(minX, maxX, minY, maxY) { /** * @type {number} diff --git a/src/ol/VectorImageTile.js b/src/ol/VectorImageTile.js index 6dcb4576ad..c53e148516 100644 --- a/src/ol/VectorImageTile.js +++ b/src/ol/VectorImageTile.js @@ -32,9 +32,9 @@ import {loadFeaturesXhr} from './featureloader.js'; * Function to call when a source tile's state changes. * @param {olx.TileOptions=} opt_options Tile options. */ -var VectorImageTile = function(tileCoord, state, sourceRevision, format, - tileLoadFunction, urlTileCoord, tileUrlFunction, sourceTileGrid, tileGrid, - sourceTiles, pixelRatio, projection, tileClass, handleTileChange, opt_options) { +const VectorImageTile = function(tileCoord, state, sourceRevision, format, + tileLoadFunction, urlTileCoord, tileUrlFunction, sourceTileGrid, tileGrid, + sourceTiles, pixelRatio, projection, tileClass, handleTileChange, opt_options) { Tile.call(this, tileCoord, state, opt_options); @@ -89,29 +89,29 @@ var VectorImageTile = function(tileCoord, state, sourceRevision, format, this.sourceTileListenerKeys_ = []; if (urlTileCoord) { - var extent = tileGrid.getTileCoordExtent(urlTileCoord); - var resolution = tileGrid.getResolution(tileCoord[0]); - var sourceZ = sourceTileGrid.getZForResolution(resolution); + const extent = tileGrid.getTileCoordExtent(urlTileCoord); + const resolution = tileGrid.getResolution(tileCoord[0]); + const sourceZ = sourceTileGrid.getZForResolution(resolution); sourceTileGrid.forEachTileCoord(extent, sourceZ, function(sourceTileCoord) { - var sharedExtent = getIntersection(extent, - sourceTileGrid.getTileCoordExtent(sourceTileCoord)); - var sourceExtent = sourceTileGrid.getExtent(); + let sharedExtent = getIntersection(extent, + sourceTileGrid.getTileCoordExtent(sourceTileCoord)); + const sourceExtent = sourceTileGrid.getExtent(); if (sourceExtent) { sharedExtent = getIntersection(sharedExtent, sourceExtent); } if (getWidth(sharedExtent) / resolution >= 0.5 && getHeight(sharedExtent) / resolution >= 0.5) { // only include source tile if overlap is at least 1 pixel - var sourceTileKey = sourceTileCoord.toString(); - var sourceTile = sourceTiles[sourceTileKey]; + const sourceTileKey = sourceTileCoord.toString(); + let sourceTile = sourceTiles[sourceTileKey]; if (!sourceTile) { - var tileUrl = tileUrlFunction(sourceTileCoord, pixelRatio, projection); + const tileUrl = tileUrlFunction(sourceTileCoord, pixelRatio, projection); sourceTile = sourceTiles[sourceTileKey] = new tileClass(sourceTileCoord, - tileUrl == undefined ? TileState.EMPTY : TileState.IDLE, - tileUrl == undefined ? '' : tileUrl, - format, tileLoadFunction); + tileUrl == undefined ? TileState.EMPTY : TileState.IDLE, + tileUrl == undefined ? '' : tileUrl, + format, tileLoadFunction); this.sourceTileListenerKeys_.push( - _ol_events_.listen(sourceTile, EventType.CHANGE, handleTileChange)); + _ol_events_.listen(sourceTile, EventType.CHANGE, handleTileChange)); } sourceTile.consumers++; this.tileKeys.push(sourceTileKey); @@ -134,9 +134,9 @@ VectorImageTile.prototype.disposeInternal = function() { this.interimTile.dispose(); } - for (var i = 0, ii = this.tileKeys.length; i < ii; ++i) { - var sourceTileKey = this.tileKeys[i]; - var sourceTile = this.getTile(sourceTileKey); + for (let i = 0, ii = this.tileKeys.length; i < ii; ++i) { + const sourceTileKey = this.tileKeys[i]; + const sourceTile = this.getTile(sourceTileKey); sourceTile.consumers--; if (sourceTile.consumers == 0) { delete this.sourceTiles_[sourceTileKey]; @@ -158,7 +158,7 @@ VectorImageTile.prototype.disposeInternal = function() { * @return {CanvasRenderingContext2D} The rendering context. */ VectorImageTile.prototype.getContext = function(layer) { - var key = getUid(layer).toString(); + const key = getUid(layer).toString(); if (!(key in this.context_)) { this.context_[key] = createCanvasContext2D(); } @@ -182,7 +182,7 @@ VectorImageTile.prototype.getImage = function(layer) { * @return {ol.TileReplayState} The replay state. */ VectorImageTile.prototype.getReplayState = function(layer) { - var key = getUid(layer).toString(); + const key = getUid(layer).toString(); if (!(key in this.replayState_)) { this.replayState_[key] = { dirty: false, @@ -218,27 +218,27 @@ VectorImageTile.prototype.getTile = function(tileKey) { VectorImageTile.prototype.load = function() { // Source tiles with LOADED state - we just count them because once they are // loaded, we're no longer listening to state changes. - var leftToLoad = 0; + let leftToLoad = 0; // Source tiles with ERROR state - we track them because they can still have // an ERROR state after another load attempt. - var errorSourceTiles = {}; + const errorSourceTiles = {}; if (this.state == TileState.IDLE) { this.setState(TileState.LOADING); } if (this.state == TileState.LOADING) { this.tileKeys.forEach(function(sourceTileKey) { - var sourceTile = this.getTile(sourceTileKey); + const sourceTile = this.getTile(sourceTileKey); if (sourceTile.state == TileState.IDLE) { sourceTile.setLoader(this.loader_); sourceTile.load(); } if (sourceTile.state == TileState.LOADING) { - var key = _ol_events_.listen(sourceTile, EventType.CHANGE, function(e) { - var state = sourceTile.getState(); + const key = _ol_events_.listen(sourceTile, EventType.CHANGE, function(e) { + const state = sourceTile.getState(); if (state == TileState.LOADED || state == TileState.ERROR) { - var uid = getUid(sourceTile); + const uid = getUid(sourceTile); if (state == TileState.ERROR) { errorSourceTiles[uid] = true; } else { @@ -265,10 +265,10 @@ VectorImageTile.prototype.load = function() { * @private */ VectorImageTile.prototype.finishLoading_ = function() { - var loaded = this.tileKeys.length; - var empty = 0; - for (var i = loaded - 1; i >= 0; --i) { - var state = this.getTile(this.tileKeys[i]).getState(); + let loaded = this.tileKeys.length; + let empty = 0; + for (let i = loaded - 1; i >= 0; --i) { + const state = this.getTile(this.tileKeys[i]).getState(); if (state != TileState.LOADED) { --loaded; } @@ -293,6 +293,6 @@ export default VectorImageTile; * @param {string} url URL. */ export function defaultLoadFunction(tile, url) { - var loader = loadFeaturesXhr(url, tile.getFormat(), tile.onLoad.bind(tile), tile.onError.bind(tile)); + const loader = loadFeaturesXhr(url, tile.getFormat(), tile.onLoad.bind(tile), tile.onError.bind(tile)); tile.setLoader(loader); } diff --git a/src/ol/VectorTile.js b/src/ol/VectorTile.js index c5830c6231..d15204ba54 100644 --- a/src/ol/VectorTile.js +++ b/src/ol/VectorTile.js @@ -15,7 +15,7 @@ import TileState from './TileState.js'; * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function. * @param {olx.TileOptions=} opt_options Tile options. */ -var VectorTile = function(tileCoord, state, src, format, tileLoadFunction, opt_options) { +const VectorTile = function(tileCoord, state, src, format, tileLoadFunction, opt_options) { Tile.call(this, tileCoord, state, opt_options); @@ -81,7 +81,7 @@ inherits(VectorTile, Tile); * @const * @type {ol.Extent} */ -var DEFAULT_EXTENT = [0, 0, 4096, 4096]; +const DEFAULT_EXTENT = [0, 0, 4096, 4096]; /** diff --git a/src/ol/View.js b/src/ol/View.js index 7c93134131..d3f30e86e8 100644 --- a/src/ol/View.js +++ b/src/ol/View.js @@ -26,7 +26,7 @@ import Units from './proj/Units.js'; /** * @type {number} Default min zoom level for the map view. */ -var DEFAULT_MIN_ZOOM = 0; +const DEFAULT_MIN_ZOOM = 0; /** @@ -86,10 +86,10 @@ var DEFAULT_MIN_ZOOM = 0; * @param {olx.ViewOptions=} opt_options View options. * @api */ -var View = function(opt_options) { +const View = function(opt_options) { BaseObject.call(this); - var options = _ol_obj_.assign({}, opt_options); + const options = _ol_obj_.assign({}, opt_options); /** * @private @@ -133,12 +133,12 @@ View.prototype.applyOptions_ = function(options) { /** * @type {Object.} */ - var properties = {}; + const properties = {}; properties[ViewProperty.CENTER] = options.center !== undefined ? options.center : null; - var resolutionConstraintInfo = View.createResolutionConstraint_( - options); + const resolutionConstraintInfo = View.createResolutionConstraint_( + options); /** * @private @@ -170,9 +170,9 @@ View.prototype.applyOptions_ = function(options) { */ this.minZoom_ = resolutionConstraintInfo.minZoom; - var centerConstraint = View.createCenterConstraint_(options); - var resolutionConstraint = resolutionConstraintInfo.constraint; - var rotationConstraint = View.createRotationConstraint_(options); + const centerConstraint = View.createCenterConstraint_(options); + const resolutionConstraint = resolutionConstraintInfo.constraint; + const rotationConstraint = View.createRotationConstraint_(options); /** * @private @@ -188,12 +188,12 @@ View.prototype.applyOptions_ = function(options) { properties[ViewProperty.RESOLUTION] = options.resolution; } else if (options.zoom !== undefined) { properties[ViewProperty.RESOLUTION] = this.constrainResolution( - this.maxResolution_, options.zoom - this.minZoom_); + this.maxResolution_, options.zoom - this.minZoom_); if (this.resolutions_) { // in case map zoom is out of min/max zoom range properties[ViewProperty.RESOLUTION] = clamp( - Number(this.getResolution() || properties[ViewProperty.RESOLUTION]), - this.minResolution_, this.maxResolution_); + Number(this.getResolution() || properties[ViewProperty.RESOLUTION]), + this.minResolution_, this.maxResolution_); } } properties[ViewProperty.ROTATION] = @@ -217,7 +217,7 @@ View.prototype.applyOptions_ = function(options) { * @return {olx.ViewOptions} New options updated with the current view state. */ View.prototype.getUpdatedOptions_ = function(newOptions) { - var options = _ol_obj_.assign({}, this.options_); + const options = _ol_obj_.assign({}, this.options_); // preserve resolution (or zoom) if (options.resolution !== undefined) { @@ -270,15 +270,15 @@ View.prototype.getUpdatedOptions_ = function(newOptions) { * @api */ View.prototype.animate = function(var_args) { - var animationCount = arguments.length; - var callback; + let animationCount = arguments.length; + let callback; if (animationCount > 1 && typeof arguments[animationCount - 1] === 'function') { callback = arguments[animationCount - 1]; --animationCount; } if (!this.isDef()) { // if view properties are not yet set, shortcut to the final state - var state = arguments[animationCount - 1]; + const state = arguments[animationCount - 1]; if (state.center) { this.setCenter(state.center); } @@ -293,15 +293,15 @@ View.prototype.animate = function(var_args) { } return; } - var start = Date.now(); - var center = this.getCenter().slice(); - var resolution = this.getResolution(); - var rotation = this.getRotation(); - var series = []; - for (var i = 0; i < animationCount; ++i) { - var options = /** @type {olx.AnimationOptions} */ (arguments[i]); + let start = Date.now(); + let center = this.getCenter().slice(); + let resolution = this.getResolution(); + let rotation = this.getRotation(); + const series = []; + for (let i = 0; i < animationCount; ++i) { + const options = /** @type {olx.AnimationOptions} */ (arguments[i]); - var animation = /** @type {ol.ViewAnimation} */ ({ + const animation = /** @type {ol.ViewAnimation} */ ({ start: start, complete: false, anchor: options.anchor, @@ -318,7 +318,7 @@ View.prototype.animate = function(var_args) { if (options.zoom !== undefined) { animation.sourceResolution = resolution; animation.targetResolution = this.constrainResolution( - this.maxResolution_, options.zoom - this.minZoom_, 0); + this.maxResolution_, options.zoom - this.minZoom_, 0); resolution = animation.targetResolution; } else if (options.resolution) { animation.sourceResolution = resolution; @@ -328,7 +328,7 @@ View.prototype.animate = function(var_args) { if (options.rotation !== undefined) { animation.sourceRotation = rotation; - var delta = modulo(options.rotation - rotation + Math.PI, 2 * Math.PI) - Math.PI; + const delta = modulo(options.rotation - rotation + Math.PI, 2 * Math.PI) - Math.PI; animation.targetRotation = rotation + delta; rotation = animation.targetRotation; } @@ -376,8 +376,8 @@ View.prototype.getInteracting = function() { */ View.prototype.cancelAnimations = function() { this.setHint(ViewHint.ANIMATING, -this.hints_[ViewHint.ANIMATING]); - for (var i = 0, ii = this.animations_.length; i < ii; ++i) { - var series = this.animations_[i]; + for (let i = 0, ii = this.animations_.length; i < ii; ++i) { + const series = this.animations_[i]; if (series[0].callback) { series[0].callback(false); } @@ -396,51 +396,51 @@ View.prototype.updateAnimations_ = function() { if (!this.getAnimating()) { return; } - var now = Date.now(); - var more = false; - for (var i = this.animations_.length - 1; i >= 0; --i) { - var series = this.animations_[i]; - var seriesComplete = true; - for (var j = 0, jj = series.length; j < jj; ++j) { - var animation = series[j]; + const now = Date.now(); + let more = false; + for (let i = this.animations_.length - 1; i >= 0; --i) { + const series = this.animations_[i]; + let seriesComplete = true; + for (let j = 0, jj = series.length; j < jj; ++j) { + const animation = series[j]; if (animation.complete) { continue; } - var elapsed = now - animation.start; - var fraction = animation.duration > 0 ? elapsed / animation.duration : 1; + const elapsed = now - animation.start; + let fraction = animation.duration > 0 ? elapsed / animation.duration : 1; if (fraction >= 1) { animation.complete = true; fraction = 1; } else { seriesComplete = false; } - var progress = animation.easing(fraction); + const progress = animation.easing(fraction); if (animation.sourceCenter) { - var x0 = animation.sourceCenter[0]; - var y0 = animation.sourceCenter[1]; - var x1 = animation.targetCenter[0]; - var y1 = animation.targetCenter[1]; - var x = x0 + progress * (x1 - x0); - var y = y0 + progress * (y1 - y0); + const x0 = animation.sourceCenter[0]; + const y0 = animation.sourceCenter[1]; + const x1 = animation.targetCenter[0]; + const y1 = animation.targetCenter[1]; + const x = x0 + progress * (x1 - x0); + const y = y0 + progress * (y1 - y0); this.set(ViewProperty.CENTER, [x, y]); } if (animation.sourceResolution && animation.targetResolution) { - var resolution = progress === 1 ? + const resolution = progress === 1 ? animation.targetResolution : animation.sourceResolution + progress * (animation.targetResolution - animation.sourceResolution); if (animation.anchor) { this.set(ViewProperty.CENTER, - this.calculateCenterZoom(resolution, animation.anchor)); + this.calculateCenterZoom(resolution, animation.anchor)); } this.set(ViewProperty.RESOLUTION, resolution); } if (animation.sourceRotation !== undefined && animation.targetRotation !== undefined) { - var rotation = progress === 1 ? + const rotation = progress === 1 ? modulo(animation.targetRotation + Math.PI, 2 * Math.PI) - Math.PI : animation.sourceRotation + progress * (animation.targetRotation - animation.sourceRotation); if (animation.anchor) { this.set(ViewProperty.CENTER, - this.calculateCenterRotate(rotation, animation.anchor)); + this.calculateCenterRotate(rotation, animation.anchor)); } this.set(ViewProperty.ROTATION, rotation); } @@ -452,7 +452,7 @@ View.prototype.updateAnimations_ = function() { if (seriesComplete) { this.animations_[i] = null; this.setHint(ViewHint.ANIMATING, -1); - var callback = series[0].callback; + const callback = series[0].callback; if (callback) { callback(true); } @@ -471,8 +471,8 @@ View.prototype.updateAnimations_ = function() { * @return {ol.Coordinate|undefined} Center for rotation and anchor. */ View.prototype.calculateCenterRotate = function(rotation, anchor) { - var center; - var currentCenter = this.getCenter(); + let center; + const currentCenter = this.getCenter(); if (currentCenter !== undefined) { center = [currentCenter[0] - anchor[0], currentCenter[1] - anchor[1]]; _ol_coordinate_.rotate(center, rotation - this.getRotation()); @@ -488,13 +488,13 @@ View.prototype.calculateCenterRotate = function(rotation, anchor) { * @return {ol.Coordinate|undefined} Center for resolution and anchor. */ View.prototype.calculateCenterZoom = function(resolution, anchor) { - var center; - var currentCenter = this.getCenter(); - var currentResolution = this.getResolution(); + let center; + const currentCenter = this.getCenter(); + const currentResolution = this.getResolution(); if (currentCenter !== undefined && currentResolution !== undefined) { - var x = anchor[0] - + const x = anchor[0] - resolution * (anchor[0] - currentCenter[0]) / currentResolution; - var y = anchor[1] - + const y = anchor[1] - resolution * (anchor[1] - currentCenter[1]) / currentResolution; center = [x, y]; } @@ -507,11 +507,11 @@ View.prototype.calculateCenterZoom = function(resolution, anchor) { * @return {ol.Size} Viewport size or `[100, 100]` when no viewport is found. */ View.prototype.getSizeFromViewport_ = function() { - var size = [100, 100]; - var selector = '.ol-viewport[data-view="' + getUid(this) + '"]'; - var element = document.querySelector(selector); + const size = [100, 100]; + const selector = '.ol-viewport[data-view="' + getUid(this) + '"]'; + const element = document.querySelector(selector); if (element) { - var metrics = getComputedStyle(element); + const metrics = getComputedStyle(element); size[0] = parseInt(metrics.width, 10); size[1] = parseInt(metrics.height, 10); } @@ -539,9 +539,9 @@ View.prototype.constrainCenter = function(center) { * @api */ View.prototype.constrainResolution = function( - resolution, opt_delta, opt_direction) { - var delta = opt_delta || 0; - var direction = opt_direction || 0; + resolution, opt_delta, opt_direction) { + const delta = opt_delta || 0; + const direction = opt_direction || 0; return this.constraints_.resolution(resolution, delta, direction); }; @@ -554,7 +554,7 @@ View.prototype.constrainResolution = function( * @api */ View.prototype.constrainRotation = function(rotation, opt_delta) { - var delta = opt_delta || 0; + const delta = opt_delta || 0; return this.constraints_.rotation(rotation, delta); }; @@ -606,12 +606,12 @@ View.prototype.getHints = function(opt_hints) { * @api */ View.prototype.calculateExtent = function(opt_size) { - var size = opt_size || this.getSizeFromViewport_(); - var center = /** @type {!ol.Coordinate} */ (this.getCenter()); + const size = opt_size || this.getSizeFromViewport_(); + const center = /** @type {!ol.Coordinate} */ (this.getCenter()); assert(center, 1); // The view center is not defined - var resolution = /** @type {!number} */ (this.getResolution()); + const resolution = /** @type {!number} */ (this.getResolution()); assert(resolution !== undefined, 2); // The view resolution is not defined - var rotation = /** @type {!number} */ (this.getRotation()); + const rotation = /** @type {!number} */ (this.getRotation()); assert(rotation !== undefined, 3); // The view rotation is not defined return getForViewAndSize(center, resolution, rotation, size); @@ -721,9 +721,9 @@ View.prototype.getResolutions = function() { * @api */ View.prototype.getResolutionForExtent = function(extent, opt_size) { - var size = opt_size || this.getSizeFromViewport_(); - var xResolution = getWidth(extent) / size[0]; - var yResolution = getHeight(extent) / size[1]; + const size = opt_size || this.getSizeFromViewport_(); + const xResolution = getWidth(extent) / size[0]; + const yResolution = getHeight(extent) / size[1]; return Math.max(xResolution, yResolution); }; @@ -735,17 +735,17 @@ View.prototype.getResolutionForExtent = function(extent, opt_size) { * @return {function(number): number} Resolution for value function. */ View.prototype.getResolutionForValueFunction = function(opt_power) { - var power = opt_power || 2; - var maxResolution = this.maxResolution_; - var minResolution = this.minResolution_; - var max = Math.log(maxResolution / minResolution) / Math.log(power); + const power = opt_power || 2; + const maxResolution = this.maxResolution_; + const minResolution = this.minResolution_; + const max = Math.log(maxResolution / minResolution) / Math.log(power); return ( /** * @param {number} value Value. * @return {number} Resolution. */ function(value) { - var resolution = maxResolution / Math.pow(power, value * max); + const resolution = maxResolution / Math.pow(power, value * max); return resolution; }); }; @@ -771,17 +771,17 @@ View.prototype.getRotation = function() { * @return {function(number): number} Value for resolution function. */ View.prototype.getValueForResolutionFunction = function(opt_power) { - var power = opt_power || 2; - var maxResolution = this.maxResolution_; - var minResolution = this.minResolution_; - var max = Math.log(maxResolution / minResolution) / Math.log(power); + const power = opt_power || 2; + const maxResolution = this.maxResolution_; + const minResolution = this.minResolution_; + const max = Math.log(maxResolution / minResolution) / Math.log(power); return ( /** * @param {number} resolution Resolution. * @return {number} Value. */ function(resolution) { - var value = + const value = (Math.log(maxResolution / resolution) / Math.log(power)) / max; return value; }); @@ -792,10 +792,10 @@ View.prototype.getValueForResolutionFunction = function(opt_power) { * @return {olx.ViewState} View state. */ View.prototype.getState = function() { - var center = /** @type {ol.Coordinate} */ (this.getCenter()); - var projection = this.getProjection(); - var resolution = /** @type {number} */ (this.getResolution()); - var rotation = this.getRotation(); + const center = /** @type {ol.Coordinate} */ (this.getCenter()); + const projection = this.getProjection(); + const resolution = /** @type {number} */ (this.getResolution()); + const rotation = this.getRotation(); return /** @type {olx.ViewState} */ ({ center: center.slice(), projection: projection !== undefined ? projection : null, @@ -814,8 +814,8 @@ View.prototype.getState = function() { * @api */ View.prototype.getZoom = function() { - var zoom; - var resolution = this.getResolution(); + let zoom; + const resolution = this.getResolution(); if (resolution !== undefined) { zoom = this.getZoomForResolution(resolution); } @@ -830,10 +830,10 @@ View.prototype.getZoom = function() { * @api */ View.prototype.getZoomForResolution = function(resolution) { - var offset = this.minZoom_ || 0; - var max, zoomFactor; + let offset = this.minZoom_ || 0; + let max, zoomFactor; if (this.resolutions_) { - var nearest = linearFindNearest(this.resolutions_, resolution, 1); + const nearest = linearFindNearest(this.resolutions_, resolution, 1); offset = nearest; max = this.resolutions_[nearest]; if (nearest == this.resolutions_.length - 1) { @@ -857,7 +857,7 @@ View.prototype.getZoomForResolution = function(resolution) { */ View.prototype.getResolutionForZoom = function(zoom) { return /** @type {number} */ (this.constrainResolution( - this.maxResolution_, zoom - this.minZoom_, 0)); + this.maxResolution_, zoom - this.minZoom_, 0)); }; @@ -872,18 +872,18 @@ View.prototype.getResolutionForZoom = function(zoom) { * @api */ View.prototype.fit = function(geometryOrExtent, opt_options) { - var options = opt_options || {}; - var size = options.size; + const options = opt_options || {}; + let size = options.size; if (!size) { size = this.getSizeFromViewport_(); } /** @type {ol.geom.SimpleGeometry} */ - var geometry; + let geometry; if (!(geometryOrExtent instanceof SimpleGeometry)) { assert(Array.isArray(geometryOrExtent), - 24); // Invalid extent or geometry provided as `geometry` + 24); // Invalid extent or geometry provided as `geometry` assert(!isEmpty(geometryOrExtent), - 25); // Cannot fit empty extent provided as `geometry` + 25); // Cannot fit empty extent provided as `geometry` geometry = polygonFromExtent(geometryOrExtent); } else if (geometryOrExtent.getType() === GeometryType.CIRCLE) { geometryOrExtent = geometryOrExtent.getExtent(); @@ -893,33 +893,33 @@ View.prototype.fit = function(geometryOrExtent, opt_options) { geometry = geometryOrExtent; } - var padding = options.padding !== undefined ? options.padding : [0, 0, 0, 0]; - var constrainResolution = options.constrainResolution !== undefined ? + const padding = options.padding !== undefined ? options.padding : [0, 0, 0, 0]; + const constrainResolution = options.constrainResolution !== undefined ? options.constrainResolution : true; - var nearest = options.nearest !== undefined ? options.nearest : false; - var minResolution; + const nearest = options.nearest !== undefined ? options.nearest : false; + let minResolution; if (options.minResolution !== undefined) { minResolution = options.minResolution; } else if (options.maxZoom !== undefined) { minResolution = this.constrainResolution( - this.maxResolution_, options.maxZoom - this.minZoom_, 0); + this.maxResolution_, options.maxZoom - this.minZoom_, 0); } else { minResolution = 0; } - var coords = geometry.getFlatCoordinates(); + const coords = geometry.getFlatCoordinates(); // calculate rotated extent - var rotation = this.getRotation(); - var cosAngle = Math.cos(-rotation); - var sinAngle = Math.sin(-rotation); - var minRotX = +Infinity; - var minRotY = +Infinity; - var maxRotX = -Infinity; - var maxRotY = -Infinity; - var stride = geometry.getStride(); - for (var i = 0, ii = coords.length; i < ii; i += stride) { - var rotX = coords[i] * cosAngle - coords[i + 1] * sinAngle; - var rotY = coords[i] * sinAngle + coords[i + 1] * cosAngle; + const rotation = this.getRotation(); + const cosAngle = Math.cos(-rotation); + let sinAngle = Math.sin(-rotation); + let minRotX = +Infinity; + let minRotY = +Infinity; + let maxRotX = -Infinity; + let maxRotY = -Infinity; + const stride = geometry.getStride(); + for (let i = 0, ii = coords.length; i < ii; i += stride) { + const rotX = coords[i] * cosAngle - coords[i + 1] * sinAngle; + const rotY = coords[i] * sinAngle + coords[i + 1] * cosAngle; minRotX = Math.min(minRotX, rotX); minRotY = Math.min(minRotY, rotY); maxRotX = Math.max(maxRotX, rotX); @@ -927,30 +927,30 @@ View.prototype.fit = function(geometryOrExtent, opt_options) { } // calculate resolution - var resolution = this.getResolutionForExtent( - [minRotX, minRotY, maxRotX, maxRotY], - [size[0] - padding[1] - padding[3], size[1] - padding[0] - padding[2]]); + let resolution = this.getResolutionForExtent( + [minRotX, minRotY, maxRotX, maxRotY], + [size[0] - padding[1] - padding[3], size[1] - padding[0] - padding[2]]); resolution = isNaN(resolution) ? minResolution : Math.max(resolution, minResolution); if (constrainResolution) { - var constrainedResolution = this.constrainResolution(resolution, 0, 0); + let constrainedResolution = this.constrainResolution(resolution, 0, 0); if (!nearest && constrainedResolution < resolution) { constrainedResolution = this.constrainResolution( - constrainedResolution, -1, 0); + constrainedResolution, -1, 0); } resolution = constrainedResolution; } // calculate center sinAngle = -sinAngle; // go back to original rotation - var centerRotX = (minRotX + maxRotX) / 2; - var centerRotY = (minRotY + maxRotY) / 2; + let centerRotX = (minRotX + maxRotX) / 2; + let centerRotY = (minRotY + maxRotY) / 2; centerRotX += (padding[1] - padding[3]) / 2 * resolution; centerRotY += (padding[0] - padding[2]) / 2 * resolution; - var centerX = centerRotX * cosAngle - centerRotY * sinAngle; - var centerY = centerRotY * cosAngle + centerRotX * sinAngle; - var center = [centerX, centerY]; - var callback = options.callback ? options.callback : nullFunction; + const centerX = centerRotX * cosAngle - centerRotY * sinAngle; + const centerY = centerRotY * cosAngle + centerRotX * sinAngle; + const center = [centerX, centerY]; + const callback = options.callback ? options.callback : nullFunction; if (options.duration !== undefined) { this.animate({ @@ -976,19 +976,19 @@ View.prototype.fit = function(geometryOrExtent, opt_options) { */ View.prototype.centerOn = function(coordinate, size, position) { // calculate rotated position - var rotation = this.getRotation(); - var cosAngle = Math.cos(-rotation); - var sinAngle = Math.sin(-rotation); - var rotX = coordinate[0] * cosAngle - coordinate[1] * sinAngle; - var rotY = coordinate[1] * cosAngle + coordinate[0] * sinAngle; - var resolution = this.getResolution(); + const rotation = this.getRotation(); + const cosAngle = Math.cos(-rotation); + let sinAngle = Math.sin(-rotation); + let rotX = coordinate[0] * cosAngle - coordinate[1] * sinAngle; + let rotY = coordinate[1] * cosAngle + coordinate[0] * sinAngle; + const resolution = this.getResolution(); rotX += (size[0] / 2 - position[0]) * resolution; rotY += (position[1] - size[1] / 2) * resolution; // go back to original angle sinAngle = -sinAngle; // go back to original rotation - var centerX = rotX * cosAngle - rotY * sinAngle; - var centerY = rotY * cosAngle + rotX * sinAngle; + const centerX = rotX * cosAngle - rotY * sinAngle; + const centerY = rotY * cosAngle + rotX * sinAngle; this.setCenter([centerX, centerY]); }; @@ -1010,7 +1010,7 @@ View.prototype.isDef = function() { */ View.prototype.rotate = function(rotation, opt_anchor) { if (opt_anchor !== undefined) { - var center = this.calculateCenterRotate(rotation, opt_anchor); + const center = this.calculateCenterRotate(rotation, opt_anchor); this.setCenter(center); } this.setRotation(rotation); @@ -1102,46 +1102,46 @@ View.createCenterConstraint_ = function(options) { * minResolution: number, zoomFactor: number}} The constraint. */ View.createResolutionConstraint_ = function(options) { - var resolutionConstraint; - var maxResolution; - var minResolution; + let resolutionConstraint; + let maxResolution; + let minResolution; // TODO: move these to be ol constants // see https://github.com/openlayers/openlayers/issues/2076 - var defaultMaxZoom = 28; - var defaultZoomFactor = 2; + const defaultMaxZoom = 28; + const defaultZoomFactor = 2; - var minZoom = options.minZoom !== undefined ? + let minZoom = options.minZoom !== undefined ? options.minZoom : DEFAULT_MIN_ZOOM; - var maxZoom = options.maxZoom !== undefined ? + let maxZoom = options.maxZoom !== undefined ? options.maxZoom : defaultMaxZoom; - var zoomFactor = options.zoomFactor !== undefined ? + const zoomFactor = options.zoomFactor !== undefined ? options.zoomFactor : defaultZoomFactor; if (options.resolutions !== undefined) { - var resolutions = options.resolutions; + const resolutions = options.resolutions; maxResolution = resolutions[minZoom]; minResolution = resolutions[maxZoom] !== undefined ? resolutions[maxZoom] : resolutions[resolutions.length - 1]; resolutionConstraint = ResolutionConstraint.createSnapToResolutions( - resolutions); + resolutions); } else { // calculate the default min and max resolution - var projection = createProjection(options.projection, 'EPSG:3857'); - var extent = projection.getExtent(); - var size = !extent ? + const projection = createProjection(options.projection, 'EPSG:3857'); + const extent = projection.getExtent(); + const size = !extent ? // use an extent that can fit the whole world if need be 360 * METERS_PER_UNIT[Units.DEGREES] / projection.getMetersPerUnit() : Math.max(getWidth(extent), getHeight(extent)); - var defaultMaxResolution = size / DEFAULT_TILE_SIZE / Math.pow( - defaultZoomFactor, DEFAULT_MIN_ZOOM); + const defaultMaxResolution = size / DEFAULT_TILE_SIZE / Math.pow( + defaultZoomFactor, DEFAULT_MIN_ZOOM); - var defaultMinResolution = defaultMaxResolution / Math.pow( - defaultZoomFactor, defaultMaxZoom - DEFAULT_MIN_ZOOM); + const defaultMinResolution = defaultMaxResolution / Math.pow( + defaultZoomFactor, defaultMaxZoom - DEFAULT_MIN_ZOOM); // user provided maxResolution takes precedence maxResolution = options.maxResolution; @@ -1167,11 +1167,11 @@ View.createResolutionConstraint_ = function(options) { // given discrete zoom levels, minResolution may be different than provided maxZoom = minZoom + Math.floor( - Math.log(maxResolution / minResolution) / Math.log(zoomFactor)); + Math.log(maxResolution / minResolution) / Math.log(zoomFactor)); minResolution = maxResolution / Math.pow(zoomFactor, maxZoom - minZoom); resolutionConstraint = ResolutionConstraint.createSnapToPower( - zoomFactor, maxResolution, maxZoom - minZoom); + zoomFactor, maxResolution, maxZoom - minZoom); } return {constraint: resolutionConstraint, maxResolution: maxResolution, minResolution: minResolution, minZoom: minZoom, zoomFactor: zoomFactor}; @@ -1184,10 +1184,10 @@ View.createResolutionConstraint_ = function(options) { * @return {ol.RotationConstraintType} Rotation constraint. */ View.createRotationConstraint_ = function(options) { - var enableRotation = options.enableRotation !== undefined ? + const enableRotation = options.enableRotation !== undefined ? options.enableRotation : true; if (enableRotation) { - var constrainRotation = options.constrainRotation; + const constrainRotation = options.constrainRotation; if (constrainRotation === undefined || constrainRotation === true) { return RotationConstraint.createSnapToZero(); } else if (constrainRotation === false) { diff --git a/src/ol/array.js b/src/ol/array.js index 57c6265385..6ccb81c310 100644 --- a/src/ol/array.js +++ b/src/ol/array.js @@ -13,11 +13,11 @@ * @return {number} The index of the item if found, -1 if not. */ export function binarySearch(haystack, needle, opt_comparator) { - var mid, cmp; - var comparator = opt_comparator || numberSafeCompareFunction; - var low = 0; - var high = haystack.length; - var found = false; + let mid, cmp; + const comparator = opt_comparator || numberSafeCompareFunction; + let low = 0; + let high = haystack.length; + let found = false; while (low < high) { /* Note that "(low + high) >>> 1" may overflow, and results in a typecast @@ -71,13 +71,13 @@ export function includes(arr, obj) { * @return {number} Index. */ export function linearFindNearest(arr, target, direction) { - var n = arr.length; + const n = arr.length; if (arr[0] <= target) { return 0; } else if (target <= arr[n - 1]) { return n - 1; } else { - var i; + let i; if (direction > 0) { for (i = 1; i < n; ++i) { if (arr[i] < target) { @@ -115,7 +115,7 @@ export function linearFindNearest(arr, target, direction) { */ export function reverseSubArray(arr, begin, end) { while (begin < end) { - var tmp = arr[begin]; + const tmp = arr[begin]; arr[begin] = arr[end]; arr[end] = tmp; ++begin; @@ -131,9 +131,9 @@ export function reverseSubArray(arr, begin, end) { * @template VALUE */ export function extend(arr, data) { - var i; - var extension = Array.isArray(data) ? data : [data]; - var length = extension.length; + let i; + const extension = Array.isArray(data) ? data : [data]; + const length = extension.length; for (i = 0; i < length; i++) { arr[arr.length] = extension[i]; } @@ -147,8 +147,8 @@ export function extend(arr, data) { * @return {boolean} If the element was removed. */ export function remove(arr, obj) { - var i = arr.indexOf(obj); - var found = i > -1; + const i = arr.indexOf(obj); + const found = i > -1; if (found) { arr.splice(i, 1); } @@ -163,10 +163,10 @@ export function remove(arr, obj) { * @return {VALUE} The element found. */ export function find(arr, func) { - var length = arr.length >>> 0; - var value; + const length = arr.length >>> 0; + let value; - for (var i = 0; i < length; i++) { + for (let i = 0; i < length; i++) { value = arr[i]; if (func(value, i, arr)) { return value; @@ -182,11 +182,11 @@ export function find(arr, func) { * @return {boolean} Whether the two arrays are equal. */ export function equals(arr1, arr2) { - var len1 = arr1.length; + const len1 = arr1.length; if (len1 !== arr2.length) { return false; } - for (var i = 0; i < len1; i++) { + for (let i = 0; i < len1; i++) { if (arr1[i] !== arr2[i]) { return false; } @@ -200,9 +200,9 @@ export function equals(arr1, arr2) { * @param {Function} compareFnc Comparison function. */ export function stableSort(arr, compareFnc) { - var length = arr.length; - var tmp = Array(arr.length); - var i; + const length = arr.length; + const tmp = Array(arr.length); + let i; for (i = 0; i < length; i++) { tmp[i] = {index: i, value: arr[i]}; } @@ -221,8 +221,8 @@ export function stableSort(arr, compareFnc) { * @return {number} Return index. */ export function findIndex(arr, func) { - var index; - var found = !arr.every(function(el, idx) { + let index; + const found = !arr.every(function(el, idx) { index = idx; return !func(el, idx, arr); }); @@ -237,12 +237,12 @@ export function findIndex(arr, func) { * @return {boolean} Return index. */ export function isSorted(arr, opt_func, opt_strict) { - var compare = opt_func || numberSafeCompareFunction; + const compare = opt_func || numberSafeCompareFunction; return arr.every(function(currentVal, index) { if (index === 0) { return true; } - var res = compare(arr[index - 1], currentVal); + const res = compare(arr[index - 1], currentVal); return !(res > 0 || opt_strict && res === 0); }); } diff --git a/src/ol/color.js b/src/ol/color.js index 7030d797ff..2a5cf1f6f6 100644 --- a/src/ol/color.js +++ b/src/ol/color.js @@ -11,7 +11,7 @@ import {clamp} from './math.js'; * @type {RegExp} * @private */ -var HEX_COLOR_RE_ = /^#(?:[0-9a-f]{3,4}){1,2}$/i; +const HEX_COLOR_RE_ = /^#(?:[0-9a-f]{3,4}){1,2}$/i; /** @@ -20,7 +20,7 @@ var HEX_COLOR_RE_ = /^#(?:[0-9a-f]{3,4}){1,2}$/i; * @type {RegExp} * @private */ -var NAMED_COLOR_RE_ = /^([a-z]*)$/i; +const NAMED_COLOR_RE_ = /^([a-z]*)$/i; /** @@ -43,10 +43,10 @@ export function asString(color) { * @return {string} Rgb string. */ function fromNamed(color) { - var el = document.createElement('div'); + const el = document.createElement('div'); el.style.color = color; document.body.appendChild(el); - var rgb = getComputedStyle(el).color; + const rgb = getComputedStyle(el).color; document.body.removeChild(el); return rgb; } @@ -56,7 +56,7 @@ function fromNamed(color) { * @param {string} s String. * @return {ol.Color} Color. */ -export var fromString = ( +export const fromString = ( function() { // We maintain a small cache of parsed strings. To provide cheap LRU-like @@ -67,17 +67,17 @@ export var fromString = ( * @const * @type {number} */ - var MAX_CACHE_SIZE = 1024; + const MAX_CACHE_SIZE = 1024; /** * @type {Object.} */ - var cache = {}; + const cache = {}; /** * @type {number} */ - var cacheSize = 0; + let cacheSize = 0; return ( /** @@ -85,13 +85,13 @@ export var fromString = ( * @return {ol.Color} Color. */ function(s) { - var color; + let color; if (cache.hasOwnProperty(s)) { color = cache[s]; } else { if (cacheSize >= MAX_CACHE_SIZE) { - var i = 0; - var key; + let i = 0; + let key; for (key in cache) { if ((i++ & 3) === 0) { delete cache[key]; @@ -130,21 +130,21 @@ export function asArray(color) { * @return {ol.Color} Color. */ function fromStringInternal_(s) { - var r, g, b, a, color, parts; + let r, g, b, a, color, parts; if (NAMED_COLOR_RE_.exec(s)) { s = fromNamed(s); } if (HEX_COLOR_RE_.exec(s)) { // hex - var n = s.length - 1; // number of hex digits - var d; // number of digits per channel + const n = s.length - 1; // number of hex digits + let d; // number of digits per channel if (n <= 4) { d = 1; } else { d = 2; } - var hasAlpha = n === 4 || n === 8; + const hasAlpha = n === 4 || n === 8; r = parseInt(s.substr(1 + 0 * d, d), 16); g = parseInt(s.substr(1 + 1 * d, d), 16); b = parseInt(s.substr(1 + 2 * d, d), 16); @@ -183,7 +183,7 @@ function fromStringInternal_(s) { * @return {ol.Color} Clamped color. */ export function normalize(color, opt_color) { - var result = opt_color || []; + const result = opt_color || []; result[0] = clamp((color[0] + 0.5) | 0, 0, 255); result[1] = clamp((color[1] + 0.5) | 0, 0, 255); result[2] = clamp((color[2] + 0.5) | 0, 0, 255); @@ -197,18 +197,18 @@ export function normalize(color, opt_color) { * @return {string} String. */ export function toString(color) { - var r = color[0]; + let r = color[0]; if (r != (r | 0)) { r = (r + 0.5) | 0; } - var g = color[1]; + let g = color[1]; if (g != (g | 0)) { g = (g + 0.5) | 0; } - var b = color[2]; + let b = color[2]; if (b != (b | 0)) { b = (b + 0.5) | 0; } - var a = color[3] === undefined ? 1 : color[3]; + const a = color[3] === undefined ? 1 : color[3]; return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; } diff --git a/src/ol/control.js b/src/ol/control.js index a0875894fd..cc7d3eadf0 100644 --- a/src/ol/control.js +++ b/src/ol/control.js @@ -21,21 +21,21 @@ import Zoom from './control/Zoom.js'; */ export function defaults(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; - var controls = new Collection(); + const controls = new Collection(); - var zoomControl = options.zoom !== undefined ? options.zoom : true; + const zoomControl = options.zoom !== undefined ? options.zoom : true; if (zoomControl) { controls.push(new Zoom(options.zoomOptions)); } - var rotateControl = options.rotate !== undefined ? options.rotate : true; + const rotateControl = options.rotate !== undefined ? options.rotate : true; if (rotateControl) { controls.push(new Rotate(options.rotateOptions)); } - var attributionControl = options.attribution !== undefined ? + const attributionControl = options.attribution !== undefined ? options.attribution : true; if (attributionControl) { controls.push(new Attribution(options.attributionOptions)); diff --git a/src/ol/control/Attribution.js b/src/ol/control/Attribution.js index 05f8c4feea..060ba32766 100644 --- a/src/ol/control/Attribution.js +++ b/src/ol/control/Attribution.js @@ -22,9 +22,9 @@ import Layer from '../layer/Layer.js'; * @param {olx.control.AttributionOptions=} opt_options Attribution options. * @api */ -var Attribution = function(opt_options) { +const Attribution = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @private @@ -49,11 +49,11 @@ var Attribution = function(opt_options) { this.collapsed_ = false; } - var className = options.className !== undefined ? options.className : 'ol-attribution'; + const className = options.className !== undefined ? options.className : 'ol-attribution'; - var tipLabel = options.tipLabel !== undefined ? options.tipLabel : 'Attributions'; + const tipLabel = options.tipLabel !== undefined ? options.tipLabel : 'Attributions'; - var collapseLabel = options.collapseLabel !== undefined ? options.collapseLabel : '\u00BB'; + const collapseLabel = options.collapseLabel !== undefined ? options.collapseLabel : '\u00BB'; if (typeof collapseLabel === 'string') { /** @@ -66,7 +66,7 @@ var Attribution = function(opt_options) { this.collapseLabel_ = collapseLabel; } - var label = options.label !== undefined ? options.label : 'i'; + const label = options.label !== undefined ? options.label : 'i'; if (typeof label === 'string') { /** @@ -80,24 +80,24 @@ var Attribution = function(opt_options) { } - var activeLabel = (this.collapsible_ && !this.collapsed_) ? + const activeLabel = (this.collapsible_ && !this.collapsed_) ? this.collapseLabel_ : this.label_; - var button = document.createElement('button'); + const button = document.createElement('button'); button.setAttribute('type', 'button'); button.title = tipLabel; button.appendChild(activeLabel); _ol_events_.listen(button, EventType.CLICK, this.handleClick_, this); - var cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL + + const cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL + (this.collapsed_ && this.collapsible_ ? ' ol-collapsed' : '') + (this.collapsible_ ? '' : ' ol-uncollapsible'); - var element = document.createElement('div'); + const element = document.createElement('div'); element.className = cssClasses; element.appendChild(this.ulElement_); element.appendChild(button); - var render = options.render ? options.render : Attribution.render; + const render = options.render ? options.render : Attribution.render; Control.call(this, { element: element, @@ -134,39 +134,39 @@ Attribution.prototype.getSourceAttributions_ = function(frameState) { * Used to determine if an attribution already exists. * @type {Object.} */ - var lookup = {}; + const lookup = {}; /** * A list of visible attributions. * @type {Array.} */ - var visibleAttributions = []; + const visibleAttributions = []; - var layerStatesArray = frameState.layerStatesArray; - var resolution = frameState.viewState.resolution; - for (var i = 0, ii = layerStatesArray.length; i < ii; ++i) { - var layerState = layerStatesArray[i]; + const layerStatesArray = frameState.layerStatesArray; + const resolution = frameState.viewState.resolution; + for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) { + const layerState = layerStatesArray[i]; if (!Layer.visibleAtResolution(layerState, resolution)) { continue; } - var source = layerState.layer.getSource(); + const source = layerState.layer.getSource(); if (!source) { continue; } - var attributionGetter = source.getAttributions(); + const attributionGetter = source.getAttributions(); if (!attributionGetter) { continue; } - var attributions = attributionGetter(frameState); + const attributions = attributionGetter(frameState); if (!attributions) { continue; } if (Array.isArray(attributions)) { - for (var j = 0, jj = attributions.length; j < jj; ++j) { + for (let j = 0, jj = attributions.length; j < jj; ++j) { if (!(attributions[j] in lookup)) { visibleAttributions.push(attributions[j]); lookup[attributions[j]] = true; @@ -207,7 +207,7 @@ Attribution.prototype.updateElement_ = function(frameState) { return; } - var attributions = this.getSourceAttributions_(frameState); + const attributions = this.getSourceAttributions_(frameState); if (equals(attributions, this.renderedAttributions_)) { return; } @@ -215,14 +215,14 @@ Attribution.prototype.updateElement_ = function(frameState) { removeChildren(this.ulElement_); // append the attributions - for (var i = 0, ii = attributions.length; i < ii; ++i) { - var element = document.createElement('LI'); + for (let i = 0, ii = attributions.length; i < ii; ++i) { + const element = document.createElement('LI'); element.innerHTML = attributions[i]; this.ulElement_.appendChild(element); } - var visible = attributions.length > 0; + const visible = attributions.length > 0; if (this.renderedVisible_ != visible) { this.element.style.display = visible ? '' : 'none'; this.renderedVisible_ = visible; diff --git a/src/ol/control/Control.js b/src/ol/control/Control.js index 91a8f5f19b..d3a33d3556 100644 --- a/src/ol/control/Control.js +++ b/src/ol/control/Control.js @@ -36,7 +36,7 @@ import _ol_events_ from '../events.js'; * @param {olx.control.ControlOptions} options Control options. * @api */ -var Control = function(options) { +const Control = function(options) { BaseObject.call(this); @@ -109,18 +109,18 @@ Control.prototype.setMap = function(map) { if (this.map_) { removeNode(this.element); } - for (var i = 0, ii = this.listenerKeys.length; i < ii; ++i) { + for (let i = 0, ii = this.listenerKeys.length; i < ii; ++i) { _ol_events_.unlistenByKey(this.listenerKeys[i]); } this.listenerKeys.length = 0; this.map_ = map; if (this.map_) { - var target = this.target_ ? + const target = this.target_ ? this.target_ : map.getOverlayContainerStopEvent(); target.appendChild(this.element); if (this.render !== nullFunction) { this.listenerKeys.push(_ol_events_.listen(map, - MapEventType.POSTRENDER, this.render, this)); + MapEventType.POSTRENDER, this.render, this)); } map.render(); } diff --git a/src/ol/control/FullScreen.js b/src/ol/control/FullScreen.js index 0f739c0162..cac72988f6 100644 --- a/src/ol/control/FullScreen.js +++ b/src/ol/control/FullScreen.js @@ -25,9 +25,9 @@ import EventType from '../events/EventType.js'; * @param {olx.control.FullScreenOptions=} opt_options Options. * @api */ -var FullScreen = function(opt_options) { +const FullScreen = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @private @@ -36,7 +36,7 @@ var FullScreen = function(opt_options) { this.cssClassName_ = options.className !== undefined ? options.className : 'ol-full-screen'; - var label = options.label !== undefined ? options.label : '\u2922'; + const label = options.label !== undefined ? options.label : '\u2922'; /** * @private @@ -45,7 +45,7 @@ var FullScreen = function(opt_options) { this.labelNode_ = typeof label === 'string' ? document.createTextNode(label) : label; - var labelActive = options.labelActive !== undefined ? options.labelActive : '\u00d7'; + const labelActive = options.labelActive !== undefined ? options.labelActive : '\u00d7'; /** * @private @@ -54,20 +54,20 @@ var FullScreen = function(opt_options) { this.labelActiveNode_ = typeof labelActive === 'string' ? document.createTextNode(labelActive) : labelActive; - var tipLabel = options.tipLabel ? options.tipLabel : 'Toggle full-screen'; - var button = document.createElement('button'); + const tipLabel = options.tipLabel ? options.tipLabel : 'Toggle full-screen'; + const button = document.createElement('button'); button.className = this.cssClassName_ + '-' + FullScreen.isFullScreen(); button.setAttribute('type', 'button'); button.title = tipLabel; button.appendChild(this.labelNode_); _ol_events_.listen(button, EventType.CLICK, - this.handleClick_, this); + this.handleClick_, this); - var cssClasses = this.cssClassName_ + ' ' + CLASS_UNSELECTABLE + + const cssClasses = this.cssClassName_ + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL + ' ' + (!FullScreen.isFullScreenSupported() ? CLASS_UNSUPPORTED : ''); - var element = document.createElement('div'); + const element = document.createElement('div'); element.className = cssClasses; element.appendChild(button); @@ -110,14 +110,14 @@ FullScreen.prototype.handleFullScreen_ = function() { if (!FullScreen.isFullScreenSupported()) { return; } - var map = this.getMap(); + const map = this.getMap(); if (!map) { return; } if (FullScreen.isFullScreen()) { FullScreen.exitFullScreen(); } else { - var element; + let element; if (this.source_) { element = typeof this.source_ === 'string' ? document.getElementById(this.source_) : @@ -139,8 +139,8 @@ FullScreen.prototype.handleFullScreen_ = function() { * @private */ FullScreen.prototype.handleFullScreenChange_ = function() { - var button = this.element.firstElementChild; - var map = this.getMap(); + const button = this.element.firstElementChild; + const map = this.getMap(); if (FullScreen.isFullScreen()) { button.className = this.cssClassName_ + '-true'; replaceNode(this.labelActiveNode_, this.labelNode_); @@ -162,8 +162,8 @@ FullScreen.prototype.setMap = function(map) { Control.prototype.setMap.call(this, map); if (map) { this.listenerKeys.push(_ol_events_.listen(document, - FullScreen.getChangeType_(), - this.handleFullScreenChange_, this) + FullScreen.getChangeType_(), + this.handleFullScreenChange_, this) ); } }; @@ -172,7 +172,7 @@ FullScreen.prototype.setMap = function(map) { * @return {boolean} Fullscreen is supported by the current platform. */ FullScreen.isFullScreenSupported = function() { - var body = document.body; + const body = document.body; return !!( body.webkitRequestFullscreen || (body.mozRequestFullScreen && document.mozFullScreenEnabled) || @@ -241,10 +241,10 @@ FullScreen.exitFullScreen = function() { * @private */ FullScreen.getChangeType_ = (function() { - var changeType; + let changeType; return function() { if (!changeType) { - var body = document.body; + const body = document.body; if (body.webkitRequestFullscreen) { changeType = 'webkitfullscreenchange'; } else if (body.mozRequestFullScreen) { diff --git a/src/ol/control/MousePosition.js b/src/ol/control/MousePosition.js index a30823b51d..d008c675ad 100644 --- a/src/ol/control/MousePosition.js +++ b/src/ol/control/MousePosition.js @@ -22,14 +22,14 @@ import {getTransformFromProjections, identityTransform, get as getProjection} fr * options. * @api */ -var MousePosition = function(opt_options) { +const MousePosition = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; - var element = document.createElement('DIV'); + const element = document.createElement('DIV'); element.className = options.className !== undefined ? options.className : 'ol-mouse-position'; - var render = options.render ? + const render = options.render ? options.render : MousePosition.render; Control.call(this, { @@ -39,8 +39,8 @@ var MousePosition = function(opt_options) { }); _ol_events_.listen(this, - BaseObject.getChangeEventType(MousePosition.Property_.PROJECTION), - this.handleProjectionChanged_, this); + BaseObject.getChangeEventType(MousePosition.Property_.PROJECTION), + this.handleProjectionChanged_, this); if (options.coordinateFormat) { this.setCoordinateFormat(options.coordinateFormat); @@ -91,7 +91,7 @@ inherits(MousePosition, Control); * @api */ MousePosition.render = function(mapEvent) { - var frameState = mapEvent.frameState; + const frameState = mapEvent.frameState; if (!frameState) { this.mapProjection_ = null; } else { @@ -146,7 +146,7 @@ MousePosition.prototype.getProjection = function() { * @protected */ MousePosition.prototype.handleMouseMove = function(event) { - var map = this.getMap(); + const map = this.getMap(); this.lastMouseMovePixel_ = map.getEventPixel(event); this.updateHTML_(this.lastMouseMovePixel_); }; @@ -169,12 +169,12 @@ MousePosition.prototype.handleMouseOut = function(event) { MousePosition.prototype.setMap = function(map) { Control.prototype.setMap.call(this, map); if (map) { - var viewport = map.getViewport(); + const viewport = map.getViewport(); this.listenerKeys.push( - _ol_events_.listen(viewport, EventType.MOUSEMOVE, - this.handleMouseMove, this), - _ol_events_.listen(viewport, EventType.MOUSEOUT, - this.handleMouseOut, this) + _ol_events_.listen(viewport, EventType.MOUSEMOVE, + this.handleMouseMove, this), + _ol_events_.listen(viewport, EventType.MOUSEOUT, + this.handleMouseOut, this) ); } }; @@ -209,22 +209,22 @@ MousePosition.prototype.setProjection = function(projection) { * @private */ MousePosition.prototype.updateHTML_ = function(pixel) { - var html = this.undefinedHTML_; + let html = this.undefinedHTML_; if (pixel && this.mapProjection_) { if (!this.transform_) { - var projection = this.getProjection(); + const projection = this.getProjection(); if (projection) { this.transform_ = getTransformFromProjections( - this.mapProjection_, projection); + this.mapProjection_, projection); } else { this.transform_ = identityTransform; } } - var map = this.getMap(); - var coordinate = map.getCoordinateFromPixel(pixel); + const map = this.getMap(); + const coordinate = map.getCoordinateFromPixel(pixel); if (coordinate) { this.transform_(coordinate, coordinate); - var coordinateFormat = this.getCoordinateFormat(); + const coordinateFormat = this.getCoordinateFormat(); if (coordinateFormat) { html = coordinateFormat(coordinate); } else { diff --git a/src/ol/control/OverviewMap.js b/src/ol/control/OverviewMap.js index dd8d4a441c..c3148743f4 100644 --- a/src/ol/control/OverviewMap.js +++ b/src/ol/control/OverviewMap.js @@ -24,14 +24,14 @@ import {containsExtent, getBottomLeft, getBottomRight, getTopLeft, getTopRight, * @type {number} Maximum width and/or height extent ratio that determines * when the overview map should be zoomed out. */ -var MAX_RATIO = 0.75; +const MAX_RATIO = 0.75; /** * @type {number} Minimum width and/or height extent ratio that determines * when the overview map should be zoomed in. */ -var MIN_RATIO = 0.1; +const MIN_RATIO = 0.1; /** @@ -42,9 +42,9 @@ var MIN_RATIO = 0.1; * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. * @api */ -var OverviewMap = function(opt_options) { +const OverviewMap = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @type {boolean} @@ -63,11 +63,11 @@ var OverviewMap = function(opt_options) { this.collapsed_ = false; } - var className = options.className !== undefined ? options.className : 'ol-overviewmap'; + const className = options.className !== undefined ? options.className : 'ol-overviewmap'; - var tipLabel = options.tipLabel !== undefined ? options.tipLabel : 'Overview map'; + const tipLabel = options.tipLabel !== undefined ? options.tipLabel : 'Overview map'; - var collapseLabel = options.collapseLabel !== undefined ? options.collapseLabel : '\u00AB'; + const collapseLabel = options.collapseLabel !== undefined ? options.collapseLabel : '\u00AB'; if (typeof collapseLabel === 'string') { /** @@ -80,7 +80,7 @@ var OverviewMap = function(opt_options) { this.collapseLabel_ = collapseLabel; } - var label = options.label !== undefined ? options.label : '\u00BB'; + const label = options.label !== undefined ? options.label : '\u00BB'; if (typeof label === 'string') { @@ -94,15 +94,15 @@ var OverviewMap = function(opt_options) { this.label_ = label; } - var activeLabel = (this.collapsible_ && !this.collapsed_) ? + const activeLabel = (this.collapsible_ && !this.collapsed_) ? this.collapseLabel_ : this.label_; - var button = document.createElement('button'); + const button = document.createElement('button'); button.setAttribute('type', 'button'); button.title = tipLabel; button.appendChild(activeLabel); _ol_events_.listen(button, EventType.CLICK, - this.handleClick_, this); + this.handleClick_, this); /** * @type {Element} @@ -120,19 +120,19 @@ var OverviewMap = function(opt_options) { interactions: new Collection(), view: options.view }); - var ovmap = this.ovmap_; + const ovmap = this.ovmap_; if (options.layers) { options.layers.forEach( - /** + /** * @param {ol.layer.Layer} layer Layer. */ - function(layer) { - ovmap.addLayer(layer); - }.bind(this)); + function(layer) { + ovmap.addLayer(layer); + }.bind(this)); } - var box = document.createElement('DIV'); + const box = document.createElement('DIV'); box.className = 'ol-overviewmap-box'; box.style.boxSizing = 'border-box'; @@ -147,15 +147,15 @@ var OverviewMap = function(opt_options) { }); this.ovmap_.addOverlay(this.boxOverlay_); - var cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL + + const cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL + (this.collapsed_ && this.collapsible_ ? ' ol-collapsed' : '') + (this.collapsible_ ? '' : ' ol-uncollapsible'); - var element = document.createElement('div'); + const element = document.createElement('div'); element.className = cssClasses; element.appendChild(this.ovmapDiv_); element.appendChild(button); - var render = options.render ? options.render : OverviewMap.render; + const render = options.render ? options.render : OverviewMap.render; Control.call(this, { element: element, @@ -165,28 +165,28 @@ var OverviewMap = function(opt_options) { /* Interactive map */ - var scope = this; + const scope = this; - var overlay = this.boxOverlay_; - var overlayBox = this.boxOverlay_.getElement(); + const overlay = this.boxOverlay_; + const overlayBox = this.boxOverlay_.getElement(); /* Functions definition */ - var computeDesiredMousePosition = function(mousePosition) { + const computeDesiredMousePosition = function(mousePosition) { return { clientX: mousePosition.clientX - (overlayBox.offsetWidth / 2), clientY: mousePosition.clientY + (overlayBox.offsetHeight / 2) }; }; - var move = function(event) { - var coordinates = ovmap.getEventCoordinate(computeDesiredMousePosition(event)); + const move = function(event) { + const coordinates = ovmap.getEventCoordinate(computeDesiredMousePosition(event)); overlay.setPosition(coordinates); }; - var endMoving = function(event) { - var coordinates = ovmap.getEventCoordinate(event); + const endMoving = function(event) { + const coordinates = ovmap.getEventCoordinate(event); scope.getMap().getView().setCenter(coordinates); @@ -210,12 +210,12 @@ inherits(OverviewMap, Control); * @api */ OverviewMap.prototype.setMap = function(map) { - var oldMap = this.getMap(); + const oldMap = this.getMap(); if (map === oldMap) { return; } if (oldMap) { - var oldView = oldMap.getView(); + const oldView = oldMap.getView(); if (oldView) { this.unbindView_(oldView); } @@ -226,15 +226,15 @@ OverviewMap.prototype.setMap = function(map) { if (map) { this.ovmap_.setTarget(this.ovmapDiv_); this.listenerKeys.push(_ol_events_.listen( - map, ObjectEventType.PROPERTYCHANGE, - this.handleMapPropertyChange_, this)); + map, ObjectEventType.PROPERTYCHANGE, + this.handleMapPropertyChange_, this)); // TODO: to really support map switching, this would need to be reworked if (this.ovmap_.getLayers().getLength() === 0) { this.ovmap_.setLayerGroup(map.getLayerGroup()); } - var view = map.getView(); + const view = map.getView(); if (view) { this.bindView_(view); if (view.isDef()) { @@ -253,11 +253,11 @@ OverviewMap.prototype.setMap = function(map) { */ OverviewMap.prototype.handleMapPropertyChange_ = function(event) { if (event.key === MapProperty.VIEW) { - var oldView = /** @type {ol.View} */ (event.oldValue); + const oldView = /** @type {ol.View} */ (event.oldValue); if (oldView) { this.unbindView_(oldView); } - var newView = this.getMap().getView(); + const newView = this.getMap().getView(); this.bindView_(newView); } }; @@ -270,8 +270,8 @@ OverviewMap.prototype.handleMapPropertyChange_ = function(event) { */ OverviewMap.prototype.bindView_ = function(view) { _ol_events_.listen(view, - BaseObject.getChangeEventType(ViewProperty.ROTATION), - this.handleRotationChanged_, this); + BaseObject.getChangeEventType(ViewProperty.ROTATION), + this.handleRotationChanged_, this); }; @@ -282,8 +282,8 @@ OverviewMap.prototype.bindView_ = function(view) { */ OverviewMap.prototype.unbindView_ = function(view) { _ol_events_.unlisten(view, - BaseObject.getChangeEventType(ViewProperty.ROTATION), - this.handleRotationChanged_, this); + BaseObject.getChangeEventType(ViewProperty.ROTATION), + this.handleRotationChanged_, this); }; @@ -322,33 +322,33 @@ OverviewMap.render = function(mapEvent) { * @private */ OverviewMap.prototype.validateExtent_ = function() { - var map = this.getMap(); - var ovmap = this.ovmap_; + const map = this.getMap(); + const ovmap = this.ovmap_; if (!map.isRendered() || !ovmap.isRendered()) { return; } - var mapSize = /** @type {ol.Size} */ (map.getSize()); + const mapSize = /** @type {ol.Size} */ (map.getSize()); - var view = map.getView(); - var extent = view.calculateExtent(mapSize); + const view = map.getView(); + const extent = view.calculateExtent(mapSize); - var ovmapSize = /** @type {ol.Size} */ (ovmap.getSize()); + const ovmapSize = /** @type {ol.Size} */ (ovmap.getSize()); - var ovview = ovmap.getView(); - var ovextent = ovview.calculateExtent(ovmapSize); + const ovview = ovmap.getView(); + const ovextent = ovview.calculateExtent(ovmapSize); - var topLeftPixel = + const topLeftPixel = ovmap.getPixelFromCoordinate(getTopLeft(extent)); - var bottomRightPixel = + const bottomRightPixel = ovmap.getPixelFromCoordinate(getBottomRight(extent)); - var boxWidth = Math.abs(topLeftPixel[0] - bottomRightPixel[0]); - var boxHeight = Math.abs(topLeftPixel[1] - bottomRightPixel[1]); + const boxWidth = Math.abs(topLeftPixel[0] - bottomRightPixel[0]); + const boxHeight = Math.abs(topLeftPixel[1] - bottomRightPixel[1]); - var ovmapWidth = ovmapSize[0]; - var ovmapHeight = ovmapSize[1]; + const ovmapWidth = ovmapSize[0]; + const ovmapHeight = ovmapSize[1]; if (boxWidth < ovmapWidth * MIN_RATIO || boxHeight < ovmapHeight * MIN_RATIO || @@ -371,22 +371,22 @@ OverviewMap.prototype.resetExtent_ = function() { return; } - var map = this.getMap(); - var ovmap = this.ovmap_; + const map = this.getMap(); + const ovmap = this.ovmap_; - var mapSize = /** @type {ol.Size} */ (map.getSize()); + const mapSize = /** @type {ol.Size} */ (map.getSize()); - var view = map.getView(); - var extent = view.calculateExtent(mapSize); + const view = map.getView(); + const extent = view.calculateExtent(mapSize); - var ovview = ovmap.getView(); + const ovview = ovmap.getView(); // get how many times the current map overview could hold different // box sizes using the min and max ratio, pick the step in the middle used // to calculate the extent from the main map to set it to the overview map, - var steps = Math.log( - MAX_RATIO / MIN_RATIO) / Math.LN2; - var ratio = 1 / (Math.pow(2, steps / 2) * MIN_RATIO); + const steps = Math.log( + MAX_RATIO / MIN_RATIO) / Math.LN2; + const ratio = 1 / (Math.pow(2, steps / 2) * MIN_RATIO); scaleFromCenter(extent, ratio); ovview.fit(extent); }; @@ -398,12 +398,12 @@ OverviewMap.prototype.resetExtent_ = function() { * @private */ OverviewMap.prototype.recenter_ = function() { - var map = this.getMap(); - var ovmap = this.ovmap_; + const map = this.getMap(); + const ovmap = this.ovmap_; - var view = map.getView(); + const view = map.getView(); - var ovview = ovmap.getView(); + const ovview = ovmap.getView(); ovview.setCenter(view.getCenter()); }; @@ -414,30 +414,30 @@ OverviewMap.prototype.recenter_ = function() { * @private */ OverviewMap.prototype.updateBox_ = function() { - var map = this.getMap(); - var ovmap = this.ovmap_; + const map = this.getMap(); + const ovmap = this.ovmap_; if (!map.isRendered() || !ovmap.isRendered()) { return; } - var mapSize = /** @type {ol.Size} */ (map.getSize()); + const mapSize = /** @type {ol.Size} */ (map.getSize()); - var view = map.getView(); + const view = map.getView(); - var ovview = ovmap.getView(); + const ovview = ovmap.getView(); - var rotation = view.getRotation(); + const rotation = view.getRotation(); - var overlay = this.boxOverlay_; - var box = this.boxOverlay_.getElement(); - var extent = view.calculateExtent(mapSize); - var ovresolution = ovview.getResolution(); - var bottomLeft = getBottomLeft(extent); - var topRight = getTopRight(extent); + const overlay = this.boxOverlay_; + const box = this.boxOverlay_.getElement(); + const extent = view.calculateExtent(mapSize); + const ovresolution = ovview.getResolution(); + const bottomLeft = getBottomLeft(extent); + const topRight = getTopRight(extent); // set position using bottom left coordinates - var rotateBottomLeft = this.calculateCoordinateRotate_(rotation, bottomLeft); + const rotateBottomLeft = this.calculateCoordinateRotate_(rotation, bottomLeft); overlay.setPosition(rotateBottomLeft); // set box size calculated from map extent size and overview map resolution @@ -455,13 +455,13 @@ OverviewMap.prototype.updateBox_ = function() { * @private */ OverviewMap.prototype.calculateCoordinateRotate_ = function( - rotation, coordinate) { - var coordinateRotate; + rotation, coordinate) { + let coordinateRotate; - var map = this.getMap(); - var view = map.getView(); + const map = this.getMap(); + const view = map.getView(); - var currentCenter = view.getCenter(); + const currentCenter = view.getCenter(); if (currentCenter) { coordinateRotate = [ @@ -499,15 +499,15 @@ OverviewMap.prototype.handleToggle_ = function() { // manage overview map if it had not been rendered before and control // is expanded - var ovmap = this.ovmap_; + const ovmap = this.ovmap_; if (!this.collapsed_ && !ovmap.isRendered()) { ovmap.updateSize(); this.resetExtent_(); _ol_events_.listenOnce(ovmap, MapEventType.POSTRENDER, - function(event) { - this.updateBox_(); - }, - this); + function(event) { + this.updateBox_(); + }, + this); } }; diff --git a/src/ol/control/Rotate.js b/src/ol/control/Rotate.js index de122cb9ad..65a7cd66b8 100644 --- a/src/ol/control/Rotate.js +++ b/src/ol/control/Rotate.js @@ -20,13 +20,13 @@ import {inherits} from '../index.js'; * @param {olx.control.RotateOptions=} opt_options Rotate options. * @api */ -var Rotate = function(opt_options) { +const Rotate = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; - var className = options.className !== undefined ? options.className : 'ol-rotate'; + const className = options.className !== undefined ? options.className : 'ol-rotate'; - var label = options.label !== undefined ? options.label : '\u21E7'; + const label = options.label !== undefined ? options.label : '\u21E7'; /** * @type {Element} @@ -43,23 +43,23 @@ var Rotate = function(opt_options) { this.label_.classList.add('ol-compass'); } - var tipLabel = options.tipLabel ? options.tipLabel : 'Reset rotation'; + const tipLabel = options.tipLabel ? options.tipLabel : 'Reset rotation'; - var button = document.createElement('button'); + const button = document.createElement('button'); button.className = className + '-reset'; button.setAttribute('type', 'button'); button.title = tipLabel; button.appendChild(this.label_); _ol_events_.listen(button, EventType.CLICK, - Rotate.prototype.handleClick_, this); + Rotate.prototype.handleClick_, this); - var cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL; - var element = document.createElement('div'); + const cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL; + const element = document.createElement('div'); element.className = cssClasses; element.appendChild(button); - var render = options.render ? options.render : Rotate.render; + const render = options.render ? options.render : Rotate.render; this.callResetNorth_ = options.resetNorth ? options.resetNorth : undefined; @@ -114,8 +114,8 @@ Rotate.prototype.handleClick_ = function(event) { * @private */ Rotate.prototype.resetNorth_ = function() { - var map = this.getMap(); - var view = map.getView(); + const map = this.getMap(); + const view = map.getView(); if (!view) { // the map does not have a view, so we can't act // upon it @@ -142,15 +142,15 @@ Rotate.prototype.resetNorth_ = function() { * @api */ Rotate.render = function(mapEvent) { - var frameState = mapEvent.frameState; + const frameState = mapEvent.frameState; if (!frameState) { return; } - var rotation = frameState.viewState.rotation; + const rotation = frameState.viewState.rotation; if (rotation != this.rotation_) { - var transform = 'rotate(' + rotation + 'rad)'; + const transform = 'rotate(' + rotation + 'rad)'; if (this.autoHide_) { - var contains = this.element.classList.contains(CLASS_HIDDEN); + const contains = this.element.classList.contains(CLASS_HIDDEN); if (!contains && rotation === 0) { this.element.classList.add(CLASS_HIDDEN); } else if (contains && rotation !== 0) { diff --git a/src/ol/control/ScaleLine.js b/src/ol/control/ScaleLine.js index 621f2f933b..4ea28331ec 100644 --- a/src/ol/control/ScaleLine.js +++ b/src/ol/control/ScaleLine.js @@ -26,11 +26,11 @@ import Units from '../proj/Units.js'; * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. * @api */ -var ScaleLine = function(opt_options) { +const ScaleLine = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; - var className = options.className !== undefined ? options.className : 'ol-scale-line'; + const className = options.className !== undefined ? options.className : 'ol-scale-line'; /** * @private @@ -77,7 +77,7 @@ var ScaleLine = function(opt_options) { */ this.renderedHTML_ = ''; - var render = options.render ? options.render : ScaleLine.render; + const render = options.render ? options.render : ScaleLine.render; Control.call(this, { element: this.element_, @@ -86,8 +86,8 @@ var ScaleLine = function(opt_options) { }); _ol_events_.listen( - this, BaseObject.getChangeEventType(ScaleLine.Property_.UNITS), - this.handleUnitsChanged_, this); + this, BaseObject.getChangeEventType(ScaleLine.Property_.UNITS), + this.handleUnitsChanged_, this); this.setUnits(/** @type {ol.control.ScaleLineUnits} */ (options.units) || ScaleLineUnits.METRIC); @@ -125,7 +125,7 @@ ScaleLine.prototype.getUnits = function() { * @api */ ScaleLine.render = function(mapEvent) { - var frameState = mapEvent.frameState; + const frameState = mapEvent.frameState; if (!frameState) { this.viewState_ = null; } else { @@ -158,7 +158,7 @@ ScaleLine.prototype.setUnits = function(units) { * @private */ ScaleLine.prototype.updateElement_ = function() { - var viewState = this.viewState_; + const viewState = this.viewState_; if (!viewState) { if (this.renderedVisible_) { @@ -168,22 +168,22 @@ ScaleLine.prototype.updateElement_ = function() { return; } - var center = viewState.center; - var projection = viewState.projection; - var units = this.getUnits(); - var pointResolutionUnits = units == ScaleLineUnits.DEGREES ? + const center = viewState.center; + const projection = viewState.projection; + const units = this.getUnits(); + const pointResolutionUnits = units == ScaleLineUnits.DEGREES ? Units.DEGREES : Units.METERS; - var pointResolution = + let pointResolution = getPointResolution(projection, viewState.resolution, center, pointResolutionUnits); if (units != ScaleLineUnits.DEGREES) { pointResolution *= projection.getMetersPerUnit(); } - var nominalCount = this.minWidth_ * pointResolution; - var suffix = ''; + let nominalCount = this.minWidth_ * pointResolution; + let suffix = ''; if (units == ScaleLineUnits.DEGREES) { - var metersPerDegree = METERS_PER_UNIT[Units.DEGREES]; + const metersPerDegree = METERS_PER_UNIT[Units.DEGREES]; if (projection.getUnits() == Units.DEGREES) { nominalCount *= metersPerDegree; } else { @@ -240,9 +240,9 @@ ScaleLine.prototype.updateElement_ = function() { assert(false, 33); // Invalid units } - var i = 3 * Math.floor( - Math.log(this.minWidth_ * pointResolution) / Math.log(10)); - var count, width; + let i = 3 * Math.floor( + Math.log(this.minWidth_ * pointResolution) / Math.log(10)); + let count, width; while (true) { count = ScaleLine.LEADING_DIGITS[((i % 3) + 3) % 3] * Math.pow(10, Math.floor(i / 3)); @@ -257,7 +257,7 @@ ScaleLine.prototype.updateElement_ = function() { ++i; } - var html = count + ' ' + suffix; + const html = count + ' ' + suffix; if (this.renderedHTML_ != html) { this.innerElement_.innerHTML = html; this.renderedHTML_ = html; diff --git a/src/ol/control/Zoom.js b/src/ol/control/Zoom.js index 2545a510b3..234a046a11 100644 --- a/src/ol/control/Zoom.js +++ b/src/ol/control/Zoom.js @@ -19,46 +19,46 @@ import {easeOut} from '../easing.js'; * @param {olx.control.ZoomOptions=} opt_options Zoom options. * @api */ -var Zoom = function(opt_options) { +const Zoom = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; - var className = options.className !== undefined ? options.className : 'ol-zoom'; + const className = options.className !== undefined ? options.className : 'ol-zoom'; - var delta = options.delta !== undefined ? options.delta : 1; + const delta = options.delta !== undefined ? options.delta : 1; - var zoomInLabel = options.zoomInLabel !== undefined ? options.zoomInLabel : '+'; - var zoomOutLabel = options.zoomOutLabel !== undefined ? options.zoomOutLabel : '\u2212'; + const zoomInLabel = options.zoomInLabel !== undefined ? options.zoomInLabel : '+'; + const zoomOutLabel = options.zoomOutLabel !== undefined ? options.zoomOutLabel : '\u2212'; - var zoomInTipLabel = options.zoomInTipLabel !== undefined ? + const zoomInTipLabel = options.zoomInTipLabel !== undefined ? options.zoomInTipLabel : 'Zoom in'; - var zoomOutTipLabel = options.zoomOutTipLabel !== undefined ? + const zoomOutTipLabel = options.zoomOutTipLabel !== undefined ? options.zoomOutTipLabel : 'Zoom out'; - var inElement = document.createElement('button'); + const inElement = document.createElement('button'); inElement.className = className + '-in'; inElement.setAttribute('type', 'button'); inElement.title = zoomInTipLabel; inElement.appendChild( - typeof zoomInLabel === 'string' ? document.createTextNode(zoomInLabel) : zoomInLabel + typeof zoomInLabel === 'string' ? document.createTextNode(zoomInLabel) : zoomInLabel ); _ol_events_.listen(inElement, EventType.CLICK, - Zoom.prototype.handleClick_.bind(this, delta)); + Zoom.prototype.handleClick_.bind(this, delta)); - var outElement = document.createElement('button'); + const outElement = document.createElement('button'); outElement.className = className + '-out'; outElement.setAttribute('type', 'button'); outElement.title = zoomOutTipLabel; outElement.appendChild( - typeof zoomOutLabel === 'string' ? document.createTextNode(zoomOutLabel) : zoomOutLabel + typeof zoomOutLabel === 'string' ? document.createTextNode(zoomOutLabel) : zoomOutLabel ); _ol_events_.listen(outElement, EventType.CLICK, - Zoom.prototype.handleClick_.bind(this, -delta)); + Zoom.prototype.handleClick_.bind(this, -delta)); - var cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL; - var element = document.createElement('div'); + const cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL; + const element = document.createElement('div'); element.className = cssClasses; element.appendChild(inElement); element.appendChild(outElement); @@ -95,16 +95,16 @@ Zoom.prototype.handleClick_ = function(delta, event) { * @private */ Zoom.prototype.zoomByDelta_ = function(delta) { - var map = this.getMap(); - var view = map.getView(); + const map = this.getMap(); + const view = map.getView(); if (!view) { // the map does not have a view, so we can't act // upon it return; } - var currentResolution = view.getResolution(); + const currentResolution = view.getResolution(); if (currentResolution) { - var newResolution = view.constrainResolution(currentResolution, delta); + const newResolution = view.constrainResolution(currentResolution, delta); if (this.duration_ > 0) { if (view.getAnimating()) { view.cancelAnimations(); diff --git a/src/ol/control/ZoomSlider.js b/src/ol/control/ZoomSlider.js index aea9f350b7..1a7a6b8ed9 100644 --- a/src/ol/control/ZoomSlider.js +++ b/src/ol/control/ZoomSlider.js @@ -28,9 +28,9 @@ import PointerEventHandler from '../pointer/PointerEventHandler.js'; * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. * @api */ -var ZoomSlider = function(opt_options) { +const ZoomSlider = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * Will hold the current resolution of the view. @@ -100,11 +100,11 @@ var ZoomSlider = function(opt_options) { */ this.duration_ = options.duration !== undefined ? options.duration : 200; - var className = options.className !== undefined ? options.className : 'ol-zoomslider'; - var thumbElement = document.createElement('button'); + const className = options.className !== undefined ? options.className : 'ol-zoomslider'; + const thumbElement = document.createElement('button'); thumbElement.setAttribute('type', 'button'); thumbElement.className = className + '-thumb ' + CLASS_UNSELECTABLE; - var containerElement = document.createElement('div'); + const containerElement = document.createElement('div'); containerElement.className = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL; containerElement.appendChild(thumbElement); /** @@ -114,18 +114,18 @@ var ZoomSlider = function(opt_options) { this.dragger_ = new PointerEventHandler(containerElement); _ol_events_.listen(this.dragger_, PointerEventType.POINTERDOWN, - this.handleDraggerStart_, this); + this.handleDraggerStart_, this); _ol_events_.listen(this.dragger_, PointerEventType.POINTERMOVE, - this.handleDraggerDrag_, this); + this.handleDraggerDrag_, this); _ol_events_.listen(this.dragger_, PointerEventType.POINTERUP, - this.handleDraggerEnd_, this); + this.handleDraggerEnd_, this); _ol_events_.listen(containerElement, EventType.CLICK, - this.handleContainerClick_, this); + this.handleContainerClick_, this); _ol_events_.listen(thumbElement, EventType.CLICK, - Event.stopPropagation); + Event.stopPropagation); - var render = options.render ? options.render : ZoomSlider.render; + const render = options.render ? options.render : ZoomSlider.render; Control.call(this, { element: containerElement, @@ -176,17 +176,17 @@ ZoomSlider.prototype.setMap = function(map) { * @private */ ZoomSlider.prototype.initSlider_ = function() { - var container = this.element; - var containerSize = { + const container = this.element; + const containerSize = { width: container.offsetWidth, height: container.offsetHeight }; - var thumb = container.firstElementChild; - var computedStyle = getComputedStyle(thumb); - var thumbWidth = thumb.offsetWidth + + const thumb = container.firstElementChild; + const computedStyle = getComputedStyle(thumb); + const thumbWidth = thumb.offsetWidth + parseFloat(computedStyle['marginRight']) + parseFloat(computedStyle['marginLeft']); - var thumbHeight = thumb.offsetHeight + + const thumbHeight = thumb.offsetHeight + parseFloat(computedStyle['marginTop']) + parseFloat(computedStyle['marginBottom']); this.thumbSize_ = [thumbWidth, thumbHeight]; @@ -215,7 +215,7 @@ ZoomSlider.render = function(mapEvent) { if (!this.sliderInitialized_) { this.initSlider_(); } - var res = mapEvent.frameState.viewState.resolution; + const res = mapEvent.frameState.viewState.resolution; if (res !== this.currentResolution_) { this.currentResolution_ = res; this.setThumbPosition_(res); @@ -228,13 +228,13 @@ ZoomSlider.render = function(mapEvent) { * @private */ ZoomSlider.prototype.handleContainerClick_ = function(event) { - var view = this.getMap().getView(); + const view = this.getMap().getView(); - var relativePosition = this.getRelativePosition_( - event.offsetX - this.thumbSize_[0] / 2, - event.offsetY - this.thumbSize_[1] / 2); + const relativePosition = this.getRelativePosition_( + event.offsetX - this.thumbSize_[0] / 2, + event.offsetY - this.thumbSize_[1] / 2); - var resolution = this.getResolutionForPosition_(relativePosition); + const resolution = this.getResolutionForPosition_(relativePosition); view.animate({ resolution: view.constrainResolution(resolution), @@ -267,10 +267,10 @@ ZoomSlider.prototype.handleDraggerStart_ = function(event) { */ ZoomSlider.prototype.handleDraggerDrag_ = function(event) { if (this.dragging_) { - var element = this.element.firstElementChild; - var deltaX = event.clientX - this.previousX_ + parseInt(element.style.left, 10); - var deltaY = event.clientY - this.previousY_ + parseInt(element.style.top, 10); - var relativePosition = this.getRelativePosition_(deltaX, deltaY); + const element = this.element.firstElementChild; + const deltaX = event.clientX - this.previousX_ + parseInt(element.style.left, 10); + const deltaY = event.clientY - this.previousY_ + parseInt(element.style.top, 10); + const relativePosition = this.getRelativePosition_(deltaX, deltaY); this.currentResolution_ = this.getResolutionForPosition_(relativePosition); this.getMap().getView().setResolution(this.currentResolution_); this.setThumbPosition_(this.currentResolution_); @@ -287,7 +287,7 @@ ZoomSlider.prototype.handleDraggerDrag_ = function(event) { */ ZoomSlider.prototype.handleDraggerEnd_ = function(event) { if (this.dragging_) { - var view = this.getMap().getView(); + const view = this.getMap().getView(); view.setHint(ViewHint.INTERACTING, -1); view.animate({ @@ -310,8 +310,8 @@ ZoomSlider.prototype.handleDraggerEnd_ = function(event) { * @private */ ZoomSlider.prototype.setThumbPosition_ = function(res) { - var position = this.getPositionForResolution_(res); - var thumb = this.element.firstElementChild; + const position = this.getPositionForResolution_(res); + const thumb = this.element.firstElementChild; if (this.direction_ == ZoomSlider.Direction_.HORIZONTAL) { thumb.style.left = this.widthLimit_ * position + 'px'; @@ -332,7 +332,7 @@ ZoomSlider.prototype.setThumbPosition_ = function(res) { * @private */ ZoomSlider.prototype.getRelativePosition_ = function(x, y) { - var amount; + let amount; if (this.direction_ === ZoomSlider.Direction_.HORIZONTAL) { amount = x / this.widthLimit_; } else { @@ -351,7 +351,7 @@ ZoomSlider.prototype.getRelativePosition_ = function(x, y) { * @private */ ZoomSlider.prototype.getResolutionForPosition_ = function(position) { - var fn = this.getMap().getView().getResolutionForValueFunction(); + const fn = this.getMap().getView().getResolutionForValueFunction(); return fn(1 - position); }; @@ -366,7 +366,7 @@ ZoomSlider.prototype.getResolutionForPosition_ = function(position) { * @private */ ZoomSlider.prototype.getPositionForResolution_ = function(res) { - var fn = this.getMap().getView().getValueForResolutionFunction(); + const fn = this.getMap().getView().getValueForResolutionFunction(); return 1 - fn(res); }; export default ZoomSlider; diff --git a/src/ol/control/ZoomToExtent.js b/src/ol/control/ZoomToExtent.js index 822f95ec43..51a60f7591 100644 --- a/src/ol/control/ZoomToExtent.js +++ b/src/ol/control/ZoomToExtent.js @@ -17,8 +17,8 @@ import {CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js'; * @param {olx.control.ZoomToExtentOptions=} opt_options Options. * @api */ -var ZoomToExtent = function(opt_options) { - var options = opt_options ? opt_options : {}; +const ZoomToExtent = function(opt_options) { + const options = opt_options ? opt_options : {}; /** * @type {ol.Extent} @@ -26,24 +26,24 @@ var ZoomToExtent = function(opt_options) { */ this.extent = options.extent ? options.extent : null; - var className = options.className !== undefined ? options.className : + const className = options.className !== undefined ? options.className : 'ol-zoom-extent'; - var label = options.label !== undefined ? options.label : 'E'; - var tipLabel = options.tipLabel !== undefined ? + const label = options.label !== undefined ? options.label : 'E'; + const tipLabel = options.tipLabel !== undefined ? options.tipLabel : 'Fit to extent'; - var button = document.createElement('button'); + const button = document.createElement('button'); button.setAttribute('type', 'button'); button.title = tipLabel; button.appendChild( - typeof label === 'string' ? document.createTextNode(label) : label + typeof label === 'string' ? document.createTextNode(label) : label ); _ol_events_.listen(button, EventType.CLICK, - this.handleClick_, this); + this.handleClick_, this); - var cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL; - var element = document.createElement('div'); + const cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL; + const element = document.createElement('div'); element.className = cssClasses; element.appendChild(button); @@ -70,9 +70,9 @@ ZoomToExtent.prototype.handleClick_ = function(event) { * @protected */ ZoomToExtent.prototype.handleZoomToExtent = function() { - var map = this.getMap(); - var view = map.getView(); - var extent = !this.extent ? view.getProjection().getExtent() : this.extent; + const map = this.getMap(); + const view = map.getView(); + const extent = !this.extent ? view.getProjection().getExtent() : this.extent; view.fit(extent); }; export default ZoomToExtent; diff --git a/src/ol/coordinate.js b/src/ol/coordinate.js index 2a4ec0a50d..b8e96d18b7 100644 --- a/src/ol/coordinate.js +++ b/src/ol/coordinate.js @@ -3,7 +3,7 @@ */ import {modulo} from './math.js'; import _ol_string_ from './string.js'; -var _ol_coordinate_ = {}; +const _ol_coordinate_ = {}; /** @@ -36,24 +36,22 @@ _ol_coordinate_.add = function(coordinate, delta) { * @return {ol.Coordinate} Closest point on the circumference */ _ol_coordinate_.closestOnCircle = function(coordinate, circle) { - var r = circle.getRadius(); - var center = circle.getCenter(); - var x0 = center[0]; - var y0 = center[1]; - var x1 = coordinate[0]; - var y1 = coordinate[1]; + const r = circle.getRadius(); + const center = circle.getCenter(); + const x0 = center[0]; + const y0 = center[1]; + const x1 = coordinate[0]; + const y1 = coordinate[1]; - var dx = x1 - x0; - var dy = y1 - y0; + let dx = x1 - x0; + const dy = y1 - y0; if (dx === 0 && dy === 0) { dx = 1; } - var d = Math.sqrt(dx * dx + dy * dy); + const d = Math.sqrt(dx * dx + dy * dy); - var x, y; - - x = x0 + r * dx / d; - y = y0 + r * dy / d; + const x = x0 + r * dx / d; + const y = y0 + r * dy / d; return [x, y]; }; @@ -71,19 +69,19 @@ _ol_coordinate_.closestOnCircle = function(coordinate, circle) { * the segment. */ _ol_coordinate_.closestOnSegment = function(coordinate, segment) { - var x0 = coordinate[0]; - var y0 = coordinate[1]; - var start = segment[0]; - var end = segment[1]; - var x1 = start[0]; - var y1 = start[1]; - var x2 = end[0]; - var y2 = end[1]; - var dx = x2 - x1; - var dy = y2 - y1; - var along = (dx === 0 && dy === 0) ? 0 : + const x0 = coordinate[0]; + const y0 = coordinate[1]; + const start = segment[0]; + const end = segment[1]; + const x1 = start[0]; + const y1 = start[1]; + const x2 = end[0]; + const y2 = end[1]; + const dx = x2 - x1; + const dy = y2 - y1; + const along = (dx === 0 && dy === 0) ? 0 : ((dx * (x0 - x1)) + (dy * (y0 - y1))) / ((dx * dx + dy * dy) || 0); - var x, y; + let x, y; if (along <= 0) { x = x1; y = y1; @@ -142,14 +140,14 @@ _ol_coordinate_.createStringXY = function(opt_fractionDigits) { * @return {string} String. */ _ol_coordinate_.degreesToStringHDMS = function(hemispheres, degrees, opt_fractionDigits) { - var normalizedDegrees = modulo(degrees + 180, 360) - 180; - var x = Math.abs(3600 * normalizedDegrees); - var dflPrecision = opt_fractionDigits || 0; - var precision = Math.pow(10, dflPrecision); + const normalizedDegrees = modulo(degrees + 180, 360) - 180; + const x = Math.abs(3600 * normalizedDegrees); + const dflPrecision = opt_fractionDigits || 0; + const precision = Math.pow(10, dflPrecision); - var deg = Math.floor(x / 3600); - var min = Math.floor((x - deg * 3600) / 60); - var sec = x - (deg * 3600) - (min * 60); + let deg = Math.floor(x / 3600); + let min = Math.floor((x - deg * 3600) / 60); + let sec = x - (deg * 3600) - (min * 60); sec = Math.ceil(sec * precision) / precision; if (sec >= 60) { @@ -198,8 +196,8 @@ _ol_coordinate_.degreesToStringHDMS = function(hemispheres, degrees, opt_fractio _ol_coordinate_.format = function(coordinate, template, opt_fractionDigits) { if (coordinate) { return template - .replace('{x}', coordinate[0].toFixed(opt_fractionDigits)) - .replace('{y}', coordinate[1].toFixed(opt_fractionDigits)); + .replace('{x}', coordinate[0].toFixed(opt_fractionDigits)) + .replace('{y}', coordinate[1].toFixed(opt_fractionDigits)); } else { return ''; } @@ -212,8 +210,8 @@ _ol_coordinate_.format = function(coordinate, template, opt_fractionDigits) { * @return {boolean} Whether the passed coordinates are equal. */ _ol_coordinate_.equals = function(coordinate1, coordinate2) { - var equals = true; - for (var i = coordinate1.length - 1; i >= 0; --i) { + let equals = true; + for (let i = coordinate1.length - 1; i >= 0; --i) { if (coordinate1[i] != coordinate2[i]) { equals = false; break; @@ -240,10 +238,10 @@ _ol_coordinate_.equals = function(coordinate1, coordinate2) { * @api */ _ol_coordinate_.rotate = function(coordinate, angle) { - var cosAngle = Math.cos(angle); - var sinAngle = Math.sin(angle); - var x = coordinate[0] * cosAngle - coordinate[1] * sinAngle; - var y = coordinate[1] * cosAngle + coordinate[0] * sinAngle; + const cosAngle = Math.cos(angle); + const sinAngle = Math.sin(angle); + const x = coordinate[0] * cosAngle - coordinate[1] * sinAngle; + const y = coordinate[1] * cosAngle + coordinate[0] * sinAngle; coordinate[0] = x; coordinate[1] = y; return coordinate; @@ -293,8 +291,8 @@ _ol_coordinate_.sub = function(coordinate, delta) { * @return {number} Squared distance between coord1 and coord2. */ _ol_coordinate_.squaredDistance = function(coord1, coord2) { - var dx = coord1[0] - coord2[0]; - var dy = coord1[1] - coord2[1]; + const dx = coord1[0] - coord2[0]; + const dy = coord1[1] - coord2[1]; return dx * dx + dy * dy; }; @@ -318,7 +316,7 @@ _ol_coordinate_.distance = function(coord1, coord2) { */ _ol_coordinate_.squaredDistanceToSegment = function(coordinate, segment) { return _ol_coordinate_.squaredDistance(coordinate, - _ol_coordinate_.closestOnSegment(coordinate, segment)); + _ol_coordinate_.closestOnSegment(coordinate, segment)); }; diff --git a/src/ol/css.js b/src/ol/css.js index 4af8609d12..bf375a6ce3 100644 --- a/src/ol/css.js +++ b/src/ol/css.js @@ -9,7 +9,7 @@ * @const * @type {string} */ -export var CLASS_HIDDEN = 'ol-hidden'; +export const CLASS_HIDDEN = 'ol-hidden'; /** @@ -18,7 +18,7 @@ export var CLASS_HIDDEN = 'ol-hidden'; * @const * @type {string} */ -export var CLASS_SELECTABLE = 'ol-selectable'; +export const CLASS_SELECTABLE = 'ol-selectable'; /** @@ -27,7 +27,7 @@ export var CLASS_SELECTABLE = 'ol-selectable'; * @const * @type {string} */ -export var CLASS_UNSELECTABLE = 'ol-unselectable'; +export const CLASS_UNSELECTABLE = 'ol-unselectable'; /** @@ -36,7 +36,7 @@ export var CLASS_UNSELECTABLE = 'ol-unselectable'; * @const * @type {string} */ -export var CLASS_UNSUPPORTED = 'ol-unsupported'; +export const CLASS_UNSUPPORTED = 'ol-unsupported'; /** @@ -45,7 +45,7 @@ export var CLASS_UNSUPPORTED = 'ol-unsupported'; * @const * @type {string} */ -export var CLASS_CONTROL = 'ol-control'; +export const CLASS_CONTROL = 'ol-control'; /** @@ -54,16 +54,16 @@ export var CLASS_CONTROL = 'ol-control'; * @param {string} The CSS font property. * @return {Object.} The font families (or null if the input spec is invalid). */ -export var getFontFamilies = (function() { - var style; - var cache = {}; +export const getFontFamilies = (function() { + let style; + const cache = {}; return function(font) { if (!style) { style = document.createElement('div').style; } if (!(font in cache)) { style.font = font; - var family = style.fontFamily; + const family = style.fontFamily; style.font = ''; if (!family) { return null; diff --git a/src/ol/dom.js b/src/ol/dom.js index cbade563de..ee58409535 100644 --- a/src/ol/dom.js +++ b/src/ol/dom.js @@ -10,7 +10,7 @@ * @return {CanvasRenderingContext2D} The context. */ export function createCanvasContext2D(opt_width, opt_height) { - var canvas = document.createElement('CANVAS'); + const canvas = document.createElement('CANVAS'); if (opt_width) { canvas.width = opt_width; } @@ -29,8 +29,8 @@ export function createCanvasContext2D(opt_width, opt_height) { * @return {number} The width. */ export function outerWidth(element) { - var width = element.offsetWidth; - var style = getComputedStyle(element); + let width = element.offsetWidth; + const style = getComputedStyle(element); width += parseInt(style.marginLeft, 10) + parseInt(style.marginRight, 10); return width; @@ -45,8 +45,8 @@ export function outerWidth(element) { * @return {number} The height. */ export function outerHeight(element) { - var height = element.offsetHeight; - var style = getComputedStyle(element); + let height = element.offsetHeight; + const style = getComputedStyle(element); height += parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10); return height; @@ -57,7 +57,7 @@ export function outerHeight(element) { * @param {Node} oldNode The node to be replaced */ export function replaceNode(newNode, oldNode) { - var parent = oldNode.parentNode; + const parent = oldNode.parentNode; if (parent) { parent.replaceChild(newNode, oldNode); } diff --git a/src/ol/events.js b/src/ol/events.js index 50ce11b443..76e0f570ee 100644 --- a/src/ol/events.js +++ b/src/ol/events.js @@ -2,7 +2,7 @@ * @module ol/events */ import _ol_obj_ from './obj.js'; -var _ol_events_ = {}; +const _ol_events_ = {}; /** @@ -10,9 +10,9 @@ var _ol_events_ = {}; * @return {ol.EventsListenerFunctionType} Bound listener. */ _ol_events_.bindListener_ = function(listenerObj) { - var boundListener = function(evt) { - var listener = listenerObj.listener; - var bindTo = listenerObj.bindTo || listenerObj.target; + const boundListener = function(evt) { + const listener = listenerObj.listener; + const bindTo = listenerObj.bindTo || listenerObj.target; if (listenerObj.callOnce) { _ol_events_.unlistenByKey(listenerObj); } @@ -36,9 +36,9 @@ _ol_events_.bindListener_ = function(listenerObj) { * @private */ _ol_events_.findListener_ = function(listeners, listener, opt_this, - opt_setDeleteIndex) { - var listenerObj; - for (var i = 0, ii = listeners.length; i < ii; ++i) { + opt_setDeleteIndex) { + let listenerObj; + for (let i = 0, ii = listeners.length; i < ii; ++i) { listenerObj = listeners[i]; if (listenerObj.listener === listener && listenerObj.bindTo === opt_this) { @@ -58,7 +58,7 @@ _ol_events_.findListener_ = function(listeners, listener, opt_this, * @return {Array.|undefined} Listeners. */ _ol_events_.getListeners = function(target, type) { - var listenerMap = target.ol_lm; + const listenerMap = target.ol_lm; return listenerMap ? listenerMap[type] : undefined; }; @@ -72,7 +72,7 @@ _ol_events_.getListeners = function(target, type) { * @private */ _ol_events_.getListenerMap_ = function(target) { - var listenerMap = target.ol_lm; + let listenerMap = target.ol_lm; if (!listenerMap) { listenerMap = target.ol_lm = {}; } @@ -89,14 +89,14 @@ _ol_events_.getListenerMap_ = function(target) { * @private */ _ol_events_.removeListeners_ = function(target, type) { - var listeners = _ol_events_.getListeners(target, type); + const listeners = _ol_events_.getListeners(target, type); if (listeners) { - for (var i = 0, ii = listeners.length; i < ii; ++i) { + for (let i = 0, ii = listeners.length; i < ii; ++i) { target.removeEventListener(type, listeners[i].boundListener); _ol_obj_.clear(listeners[i]); } listeners.length = 0; - var listenerMap = target.ol_lm; + const listenerMap = target.ol_lm; if (listenerMap) { delete listenerMap[type]; if (Object.keys(listenerMap).length === 0) { @@ -123,13 +123,13 @@ _ol_events_.removeListeners_ = function(target, type) { * @return {ol.EventsKey} Unique key for the listener. */ _ol_events_.listen = function(target, type, listener, opt_this, opt_once) { - var listenerMap = _ol_events_.getListenerMap_(target); - var listeners = listenerMap[type]; + const listenerMap = _ol_events_.getListenerMap_(target); + let listeners = listenerMap[type]; if (!listeners) { listeners = listenerMap[type] = []; } - var listenerObj = _ol_events_.findListener_(listeners, listener, opt_this, - false); + let listenerObj = _ol_events_.findListener_(listeners, listener, opt_this, + false); if (listenerObj) { if (!opt_once) { // Turn one-off listener into a permanent one. @@ -190,10 +190,10 @@ _ol_events_.listenOnce = function(target, type, listener, opt_this) { * listener. Default is the `target`. */ _ol_events_.unlisten = function(target, type, listener, opt_this) { - var listeners = _ol_events_.getListeners(target, type); + const listeners = _ol_events_.getListeners(target, type); if (listeners) { - var listenerObj = _ol_events_.findListener_(listeners, listener, opt_this, - true); + const listenerObj = _ol_events_.findListener_(listeners, listener, opt_this, + true); if (listenerObj) { _ol_events_.unlistenByKey(listenerObj); } @@ -213,9 +213,9 @@ _ol_events_.unlisten = function(target, type, listener, opt_this) { _ol_events_.unlistenByKey = function(key) { if (key && key.target) { key.target.removeEventListener(key.type, key.boundListener); - var listeners = _ol_events_.getListeners(key.target, key.type); + const listeners = _ol_events_.getListeners(key.target, key.type); if (listeners) { - var i = 'deleteIndex' in key ? key.deleteIndex : listeners.indexOf(key); + const i = 'deleteIndex' in key ? key.deleteIndex : listeners.indexOf(key); if (i !== -1) { listeners.splice(i, 1); } @@ -235,8 +235,8 @@ _ol_events_.unlistenByKey = function(key) { * @param {ol.EventTargetLike} target Target. */ _ol_events_.unlistenAll = function(target) { - var listenerMap = _ol_events_.getListenerMap_(target); - for (var type in listenerMap) { + const listenerMap = _ol_events_.getListenerMap_(target); + for (const type in listenerMap) { _ol_events_.removeListeners_(target, type); } }; diff --git a/src/ol/events/Event.js b/src/ol/events/Event.js index e5255990e7..8756c1bca7 100644 --- a/src/ol/events/Event.js +++ b/src/ol/events/Event.js @@ -15,7 +15,7 @@ * @implements {oli.events.Event} * @param {string} type Type. */ -var Event = function(type) { +const Event = function(type) { /** * @type {boolean} diff --git a/src/ol/events/EventTarget.js b/src/ol/events/EventTarget.js index 2436d14e11..d20b688116 100644 --- a/src/ol/events/EventTarget.js +++ b/src/ol/events/EventTarget.js @@ -24,7 +24,7 @@ import Event from '../events/Event.js'; * @constructor * @extends {ol.Disposable} */ -var EventTarget = function() { +const EventTarget = function() { Disposable.call(this); @@ -56,7 +56,7 @@ inherits(EventTarget, Disposable); * @param {ol.EventsListenerFunctionType} listener Listener. */ EventTarget.prototype.addEventListener = function(type, listener) { - var listeners = this.listeners_[type]; + let listeners = this.listeners_[type]; if (!listeners) { listeners = this.listeners_[type] = []; } @@ -74,18 +74,18 @@ EventTarget.prototype.addEventListener = function(type, listener) { * event object or if any of the listeners returned false. */ EventTarget.prototype.dispatchEvent = function(event) { - var evt = typeof event === 'string' ? new Event(event) : event; - var type = evt.type; + const evt = typeof event === 'string' ? new Event(event) : event; + const type = evt.type; evt.target = this; - var listeners = this.listeners_[type]; - var propagate; + const listeners = this.listeners_[type]; + let propagate; if (listeners) { if (!(type in this.dispatching_)) { this.dispatching_[type] = 0; this.pendingRemovals_[type] = 0; } ++this.dispatching_[type]; - for (var i = 0, ii = listeners.length; i < ii; ++i) { + for (let i = 0, ii = listeners.length; i < ii; ++i) { if (listeners[i].call(this, evt) === false || evt.propagationStopped) { propagate = false; break; @@ -93,7 +93,7 @@ EventTarget.prototype.dispatchEvent = function(event) { } --this.dispatching_[type]; if (this.dispatching_[type] === 0) { - var pendingRemovals = this.pendingRemovals_[type]; + let pendingRemovals = this.pendingRemovals_[type]; delete this.pendingRemovals_[type]; while (pendingRemovals--) { this.removeEventListener(type, nullFunction); @@ -142,9 +142,9 @@ EventTarget.prototype.hasListener = function(opt_type) { * @param {ol.EventsListenerFunctionType} listener Listener. */ EventTarget.prototype.removeEventListener = function(type, listener) { - var listeners = this.listeners_[type]; + const listeners = this.listeners_[type]; if (listeners) { - var index = listeners.indexOf(listener); + const index = listeners.indexOf(listener); if (type in this.pendingRemovals_) { // make listener a no-op, and remove later in #dispatchEvent() listeners[index] = nullFunction; diff --git a/src/ol/events/condition.js b/src/ol/events/condition.js index 299526a004..9c31d9123a 100644 --- a/src/ol/events/condition.js +++ b/src/ol/events/condition.js @@ -5,7 +5,7 @@ import MapBrowserEventType from '../MapBrowserEventType.js'; import {assert} from '../asserts.js'; import {TRUE, FALSE} from '../functions.js'; import _ol_has_ from '../has.js'; -var _ol_events_condition_ = {}; +const _ol_events_condition_ = {}; /** @@ -17,7 +17,7 @@ var _ol_events_condition_ = {}; * @api */ _ol_events_condition_.altKeyOnly = function(mapBrowserEvent) { - var originalEvent = mapBrowserEvent.originalEvent; + const originalEvent = mapBrowserEvent.originalEvent; return ( originalEvent.altKey && !(originalEvent.metaKey || originalEvent.ctrlKey) && @@ -34,7 +34,7 @@ _ol_events_condition_.altKeyOnly = function(mapBrowserEvent) { * @api */ _ol_events_condition_.altShiftKeysOnly = function(mapBrowserEvent) { - var originalEvent = mapBrowserEvent.originalEvent; + const originalEvent = mapBrowserEvent.originalEvent; return ( originalEvent.altKey && !(originalEvent.metaKey || originalEvent.ctrlKey) && @@ -75,7 +75,7 @@ _ol_events_condition_.click = function(mapBrowserEvent) { * @return {boolean} The result. */ _ol_events_condition_.mouseActionButton = function(mapBrowserEvent) { - var originalEvent = mapBrowserEvent.originalEvent; + const originalEvent = mapBrowserEvent.originalEvent; return originalEvent.button == 0 && !(_ol_has_.WEBKIT && _ol_has_.MAC && originalEvent.ctrlKey); }; @@ -138,7 +138,7 @@ _ol_events_condition_.doubleClick = function(mapBrowserEvent) { * @api */ _ol_events_condition_.noModifierKeys = function(mapBrowserEvent) { - var originalEvent = mapBrowserEvent.originalEvent; + const originalEvent = mapBrowserEvent.originalEvent; return ( !originalEvent.altKey && !(originalEvent.metaKey || originalEvent.ctrlKey) && @@ -156,7 +156,7 @@ _ol_events_condition_.noModifierKeys = function(mapBrowserEvent) { * @api */ _ol_events_condition_.platformModifierKeyOnly = function(mapBrowserEvent) { - var originalEvent = mapBrowserEvent.originalEvent; + const originalEvent = mapBrowserEvent.originalEvent; return !originalEvent.altKey && (_ol_has_.MAC ? originalEvent.metaKey : originalEvent.ctrlKey) && !originalEvent.shiftKey; @@ -172,7 +172,7 @@ _ol_events_condition_.platformModifierKeyOnly = function(mapBrowserEvent) { * @api */ _ol_events_condition_.shiftKeyOnly = function(mapBrowserEvent) { - var originalEvent = mapBrowserEvent.originalEvent; + const originalEvent = mapBrowserEvent.originalEvent; return ( !originalEvent.altKey && !(originalEvent.metaKey || originalEvent.ctrlKey) && @@ -189,8 +189,8 @@ _ol_events_condition_.shiftKeyOnly = function(mapBrowserEvent) { * @api */ _ol_events_condition_.targetNotEditable = function(mapBrowserEvent) { - var target = mapBrowserEvent.originalEvent.target; - var tagName = target.tagName; + const target = mapBrowserEvent.originalEvent.target; + const tagName = target.tagName; return ( tagName !== 'INPUT' && tagName !== 'SELECT' && @@ -222,7 +222,7 @@ _ol_events_condition_.mouseOnly = function(mapBrowserEvent) { * @api */ _ol_events_condition_.primaryAction = function(mapBrowserEvent) { - var pointerEvent = mapBrowserEvent.pointerEvent; + const pointerEvent = mapBrowserEvent.pointerEvent; return pointerEvent.isPrimary && pointerEvent.button === 0; }; export default _ol_events_condition_; diff --git a/src/ol/extent.js b/src/ol/extent.js index f9fa970e9e..3091ad7a12 100644 --- a/src/ol/extent.js +++ b/src/ol/extent.js @@ -14,8 +14,8 @@ import Relationship from './extent/Relationship.js'; * @api */ export function boundingExtent(coordinates) { - var extent = createEmpty(); - for (var i = 0, ii = coordinates.length; i < ii; ++i) { + const extent = createEmpty(); + for (let i = 0, ii = coordinates.length; i < ii; ++i) { extendCoordinate(extent, coordinates[i]); } return extent; @@ -30,10 +30,10 @@ export function boundingExtent(coordinates) { * @return {ol.Extent} Extent. */ function _boundingExtentXYs(xs, ys, opt_extent) { - var minX = Math.min.apply(null, xs); - var minY = Math.min.apply(null, ys); - var maxX = Math.max.apply(null, xs); - var maxY = Math.max.apply(null, ys); + const minX = Math.min.apply(null, xs); + const minY = Math.min.apply(null, ys); + const maxX = Math.max.apply(null, xs); + const maxY = Math.max.apply(null, ys); return createOrUpdate(minX, minY, maxX, maxY, opt_extent); } @@ -91,7 +91,7 @@ export function clone(extent, opt_extent) { * @return {number} Closest squared distance. */ export function closestSquaredDistanceXY(extent, x, y) { - var dx, dy; + let dx, dy; if (x < extent[0]) { dx = extent[0] - x; } else if (extent[2] < x) { @@ -163,13 +163,13 @@ export function containsXY(extent, x, y) { * ol.extent.Relationship). */ export function coordinateRelationship(extent, coordinate) { - var minX = extent[0]; - var minY = extent[1]; - var maxX = extent[2]; - var maxY = extent[3]; - var x = coordinate[0]; - var y = coordinate[1]; - var relationship = Relationship.UNKNOWN; + const minX = extent[0]; + const minY = extent[1]; + const maxX = extent[2]; + const maxY = extent[3]; + const x = coordinate[0]; + const y = coordinate[1]; + let relationship = Relationship.UNKNOWN; if (x < minX) { relationship = relationship | Relationship.LEFT; } else if (x > maxX) { @@ -226,7 +226,7 @@ export function createOrUpdate(minX, minY, maxX, maxY, opt_extent) { */ export function createOrUpdateEmpty(opt_extent) { return createOrUpdate( - Infinity, Infinity, -Infinity, -Infinity, opt_extent); + Infinity, Infinity, -Infinity, -Infinity, opt_extent); } @@ -236,8 +236,8 @@ export function createOrUpdateEmpty(opt_extent) { * @return {ol.Extent} Extent. */ export function createOrUpdateFromCoordinate(coordinate, opt_extent) { - var x = coordinate[0]; - var y = coordinate[1]; + const x = coordinate[0]; + const y = coordinate[1]; return createOrUpdate(x, y, x, y, opt_extent); } @@ -248,7 +248,7 @@ export function createOrUpdateFromCoordinate(coordinate, opt_extent) { * @return {ol.Extent} Extent. */ export function createOrUpdateFromCoordinates(coordinates, opt_extent) { - var extent = createOrUpdateEmpty(opt_extent); + const extent = createOrUpdateEmpty(opt_extent); return extendCoordinates(extent, coordinates); } @@ -262,7 +262,7 @@ export function createOrUpdateFromCoordinates(coordinates, opt_extent) { * @return {ol.Extent} Extent. */ export function createOrUpdateFromFlatCoordinates(flatCoordinates, offset, end, stride, opt_extent) { - var extent = createOrUpdateEmpty(opt_extent); + const extent = createOrUpdateEmpty(opt_extent); return extendFlatCoordinates(extent, flatCoordinates, offset, end, stride); } @@ -272,7 +272,7 @@ export function createOrUpdateFromFlatCoordinates(flatCoordinates, offset, end, * @return {ol.Extent} Extent. */ export function createOrUpdateFromRings(rings, opt_extent) { - var extent = createOrUpdateEmpty(opt_extent); + const extent = createOrUpdateEmpty(opt_extent); return extendRings(extent, rings); } @@ -340,7 +340,7 @@ export function extendCoordinate(extent, coordinate) { * @return {ol.Extent} Extent. */ export function extendCoordinates(extent, coordinates) { - var i, ii; + let i, ii; for (i = 0, ii = coordinates.length; i < ii; ++i) { extendCoordinate(extent, coordinates[i]); } @@ -370,7 +370,7 @@ export function extendFlatCoordinates(extent, flatCoordinates, offset, end, stri * @return {ol.Extent} Extent. */ export function extendRings(extent, rings) { - var i, ii; + let i, ii; for (i = 0, ii = rings.length; i < ii; ++i) { extendCoordinates(extent, rings[i]); } @@ -402,7 +402,7 @@ export function extendXY(extent, x, y) { * @template S, T */ export function forEachCorner(extent, callback, opt_this) { - var val; + let val; val = callback.call(opt_this, getBottomLeft(extent)); if (val) { return val; @@ -430,7 +430,7 @@ export function forEachCorner(extent, callback, opt_this) { * @api */ export function getArea(extent) { - var area = 0; + let area = 0; if (!isEmpty(extent)) { area = getWidth(extent) * getHeight(extent); } @@ -478,7 +478,7 @@ export function getCenter(extent) { * @return {ol.Coordinate} Corner coordinate. */ export function getCorner(extent, corner) { - var coordinate; + let coordinate; if (corner === Corner.BOTTOM_LEFT) { coordinate = getBottomLeft(extent); } else if (corner === Corner.BOTTOM_RIGHT) { @@ -500,10 +500,10 @@ export function getCorner(extent, corner) { * @return {number} Enlarged area. */ export function getEnlargedArea(extent1, extent2) { - var minX = Math.min(extent1[0], extent2[0]); - var minY = Math.min(extent1[1], extent2[1]); - var maxX = Math.max(extent1[2], extent2[2]); - var maxY = Math.max(extent1[3], extent2[3]); + const minX = Math.min(extent1[0], extent2[0]); + const minY = Math.min(extent1[1], extent2[1]); + const maxX = Math.max(extent1[2], extent2[2]); + const maxY = Math.max(extent1[3], extent2[3]); return (maxX - minX) * (maxY - minY); } @@ -517,28 +517,28 @@ export function getEnlargedArea(extent1, extent2) { * @return {ol.Extent} Extent. */ export function getForViewAndSize(center, resolution, rotation, size, opt_extent) { - var dx = resolution * size[0] / 2; - var dy = resolution * size[1] / 2; - var cosRotation = Math.cos(rotation); - var sinRotation = Math.sin(rotation); - var xCos = dx * cosRotation; - var xSin = dx * sinRotation; - var yCos = dy * cosRotation; - var ySin = dy * sinRotation; - var x = center[0]; - var y = center[1]; - var x0 = x - xCos + ySin; - var x1 = x - xCos - ySin; - var x2 = x + xCos - ySin; - var x3 = x + xCos + ySin; - var y0 = y - xSin - yCos; - var y1 = y - xSin + yCos; - var y2 = y + xSin + yCos; - var y3 = y + xSin - yCos; + const dx = resolution * size[0] / 2; + const dy = resolution * size[1] / 2; + const cosRotation = Math.cos(rotation); + const sinRotation = Math.sin(rotation); + const xCos = dx * cosRotation; + const xSin = dx * sinRotation; + const yCos = dy * cosRotation; + const ySin = dy * sinRotation; + const x = center[0]; + const y = center[1]; + const x0 = x - xCos + ySin; + const x1 = x - xCos - ySin; + const x2 = x + xCos - ySin; + const x3 = x + xCos + ySin; + const y0 = y - xSin - yCos; + const y1 = y - xSin + yCos; + const y2 = y + xSin + yCos; + const y3 = y + xSin - yCos; return createOrUpdate( - Math.min(x0, x1, x2, x3), Math.min(y0, y1, y2, y3), - Math.max(x0, x1, x2, x3), Math.max(y0, y1, y2, y3), - opt_extent); + Math.min(x0, x1, x2, x3), Math.min(y0, y1, y2, y3), + Math.max(x0, x1, x2, x3), Math.max(y0, y1, y2, y3), + opt_extent); } @@ -559,7 +559,7 @@ export function getHeight(extent) { * @return {number} Intersection area. */ export function getIntersectionArea(extent1, extent2) { - var intersection = getIntersection(extent1, extent2); + const intersection = getIntersection(extent1, extent2); return getArea(intersection); } @@ -573,7 +573,7 @@ export function getIntersectionArea(extent1, extent2) { * @api */ export function getIntersection(extent1, extent2, opt_extent) { - var intersection = opt_extent ? opt_extent : createEmpty(); + const intersection = opt_extent ? opt_extent : createEmpty(); if (intersects(extent1, extent2)) { if (extent1[0] > extent2[0]) { intersection[0] = extent1[0]; @@ -702,8 +702,8 @@ export function returnOrUpdate(extent, opt_extent) { * @param {number} value Value. */ export function scaleFromCenter(extent, value) { - var deltaX = ((extent[2] - extent[0]) / 2) * (value - 1); - var deltaY = ((extent[3] - extent[1]) / 2) * (value - 1); + const deltaX = ((extent[2] - extent[0]) / 2) * (value - 1); + const deltaY = ((extent[3] - extent[1]) / 2) * (value - 1); extent[0] -= deltaX; extent[2] += deltaX; extent[1] -= deltaY; @@ -720,23 +720,23 @@ export function scaleFromCenter(extent, value) { * @return {boolean} The segment intersects the extent. */ export function intersectsSegment(extent, start, end) { - var intersects = false; - var startRel = coordinateRelationship(extent, start); - var endRel = coordinateRelationship(extent, end); + let intersects = false; + const startRel = coordinateRelationship(extent, start); + const endRel = coordinateRelationship(extent, end); if (startRel === Relationship.INTERSECTING || endRel === Relationship.INTERSECTING) { intersects = true; } else { - var minX = extent[0]; - var minY = extent[1]; - var maxX = extent[2]; - var maxY = extent[3]; - var startX = start[0]; - var startY = start[1]; - var endX = end[0]; - var endY = end[1]; - var slope = (endY - startY) / (endX - startX); - var x, y; + const minX = extent[0]; + const minY = extent[1]; + const maxX = extent[2]; + const maxY = extent[3]; + const startX = start[0]; + const startY = start[1]; + const endX = end[0]; + const endY = end[1]; + const slope = (endY - startY) / (endX - startX); + let x, y; if (!!(endRel & Relationship.ABOVE) && !(startRel & Relationship.ABOVE)) { // potentially intersects top @@ -777,14 +777,14 @@ export function intersectsSegment(extent, start, end) { * @api */ export function applyTransform(extent, transformFn, opt_extent) { - var coordinates = [ + const coordinates = [ extent[0], extent[1], extent[0], extent[3], extent[2], extent[1], extent[2], extent[3] ]; transformFn(coordinates, coordinates, 2); - var xs = [coordinates[0], coordinates[2], coordinates[4], coordinates[6]]; - var ys = [coordinates[1], coordinates[3], coordinates[5], coordinates[7]]; + const xs = [coordinates[0], coordinates[2], coordinates[4], coordinates[6]]; + const ys = [coordinates[1], coordinates[3], coordinates[5], coordinates[7]]; return _boundingExtentXYs(xs, ys, opt_extent); } diff --git a/src/ol/featureloader.js b/src/ol/featureloader.js index a456b67692..168355f821 100644 --- a/src/ol/featureloader.js +++ b/src/ol/featureloader.js @@ -26,10 +26,10 @@ export function loadFeaturesXhr(url, format, success, failure) { * @this {ol.source.Vector|ol.VectorTile} */ function(extent, resolution, projection) { - var xhr = new XMLHttpRequest(); + const xhr = new XMLHttpRequest(); xhr.open('GET', - typeof url === 'function' ? url(extent, resolution, projection) : url, - true); + typeof url === 'function' ? url(extent, resolution, projection) : url, + true); if (format.getType() == FormatType.ARRAY_BUFFER) { xhr.responseType = 'arraybuffer'; } @@ -40,9 +40,9 @@ export function loadFeaturesXhr(url, format, success, failure) { xhr.onload = function(event) { // status will be 0 for file:// urls if (!xhr.status || xhr.status >= 200 && xhr.status < 300) { - var type = format.getType(); + const type = format.getType(); /** @type {Document|Node|Object|string|undefined} */ - var source; + let source; if (type == FormatType.JSON || type == FormatType.TEXT) { source = xhr.responseText; } else if (type == FormatType.XML) { @@ -55,7 +55,7 @@ export function loadFeaturesXhr(url, format, success, failure) { } if (source) { success.call(this, format.readFeatures(source, - {featureProjection: projection}), + {featureProjection: projection}), format.readProjection(source), format.getLastExtent()); } else { failure.call(this); @@ -87,12 +87,12 @@ export function loadFeaturesXhr(url, format, success, failure) { */ export function xhr(url, format) { return loadFeaturesXhr(url, format, - /** + /** * @param {Array.} features The loaded features. * @param {ol.proj.Projection} dataProjection Data projection. * @this {ol.source.Vector} */ - function(features, dataProjection) { - this.addFeatures(features); - }, /* FIXME handle error */ nullFunction); + function(features, dataProjection) { + this.addFeatures(features); + }, /* FIXME handle error */ nullFunction); } diff --git a/src/ol/format/EsriJSON.js b/src/ol/format/EsriJSON.js index 60705ec6af..7d270a23fa 100644 --- a/src/ol/format/EsriJSON.js +++ b/src/ol/format/EsriJSON.js @@ -30,9 +30,9 @@ import {get as getProjection} from '../proj.js'; * @param {olx.format.EsriJSONOptions=} opt_options Options. * @api */ -var EsriJSON = function(opt_options) { +const EsriJSON = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; JSONFeature.call(this); @@ -59,7 +59,7 @@ EsriJSON.readGeometry_ = function(object, opt_options) { return null; } /** @type {ol.geom.GeometryType} */ - var type; + let type; if (typeof object.x === 'number' && typeof object.y === 'number') { type = GeometryType.POINT; } else if (object.points) { @@ -71,8 +71,8 @@ EsriJSON.readGeometry_ = function(object, opt_options) { type = GeometryType.MULTI_LINE_STRING; } } else if (object.rings) { - var layout = EsriJSON.getGeometryLayout_(object); - var rings = EsriJSON.convertRings_(object.rings, layout); + const layout = EsriJSON.getGeometryLayout_(object); + const rings = EsriJSON.convertRings_(object.rings, layout); object = /** @type {EsriJSONGeometry} */(_ol_obj_.assign({}, object)); if (rings.length === 1) { type = GeometryType.POLYGON; @@ -82,10 +82,10 @@ EsriJSON.readGeometry_ = function(object, opt_options) { object.rings = rings; } } - var geometryReader = EsriJSON.GEOMETRY_READERS_[type]; + const geometryReader = EsriJSON.GEOMETRY_READERS_[type]; return ( /** @type {ol.geom.Geometry} */ transformWithOptions( - geometryReader(object), false, opt_options) + geometryReader(object), false, opt_options) ); }; @@ -101,16 +101,16 @@ EsriJSON.readGeometry_ = function(object, opt_options) { * @return {Array.>>} Transformed rings. */ EsriJSON.convertRings_ = function(rings, layout) { - var flatRing = []; - var outerRings = []; - var holes = []; - var i, ii; + const flatRing = []; + const outerRings = []; + const holes = []; + let i, ii; for (i = 0, ii = rings.length; i < ii; ++i) { flatRing.length = 0; _ol_geom_flat_deflate_.coordinates(flatRing, 0, rings[i], layout.length); // is this ring an outer ring? is it clockwise? - var clockwise = _ol_geom_flat_orient_.linearRingIsClockwise(flatRing, 0, - flatRing.length, layout.length); + const clockwise = _ol_geom_flat_orient_.linearRingIsClockwise(flatRing, 0, + flatRing.length, layout.length); if (clockwise) { outerRings.push([rings[i]]); } else { @@ -118,14 +118,14 @@ EsriJSON.convertRings_ = function(rings, layout) { } } while (holes.length) { - var hole = holes.shift(); - var matched = false; + const hole = holes.shift(); + let matched = false; // loop over all outer rings and see if they contain our hole. for (i = outerRings.length - 1; i >= 0; i--) { - var outerRing = outerRings[i][0]; - var containsHole = containsExtent( - new LinearRing(outerRing).getExtent(), - new LinearRing(hole).getExtent() + const outerRing = outerRings[i][0]; + const containsHole = containsExtent( + new LinearRing(outerRing).getExtent(), + new LinearRing(hole).getExtent() ); if (containsHole) { // the hole is contained push it into our polygon @@ -150,16 +150,16 @@ EsriJSON.convertRings_ = function(rings, layout) { * @return {ol.geom.Geometry} Point. */ EsriJSON.readPointGeometry_ = function(object) { - var point; + let point; if (object.m !== undefined && object.z !== undefined) { point = new Point([object.x, object.y, object.z, object.m], - GeometryLayout.XYZM); + GeometryLayout.XYZM); } else if (object.z !== undefined) { point = new Point([object.x, object.y, object.z], - GeometryLayout.XYZ); + GeometryLayout.XYZ); } else if (object.m !== undefined) { point = new Point([object.x, object.y, object.m], - GeometryLayout.XYM); + GeometryLayout.XYM); } else { point = new Point([object.x, object.y]); } @@ -173,7 +173,7 @@ EsriJSON.readPointGeometry_ = function(object) { * @return {ol.geom.Geometry} LineString. */ EsriJSON.readLineStringGeometry_ = function(object) { - var layout = EsriJSON.getGeometryLayout_(object); + const layout = EsriJSON.getGeometryLayout_(object); return new LineString(object.paths[0], layout); }; @@ -184,7 +184,7 @@ EsriJSON.readLineStringGeometry_ = function(object) { * @return {ol.geom.Geometry} MultiLineString. */ EsriJSON.readMultiLineStringGeometry_ = function(object) { - var layout = EsriJSON.getGeometryLayout_(object); + const layout = EsriJSON.getGeometryLayout_(object); return new MultiLineString(object.paths, layout); }; @@ -195,7 +195,7 @@ EsriJSON.readMultiLineStringGeometry_ = function(object) { * @return {ol.geom.GeometryLayout} The geometry layout to use. */ EsriJSON.getGeometryLayout_ = function(object) { - var layout = GeometryLayout.XY; + let layout = GeometryLayout.XY; if (object.hasZ === true && object.hasM === true) { layout = GeometryLayout.XYZM; } else if (object.hasZ === true) { @@ -213,7 +213,7 @@ EsriJSON.getGeometryLayout_ = function(object) { * @return {ol.geom.Geometry} MultiPoint. */ EsriJSON.readMultiPointGeometry_ = function(object) { - var layout = EsriJSON.getGeometryLayout_(object); + const layout = EsriJSON.getGeometryLayout_(object); return new MultiPoint(object.points, layout); }; @@ -224,10 +224,10 @@ EsriJSON.readMultiPointGeometry_ = function(object) { * @return {ol.geom.Geometry} MultiPolygon. */ EsriJSON.readMultiPolygonGeometry_ = function(object) { - var layout = EsriJSON.getGeometryLayout_(object); + const layout = EsriJSON.getGeometryLayout_(object); return new MultiPolygon( - /** @type {Array.>>>} */(object.rings), - layout); + /** @type {Array.>>>} */(object.rings), + layout); }; @@ -237,7 +237,7 @@ EsriJSON.readMultiPolygonGeometry_ = function(object) { * @return {ol.geom.Geometry} Polygon. */ EsriJSON.readPolygonGeometry_ = function(object) { - var layout = EsriJSON.getGeometryLayout_(object); + const layout = EsriJSON.getGeometryLayout_(object); return new Polygon(object.rings, layout); }; @@ -249,9 +249,9 @@ EsriJSON.readPolygonGeometry_ = function(object) { * @return {EsriJSONGeometry} EsriJSON geometry. */ EsriJSON.writePointGeometry_ = function(geometry, opt_options) { - var coordinates = /** @type {ol.geom.Point} */ (geometry).getCoordinates(); - var esriJSON; - var layout = /** @type {ol.geom.Point} */ (geometry).getLayout(); + const coordinates = /** @type {ol.geom.Point} */ (geometry).getCoordinates(); + let esriJSON; + const layout = /** @type {ol.geom.Point} */ (geometry).getLayout(); if (layout === GeometryLayout.XYZ) { esriJSON = /** @type {EsriJSONPoint} */ ({ x: coordinates[0], @@ -289,7 +289,7 @@ EsriJSON.writePointGeometry_ = function(geometry, opt_options) { * @return {Object} Object with boolean hasZ and hasM keys. */ EsriJSON.getHasZM_ = function(geometry) { - var layout = geometry.getLayout(); + const layout = geometry.getLayout(); return { hasZ: (layout === GeometryLayout.XYZ || layout === GeometryLayout.XYZM), @@ -306,7 +306,7 @@ EsriJSON.getHasZM_ = function(geometry) { * @return {EsriJSONPolyline} EsriJSON geometry. */ EsriJSON.writeLineStringGeometry_ = function(geometry, opt_options) { - var hasZM = EsriJSON.getHasZM_(/** @type {ol.geom.LineString} */(geometry)); + const hasZM = EsriJSON.getHasZM_(/** @type {ol.geom.LineString} */(geometry)); return /** @type {EsriJSONPolyline} */ ({ hasZ: hasZM.hasZ, hasM: hasZM.hasM, @@ -325,7 +325,7 @@ EsriJSON.writeLineStringGeometry_ = function(geometry, opt_options) { */ EsriJSON.writePolygonGeometry_ = function(geometry, opt_options) { // Esri geometries use the left-hand rule - var hasZM = EsriJSON.getHasZM_(/** @type {ol.geom.Polygon} */(geometry)); + const hasZM = EsriJSON.getHasZM_(/** @type {ol.geom.Polygon} */(geometry)); return /** @type {EsriJSONPolygon} */ ({ hasZ: hasZM.hasZ, hasM: hasZM.hasM, @@ -341,7 +341,7 @@ EsriJSON.writePolygonGeometry_ = function(geometry, opt_options) { * @return {EsriJSONPolyline} EsriJSON geometry. */ EsriJSON.writeMultiLineStringGeometry_ = function(geometry, opt_options) { - var hasZM = EsriJSON.getHasZM_(/** @type {ol.geom.MultiLineString} */(geometry)); + const hasZM = EsriJSON.getHasZM_(/** @type {ol.geom.MultiLineString} */(geometry)); return /** @type {EsriJSONPolyline} */ ({ hasZ: hasZM.hasZ, hasM: hasZM.hasM, @@ -357,7 +357,7 @@ EsriJSON.writeMultiLineStringGeometry_ = function(geometry, opt_options) { * @return {EsriJSONMultipoint} EsriJSON geometry. */ EsriJSON.writeMultiPointGeometry_ = function(geometry, opt_options) { - var hasZM = EsriJSON.getHasZM_(/** @type {ol.geom.MultiPoint} */(geometry)); + const hasZM = EsriJSON.getHasZM_(/** @type {ol.geom.MultiPoint} */(geometry)); return /** @type {EsriJSONMultipoint} */ ({ hasZ: hasZM.hasZ, hasM: hasZM.hasM, @@ -373,12 +373,12 @@ EsriJSON.writeMultiPointGeometry_ = function(geometry, opt_options) { * @return {EsriJSONPolygon} EsriJSON geometry. */ EsriJSON.writeMultiPolygonGeometry_ = function(geometry, - opt_options) { - var hasZM = EsriJSON.getHasZM_(/** @type {ol.geom.MultiPolygon} */(geometry)); - var coordinates = /** @type {ol.geom.MultiPolygon} */ (geometry).getCoordinates(false); - var output = []; - for (var i = 0; i < coordinates.length; i++) { - for (var x = coordinates[i].length - 1; x >= 0; x--) { + opt_options) { + const hasZM = EsriJSON.getHasZM_(/** @type {ol.geom.MultiPolygon} */(geometry)); + const coordinates = /** @type {ol.geom.MultiPolygon} */ (geometry).getCoordinates(false); + const output = []; + for (let i = 0; i < coordinates.length; i++) { + for (let x = coordinates[i].length - 1; x >= 0; x--) { output.push(coordinates[i][x]); } } @@ -460,11 +460,11 @@ EsriJSON.prototype.readFeatures; * @inheritDoc */ EsriJSON.prototype.readFeatureFromObject = function( - object, opt_options) { - var esriJSONFeature = /** @type {EsriJSONFeature} */ (object); - var geometry = EsriJSON.readGeometry_(esriJSONFeature.geometry, - opt_options); - var feature = new Feature(); + object, opt_options) { + const esriJSONFeature = /** @type {EsriJSONFeature} */ (object); + const geometry = EsriJSON.readGeometry_(esriJSONFeature.geometry, + opt_options); + const feature = new Feature(); if (this.geometryName_) { feature.setGeometryName(this.geometryName_); } @@ -485,20 +485,20 @@ EsriJSON.prototype.readFeatureFromObject = function( * @inheritDoc */ EsriJSON.prototype.readFeaturesFromObject = function( - object, opt_options) { - var esriJSONObject = /** @type {EsriJSONObject} */ (object); - var options = opt_options ? opt_options : {}; + object, opt_options) { + const esriJSONObject = /** @type {EsriJSONObject} */ (object); + const options = opt_options ? opt_options : {}; if (esriJSONObject.features) { - var esriJSONFeatureCollection = /** @type {EsriJSONFeatureCollection} */ + const esriJSONFeatureCollection = /** @type {EsriJSONFeatureCollection} */ (object); /** @type {Array.} */ - var features = []; - var esriJSONFeatures = esriJSONFeatureCollection.features; - var i, ii; + const features = []; + const esriJSONFeatures = esriJSONFeatureCollection.features; + let i, ii; options.idField = object.objectIdFieldName; for (i = 0, ii = esriJSONFeatures.length; i < ii; ++i) { features.push(this.readFeatureFromObject(esriJSONFeatures[i], - options)); + options)); } return features; } else { @@ -523,9 +523,9 @@ EsriJSON.prototype.readGeometry; * @inheritDoc */ EsriJSON.prototype.readGeometryFromObject = function( - object, opt_options) { + object, opt_options) { return EsriJSON.readGeometry_( - /** @type {EsriJSONGeometry} */(object), opt_options); + /** @type {EsriJSONGeometry} */(object), opt_options); }; @@ -544,9 +544,9 @@ EsriJSON.prototype.readProjection; * @inheritDoc */ EsriJSON.prototype.readProjectionFromObject = function(object) { - var esriJSONObject = /** @type {EsriJSONObject} */ (object); + const esriJSONObject = /** @type {EsriJSONObject} */ (object); if (esriJSONObject.spatialReference && esriJSONObject.spatialReference.wkid) { - var crs = esriJSONObject.spatialReference.wkid; + const crs = esriJSONObject.spatialReference.wkid; return getProjection('EPSG:' + crs); } else { return null; @@ -561,7 +561,7 @@ EsriJSON.prototype.readProjectionFromObject = function(object) { * @return {EsriJSONGeometry} EsriJSON geometry. */ EsriJSON.writeGeometry_ = function(geometry, opt_options) { - var geometryWriter = EsriJSON.GEOMETRY_WRITERS_[geometry.getType()]; + const geometryWriter = EsriJSON.GEOMETRY_WRITERS_[geometry.getType()]; return geometryWriter(/** @type {ol.geom.Geometry} */( transformWithOptions(geometry, true, opt_options)), opt_options); }; @@ -589,9 +589,9 @@ EsriJSON.prototype.writeGeometry; * @api */ EsriJSON.prototype.writeGeometryObject = function(geometry, - opt_options) { + opt_options) { return EsriJSON.writeGeometry_(geometry, - this.adaptOptions(opt_options)); + this.adaptOptions(opt_options)); }; @@ -617,10 +617,10 @@ EsriJSON.prototype.writeFeature; * @api */ EsriJSON.prototype.writeFeatureObject = function( - feature, opt_options) { + feature, opt_options) { opt_options = this.adaptOptions(opt_options); - var object = {}; - var geometry = feature.getGeometry(); + const object = {}; + const geometry = feature.getGeometry(); if (geometry) { object['geometry'] = EsriJSON.writeGeometry_(geometry, opt_options); @@ -630,7 +630,7 @@ EsriJSON.prototype.writeFeatureObject = function( }); } } - var properties = feature.getProperties(); + const properties = feature.getProperties(); delete properties[feature.getGeometryName()]; if (!_ol_obj_.isEmpty(properties)) { object['attributes'] = properties; @@ -664,8 +664,8 @@ EsriJSON.prototype.writeFeatures; */ EsriJSON.prototype.writeFeaturesObject = function(features, opt_options) { opt_options = this.adaptOptions(opt_options); - var objects = []; - var i, ii; + const objects = []; + let i, ii; for (i = 0, ii = features.length; i < ii; ++i) { objects.push(this.writeFeatureObject(features[i], opt_options)); } diff --git a/src/ol/format/Feature.js b/src/ol/format/Feature.js index e8b6125540..803d40740a 100644 --- a/src/ol/format/Feature.js +++ b/src/ol/format/Feature.js @@ -18,7 +18,7 @@ import {get as getProjection, equivalent as equivalentProjection, transformExten * @abstract * @api */ -var FeatureFormat = function() { +const FeatureFormat = function() { /** * @protected @@ -43,7 +43,7 @@ var FeatureFormat = function() { * @protected */ FeatureFormat.prototype.getReadOptions = function(source, opt_options) { - var options; + let options; if (opt_options) { options = { dataProjection: opt_options.dataProjection ? @@ -173,40 +173,40 @@ export default FeatureFormat; * @return {ol.geom.Geometry|ol.Extent} Transformed geometry. */ export function transformWithOptions(geometry, write, opt_options) { - var featureProjection = opt_options ? + const featureProjection = opt_options ? getProjection(opt_options.featureProjection) : null; - var dataProjection = opt_options ? + const dataProjection = opt_options ? getProjection(opt_options.dataProjection) : null; /** * @type {ol.geom.Geometry|ol.Extent} */ - var transformed; + let transformed; if (featureProjection && dataProjection && !equivalentProjection(featureProjection, dataProjection)) { if (geometry instanceof Geometry) { transformed = (write ? geometry.clone() : geometry).transform( - write ? featureProjection : dataProjection, - write ? dataProjection : featureProjection); + write ? featureProjection : dataProjection, + write ? dataProjection : featureProjection); } else { // FIXME this is necessary because ol.format.GML treats extents // as geometries transformed = transformExtent( - geometry, - dataProjection, - featureProjection); + geometry, + dataProjection, + featureProjection); } } else { transformed = geometry; } if (write && opt_options && opt_options.decimals !== undefined) { - var power = Math.pow(10, opt_options.decimals); + const power = Math.pow(10, opt_options.decimals); // if decimals option on write, round each coordinate appropriately /** * @param {Array.} coordinates Coordinates. * @return {Array.} Transformed coordinates. */ - var transform = function(coordinates) { - for (var i = 0, ii = coordinates.length; i < ii; ++i) { + const transform = function(coordinates) { + for (let i = 0, ii = coordinates.length; i < ii; ++i) { coordinates[i] = Math.round(coordinates[i] * power) / power; } return coordinates; diff --git a/src/ol/format/GML.js b/src/ol/format/GML.js index 740506185c..75915fe795 100644 --- a/src/ol/format/GML.js +++ b/src/ol/format/GML.js @@ -15,7 +15,7 @@ import GML3 from '../format/GML3.js'; * @extends {ol.format.GMLBase} * @api */ -var _ol_format_GML_ = GML3; +const _ol_format_GML_ = GML3; /** diff --git a/src/ol/format/GML2.js b/src/ol/format/GML2.js index cbbd867b7c..8a23ae76c5 100644 --- a/src/ol/format/GML2.js +++ b/src/ol/format/GML2.js @@ -21,14 +21,14 @@ import _ol_xml_ from '../xml.js'; * @extends {ol.format.GMLBase} * @api */ -var GML2 = function(opt_options) { - var options = /** @type {olx.format.GMLOptions} */ +const GML2 = function(opt_options) { + const options = /** @type {olx.format.GMLOptions} */ (opt_options ? opt_options : {}); GMLBase.call(this, options); this.FEATURE_COLLECTION_PARSERS[GMLBase.GMLNS][ - 'featureMember'] = + 'featureMember'] = _ol_xml_.makeArrayPusher(GMLBase.prototype.readFeaturesInternal); /** @@ -58,21 +58,21 @@ GML2.schemaLocation_ = GMLBase.GMLNS + * @return {Array.|undefined} Flat coordinates. */ GML2.prototype.readFlatCoordinates_ = function(node, objectStack) { - var s = _ol_xml_.getAllTextContent(node, false).replace(/^\s*|\s*$/g, ''); - var context = /** @type {ol.XmlNodeStackItem} */ (objectStack[0]); - var containerSrs = context['srsName']; - var axisOrientation = 'enu'; + const s = _ol_xml_.getAllTextContent(node, false).replace(/^\s*|\s*$/g, ''); + const context = /** @type {ol.XmlNodeStackItem} */ (objectStack[0]); + const containerSrs = context['srsName']; + let axisOrientation = 'enu'; if (containerSrs) { - var proj = getProjection(containerSrs); + const proj = getProjection(containerSrs); if (proj) { axisOrientation = proj.getAxisOrientation(); } } - var coordsGroups = s.trim().split(/\s+/); - var x, y, z; - var flatCoordinates = []; - for (var i = 0, ii = coordsGroups.length; i < ii; i++) { - var coords = coordsGroups[i].split(/,+/); + const coordsGroups = s.trim().split(/\s+/); + let x, y, z; + const flatCoordinates = []; + for (let i = 0, ii = coordsGroups.length; i < ii; i++) { + const coords = coordsGroups[i].split(/,+/); x = parseFloat(coords[0]); y = parseFloat(coords[1]); z = (coords.length === 3) ? parseFloat(coords[2]) : 0; @@ -94,11 +94,11 @@ GML2.prototype.readFlatCoordinates_ = function(node, objectStack) { */ GML2.prototype.readBox_ = function(node, objectStack) { /** @type {Array.} */ - var flatCoordinates = _ol_xml_.pushParseAndPop([null], - this.BOX_PARSERS_, node, objectStack, this); + const flatCoordinates = _ol_xml_.pushParseAndPop([null], + this.BOX_PARSERS_, node, objectStack, this); return createOrUpdate(flatCoordinates[1][0], - flatCoordinates[1][1], flatCoordinates[1][3], - flatCoordinates[1][4]); + flatCoordinates[1][1], flatCoordinates[1][3], + flatCoordinates[1][4]); }; @@ -109,10 +109,10 @@ GML2.prototype.readBox_ = function(node, objectStack) { */ GML2.prototype.innerBoundaryIsParser_ = function(node, objectStack) { /** @type {Array.|undefined} */ - var flatLinearRing = _ol_xml_.pushParseAndPop(undefined, - this.RING_PARSERS, node, objectStack, this); + const flatLinearRing = _ol_xml_.pushParseAndPop(undefined, + this.RING_PARSERS, node, objectStack, this); if (flatLinearRing) { - var flatLinearRings = /** @type {Array.>} */ + const flatLinearRings = /** @type {Array.>} */ (objectStack[objectStack.length - 1]); flatLinearRings.push(flatLinearRing); } @@ -126,10 +126,10 @@ GML2.prototype.innerBoundaryIsParser_ = function(node, objectStack) { */ GML2.prototype.outerBoundaryIsParser_ = function(node, objectStack) { /** @type {Array.|undefined} */ - var flatLinearRing = _ol_xml_.pushParseAndPop(undefined, - this.RING_PARSERS, node, objectStack, this); + const flatLinearRing = _ol_xml_.pushParseAndPop(undefined, + this.RING_PARSERS, node, objectStack, this); if (flatLinearRing) { - var flatLinearRings = /** @type {Array.>} */ + const flatLinearRings = /** @type {Array.>} */ (objectStack[objectStack.length - 1]); flatLinearRings[0] = flatLinearRing; } @@ -144,7 +144,7 @@ GML2.prototype.outerBoundaryIsParser_ = function(node, objectStack) { GML2.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS_ = { 'http://www.opengis.net/gml': { 'coordinates': _ol_xml_.makeReplacer( - GML2.prototype.readFlatCoordinates_) + GML2.prototype.readFlatCoordinates_) } }; @@ -170,7 +170,7 @@ GML2.prototype.FLAT_LINEAR_RINGS_PARSERS_ = { GML2.prototype.BOX_PARSERS_ = { 'http://www.opengis.net/gml': { 'coordinates': _ol_xml_.makeArrayPusher( - GML2.prototype.readFlatCoordinates_) + GML2.prototype.readFlatCoordinates_) } }; @@ -184,16 +184,16 @@ GML2.prototype.GEOMETRY_PARSERS_ = { 'http://www.opengis.net/gml': { 'Point': _ol_xml_.makeReplacer(GMLBase.prototype.readPoint), 'MultiPoint': _ol_xml_.makeReplacer( - GMLBase.prototype.readMultiPoint), + GMLBase.prototype.readMultiPoint), 'LineString': _ol_xml_.makeReplacer( - GMLBase.prototype.readLineString), + GMLBase.prototype.readLineString), 'MultiLineString': _ol_xml_.makeReplacer( - GMLBase.prototype.readMultiLineString), + GMLBase.prototype.readMultiLineString), 'LinearRing': _ol_xml_.makeReplacer( - GMLBase.prototype.readLinearRing), + GMLBase.prototype.readLinearRing), 'Polygon': _ol_xml_.makeReplacer(GMLBase.prototype.readPolygon), 'MultiPolygon': _ol_xml_.makeReplacer( - GMLBase.prototype.readMultiPolygon), + GMLBase.prototype.readMultiPolygon), 'Box': _ol_xml_.makeReplacer(GML2.prototype.readBox_) } }; @@ -208,11 +208,11 @@ GML2.prototype.GEOMETRY_PARSERS_ = { * @private */ GML2.prototype.GEOMETRY_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) { - var context = objectStack[objectStack.length - 1]; - var multiSurface = context['multiSurface']; - var surface = context['surface']; - var multiCurve = context['multiCurve']; - var nodeName; + const context = objectStack[objectStack.length - 1]; + const multiSurface = context['multiSurface']; + const surface = context['surface']; + const multiCurve = context['multiCurve']; + let nodeName; if (!Array.isArray(value)) { nodeName = /** @type {ol.geom.Geometry} */ (value).getType(); if (nodeName === 'MultiPolygon' && multiSurface === true) { @@ -226,7 +226,7 @@ GML2.prototype.GEOMETRY_NODE_FACTORY_ = function(value, objectStack, opt_nodeNam nodeName = 'Envelope'; } return _ol_xml_.createElementNS('http://www.opengis.net/gml', - nodeName); + nodeName); }; @@ -236,44 +236,45 @@ GML2.prototype.GEOMETRY_NODE_FACTORY_ = function(value, objectStack, opt_nodeNam * @param {Array.<*>} objectStack Node stack. */ GML2.prototype.writeFeatureElement = function(node, feature, objectStack) { - var fid = feature.getId(); + const fid = feature.getId(); if (fid) { node.setAttribute('fid', fid); } - var context = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var featureNS = context['featureNS']; - var geometryName = feature.getGeometryName(); + const context = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const featureNS = context['featureNS']; + const geometryName = feature.getGeometryName(); if (!context.serializers) { context.serializers = {}; context.serializers[featureNS] = {}; } - var properties = feature.getProperties(); - var keys = [], values = []; - for (var key in properties) { - var value = properties[key]; + const properties = feature.getProperties(); + const keys = []; + const values = []; + for (const key in properties) { + const value = properties[key]; if (value !== null) { keys.push(key); values.push(value); if (key == geometryName || value instanceof Geometry) { if (!(key in context.serializers[featureNS])) { context.serializers[featureNS][key] = _ol_xml_.makeChildAppender( - this.writeGeometryElement, this); + this.writeGeometryElement, this); } } else { if (!(key in context.serializers[featureNS])) { context.serializers[featureNS][key] = _ol_xml_.makeChildAppender( - XSD.writeStringTextNode); + XSD.writeStringTextNode); } } } } - var item = _ol_obj_.assign({}, context); + const item = _ol_obj_.assign({}, context); item.node = node; _ol_xml_.pushSerializeAndPop(/** @type {ol.XmlNodeStackItem} */ - (item), context.serializers, - _ol_xml_.makeSimpleNodeFactory(undefined, featureNS), - values, - objectStack, keys); + (item), context.serializers, + _ol_xml_.makeSimpleNodeFactory(undefined, featureNS), + values, + objectStack, keys); }; @@ -283,14 +284,14 @@ GML2.prototype.writeFeatureElement = function(node, feature, objectStack) { * @param {Array.<*>} objectStack Node stack. */ GML2.prototype.writeGeometryElement = function(node, geometry, objectStack) { - var context = /** @type {olx.format.WriteOptions} */ (objectStack[objectStack.length - 1]); - var item = _ol_obj_.assign({}, context); + const context = /** @type {olx.format.WriteOptions} */ (objectStack[objectStack.length - 1]); + const item = _ol_obj_.assign({}, context); item.node = node; - var value; + let value; if (Array.isArray(geometry)) { if (context.dataProjection) { value = transformExtent( - geometry, context.featureProjection, context.dataProjection); + geometry, context.featureProjection, context.dataProjection); } else { value = geometry; } @@ -298,9 +299,9 @@ GML2.prototype.writeGeometryElement = function(node, geometry, objectStack) { value = transformWithOptions(/** @type {ol.geom.Geometry} */ (geometry), true, context); } _ol_xml_.pushSerializeAndPop(/** @type {ol.XmlNodeStackItem} */ - (item), GML2.GEOMETRY_SERIALIZERS_, - this.GEOMETRY_NODE_FACTORY_, [value], - objectStack, undefined, this); + (item), GML2.GEOMETRY_SERIALIZERS_, + this.GEOMETRY_NODE_FACTORY_, [value], + objectStack, undefined, this); }; @@ -311,21 +312,21 @@ GML2.prototype.writeGeometryElement = function(node, geometry, objectStack) { * @private */ GML2.prototype.writeCurveOrLineString_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const srsName = context['srsName']; if (node.nodeName !== 'LineStringSegment' && srsName) { node.setAttribute('srsName', srsName); } if (node.nodeName === 'LineString' || node.nodeName === 'LineStringSegment') { - var coordinates = this.createCoordinatesNode_(node.namespaceURI); + const coordinates = this.createCoordinatesNode_(node.namespaceURI); node.appendChild(coordinates); this.writeCoordinates_(coordinates, geometry, objectStack); } else if (node.nodeName === 'Curve') { - var segments = _ol_xml_.createElementNS(node.namespaceURI, 'segments'); + const segments = _ol_xml_.createElementNS(node.namespaceURI, 'segments'); node.appendChild(segments); this.writeCurveSegments_(segments, - geometry, objectStack); + geometry, objectStack); } }; @@ -336,7 +337,7 @@ GML2.prototype.writeCurveOrLineString_ = function(node, geometry, objectStack) { * @private */ GML2.prototype.createCoordinatesNode_ = function(namespaceURI) { - var coordinates = _ol_xml_.createElementNS(namespaceURI, 'coordinates'); + const coordinates = _ol_xml_.createElementNS(namespaceURI, 'coordinates'); coordinates.setAttribute('decimal', '.'); coordinates.setAttribute('cs', ','); coordinates.setAttribute('ts', ' '); @@ -352,15 +353,15 @@ GML2.prototype.createCoordinatesNode_ = function(namespaceURI) { * @private */ GML2.prototype.writeCoordinates_ = function(node, value, objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsName = context['srsName']; // only 2d for simple features profile - var points = value.getCoordinates(); - var len = points.length; - var parts = new Array(len); - var point; - for (var i = 0; i < len; ++i) { + const points = value.getCoordinates(); + const len = points.length; + const parts = new Array(len); + let point; + for (let i = 0; i < len; ++i) { point = points[i]; parts[i] = this.getCoords_(point, srsName, hasZ); } @@ -375,8 +376,8 @@ GML2.prototype.writeCoordinates_ = function(node, value, objectStack) { * @private */ GML2.prototype.writeCurveSegments_ = function(node, line, objectStack) { - var child = _ol_xml_.createElementNS(node.namespaceURI, - 'LineStringSegment'); + const child = _ol_xml_.createElementNS(node.namespaceURI, + 'LineStringSegment'); node.appendChild(child); this.writeCurveOrLineString_(child, line, objectStack); }; @@ -389,24 +390,24 @@ GML2.prototype.writeCurveSegments_ = function(node, line, objectStack) { * @private */ GML2.prototype.writeSurfaceOrPolygon_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsName = context['srsName']; if (node.nodeName !== 'PolygonPatch' && srsName) { node.setAttribute('srsName', srsName); } if (node.nodeName === 'Polygon' || node.nodeName === 'PolygonPatch') { - var rings = geometry.getLinearRings(); + const rings = geometry.getLinearRings(); _ol_xml_.pushSerializeAndPop( - {node: node, hasZ: hasZ, srsName: srsName}, - GML2.RING_SERIALIZERS_, - this.RING_NODE_FACTORY_, - rings, objectStack, undefined, this); + {node: node, hasZ: hasZ, srsName: srsName}, + GML2.RING_SERIALIZERS_, + this.RING_NODE_FACTORY_, + rings, objectStack, undefined, this); } else if (node.nodeName === 'Surface') { - var patches = _ol_xml_.createElementNS(node.namespaceURI, 'patches'); + const patches = _ol_xml_.createElementNS(node.namespaceURI, 'patches'); node.appendChild(patches); this.writeSurfacePatches_( - patches, geometry, objectStack); + patches, geometry, objectStack); } }; @@ -419,14 +420,14 @@ GML2.prototype.writeSurfaceOrPolygon_ = function(node, geometry, objectStack) { * @private */ GML2.prototype.RING_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) { - var context = objectStack[objectStack.length - 1]; - var parentNode = context.node; - var exteriorWritten = context['exteriorWritten']; + const context = objectStack[objectStack.length - 1]; + const parentNode = context.node; + const exteriorWritten = context['exteriorWritten']; if (exteriorWritten === undefined) { context['exteriorWritten'] = true; } return _ol_xml_.createElementNS(parentNode.namespaceURI, - exteriorWritten !== undefined ? 'innerBoundaryIs' : 'outerBoundaryIs'); + exteriorWritten !== undefined ? 'innerBoundaryIs' : 'outerBoundaryIs'); }; @@ -437,7 +438,7 @@ GML2.prototype.RING_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) { * @private */ GML2.prototype.writeSurfacePatches_ = function(node, polygon, objectStack) { - var child = _ol_xml_.createElementNS(node.namespaceURI, 'PolygonPatch'); + const child = _ol_xml_.createElementNS(node.namespaceURI, 'PolygonPatch'); node.appendChild(child); this.writeSurfaceOrPolygon_(child, polygon, objectStack); }; @@ -450,7 +451,7 @@ GML2.prototype.writeSurfacePatches_ = function(node, polygon, objectStack) { * @private */ GML2.prototype.writeRing_ = function(node, ring, objectStack) { - var linearRing = _ol_xml_.createElementNS(node.namespaceURI, 'LinearRing'); + const linearRing = _ol_xml_.createElementNS(node.namespaceURI, 'LinearRing'); node.appendChild(linearRing); this.writeLinearRing_(linearRing, ring, objectStack); }; @@ -464,16 +465,16 @@ GML2.prototype.writeRing_ = function(node, ring, objectStack) { * @private */ GML2.prototype.getCoords_ = function(point, opt_srsName, opt_hasZ) { - var axisOrientation = 'enu'; + let axisOrientation = 'enu'; if (opt_srsName) { axisOrientation = getProjection(opt_srsName).getAxisOrientation(); } - var coords = ((axisOrientation.substr(0, 2) === 'en') ? + let coords = ((axisOrientation.substr(0, 2) === 'en') ? point[0] + ',' + point[1] : point[1] + ',' + point[0]); if (opt_hasZ) { // For newly created points, Z can be undefined. - var z = point[2] || 0; + const z = point[2] || 0; coords += ',' + z; } @@ -488,18 +489,18 @@ GML2.prototype.getCoords_ = function(point, opt_srsName, opt_hasZ) { * @private */ GML2.prototype.writeMultiCurveOrLineString_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsName = context['srsName']; - var curve = context['curve']; + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsName = context['srsName']; + const curve = context['curve']; if (srsName) { node.setAttribute('srsName', srsName); } - var lines = geometry.getLineStrings(); + const lines = geometry.getLineStrings(); _ol_xml_.pushSerializeAndPop({node: node, hasZ: hasZ, srsName: srsName, curve: curve}, - GML2.LINESTRINGORCURVEMEMBER_SERIALIZERS_, - this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_, lines, - objectStack, undefined, this); + GML2.LINESTRINGORCURVEMEMBER_SERIALIZERS_, + this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_, lines, + objectStack, undefined, this); }; @@ -510,16 +511,16 @@ GML2.prototype.writeMultiCurveOrLineString_ = function(node, geometry, objectSta * @private */ GML2.prototype.writePoint_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsName = context['srsName']; if (srsName) { node.setAttribute('srsName', srsName); } - var coordinates = this.createCoordinatesNode_(node.namespaceURI); + const coordinates = this.createCoordinatesNode_(node.namespaceURI); node.appendChild(coordinates); - var point = geometry.getCoordinates(); - var coord = this.getCoords_(point, srsName, hasZ); + const point = geometry.getCoordinates(); + const coord = this.getCoords_(point, srsName, hasZ); XSD.writeStringTextNode(coordinates, coord); }; @@ -531,18 +532,18 @@ GML2.prototype.writePoint_ = function(node, geometry, objectStack) { * @private */ GML2.prototype.writeMultiPoint_ = function(node, geometry, - objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsName = context['srsName']; + objectStack) { + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsName = context['srsName']; if (srsName) { node.setAttribute('srsName', srsName); } - var points = geometry.getPoints(); + const points = geometry.getPoints(); _ol_xml_.pushSerializeAndPop({node: node, hasZ: hasZ, srsName: srsName}, - GML2.POINTMEMBER_SERIALIZERS_, - _ol_xml_.makeSimpleNodeFactory('pointMember'), points, - objectStack, undefined, this); + GML2.POINTMEMBER_SERIALIZERS_, + _ol_xml_.makeSimpleNodeFactory('pointMember'), points, + objectStack, undefined, this); }; @@ -553,7 +554,7 @@ GML2.prototype.writeMultiPoint_ = function(node, geometry, * @private */ GML2.prototype.writePointMember_ = function(node, point, objectStack) { - var child = _ol_xml_.createElementNS(node.namespaceURI, 'Point'); + const child = _ol_xml_.createElementNS(node.namespaceURI, 'Point'); node.appendChild(child); this.writePoint_(child, point, objectStack); }; @@ -566,7 +567,7 @@ GML2.prototype.writePointMember_ = function(node, point, objectStack) { * @private */ GML2.prototype.writeLineStringOrCurveMember_ = function(node, line, objectStack) { - var child = this.GEOMETRY_NODE_FACTORY_(line, objectStack); + const child = this.GEOMETRY_NODE_FACTORY_(line, objectStack); if (child) { node.appendChild(child); this.writeCurveOrLineString_(child, line, objectStack); @@ -581,12 +582,12 @@ GML2.prototype.writeLineStringOrCurveMember_ = function(node, line, objectStack) * @private */ GML2.prototype.writeLinearRing_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const srsName = context['srsName']; if (srsName) { node.setAttribute('srsName', srsName); } - var coordinates = this.createCoordinatesNode_(node.namespaceURI); + const coordinates = this.createCoordinatesNode_(node.namespaceURI); node.appendChild(coordinates); this.writeCoordinates_(coordinates, geometry, objectStack); }; @@ -599,18 +600,18 @@ GML2.prototype.writeLinearRing_ = function(node, geometry, objectStack) { * @private */ GML2.prototype.writeMultiSurfaceOrPolygon_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsName = context['srsName']; - var surface = context['surface']; + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsName = context['srsName']; + const surface = context['surface']; if (srsName) { node.setAttribute('srsName', srsName); } - var polygons = geometry.getPolygons(); + const polygons = geometry.getPolygons(); _ol_xml_.pushSerializeAndPop({node: node, hasZ: hasZ, srsName: srsName, surface: surface}, - GML2.SURFACEORPOLYGONMEMBER_SERIALIZERS_, - this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_, polygons, - objectStack, undefined, this); + GML2.SURFACEORPOLYGONMEMBER_SERIALIZERS_, + this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_, polygons, + objectStack, undefined, this); }; @@ -621,8 +622,8 @@ GML2.prototype.writeMultiSurfaceOrPolygon_ = function(node, geometry, objectStac * @private */ GML2.prototype.writeSurfaceOrPolygonMember_ = function(node, polygon, objectStack) { - var child = this.GEOMETRY_NODE_FACTORY_( - polygon, objectStack); + const child = this.GEOMETRY_NODE_FACTORY_( + polygon, objectStack); if (child) { node.appendChild(child); this.writeSurfaceOrPolygon_(child, polygon, objectStack); @@ -637,18 +638,18 @@ GML2.prototype.writeSurfaceOrPolygonMember_ = function(node, polygon, objectStac * @private */ GML2.prototype.writeEnvelope = function(node, extent, objectStack) { - var context = objectStack[objectStack.length - 1]; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const srsName = context['srsName']; if (srsName) { node.setAttribute('srsName', srsName); } - var keys = ['lowerCorner', 'upperCorner']; - var values = [extent[0] + ' ' + extent[1], extent[2] + ' ' + extent[3]]; + const keys = ['lowerCorner', 'upperCorner']; + const values = [extent[0] + ' ' + extent[1], extent[2] + ' ' + extent[3]]; _ol_xml_.pushSerializeAndPop(/** @type {ol.XmlNodeStackItem} */ - ({node: node}), GML2.ENVELOPE_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, - values, - objectStack, keys, this); + ({node: node}), GML2.ENVELOPE_SERIALIZERS_, + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, + values, + objectStack, keys, this); }; @@ -660,28 +661,28 @@ GML2.prototype.writeEnvelope = function(node, extent, objectStack) { GML2.GEOMETRY_SERIALIZERS_ = { 'http://www.opengis.net/gml': { 'Curve': _ol_xml_.makeChildAppender( - GML2.prototype.writeCurveOrLineString_), + GML2.prototype.writeCurveOrLineString_), 'MultiCurve': _ol_xml_.makeChildAppender( - GML2.prototype.writeMultiCurveOrLineString_), + GML2.prototype.writeMultiCurveOrLineString_), 'Point': _ol_xml_.makeChildAppender(GML2.prototype.writePoint_), 'MultiPoint': _ol_xml_.makeChildAppender( - GML2.prototype.writeMultiPoint_), + GML2.prototype.writeMultiPoint_), 'LineString': _ol_xml_.makeChildAppender( - GML2.prototype.writeCurveOrLineString_), + GML2.prototype.writeCurveOrLineString_), 'MultiLineString': _ol_xml_.makeChildAppender( - GML2.prototype.writeMultiCurveOrLineString_), + GML2.prototype.writeMultiCurveOrLineString_), 'LinearRing': _ol_xml_.makeChildAppender( - GML2.prototype.writeLinearRing_), + GML2.prototype.writeLinearRing_), 'Polygon': _ol_xml_.makeChildAppender( - GML2.prototype.writeSurfaceOrPolygon_), + GML2.prototype.writeSurfaceOrPolygon_), 'MultiPolygon': _ol_xml_.makeChildAppender( - GML2.prototype.writeMultiSurfaceOrPolygon_), + GML2.prototype.writeMultiSurfaceOrPolygon_), 'Surface': _ol_xml_.makeChildAppender( - GML2.prototype.writeSurfaceOrPolygon_), + GML2.prototype.writeSurfaceOrPolygon_), 'MultiSurface': _ol_xml_.makeChildAppender( - GML2.prototype.writeMultiSurfaceOrPolygon_), + GML2.prototype.writeMultiSurfaceOrPolygon_), 'Envelope': _ol_xml_.makeChildAppender( - GML2.prototype.writeEnvelope) + GML2.prototype.writeEnvelope) } }; @@ -705,7 +706,7 @@ GML2.RING_SERIALIZERS_ = { GML2.POINTMEMBER_SERIALIZERS_ = { 'http://www.opengis.net/gml': { 'pointMember': _ol_xml_.makeChildAppender( - GML2.prototype.writePointMember_) + GML2.prototype.writePointMember_) } }; @@ -717,9 +718,9 @@ GML2.POINTMEMBER_SERIALIZERS_ = { GML2.LINESTRINGORCURVEMEMBER_SERIALIZERS_ = { 'http://www.opengis.net/gml': { 'lineStringMember': _ol_xml_.makeChildAppender( - GML2.prototype.writeLineStringOrCurveMember_), + GML2.prototype.writeLineStringOrCurveMember_), 'curveMember': _ol_xml_.makeChildAppender( - GML2.prototype.writeLineStringOrCurveMember_) + GML2.prototype.writeLineStringOrCurveMember_) } }; @@ -733,9 +734,9 @@ GML2.LINESTRINGORCURVEMEMBER_SERIALIZERS_ = { * @private */ GML2.prototype.MULTIGEOMETRY_MEMBER_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) { - var parentNode = objectStack[objectStack.length - 1].node; + const parentNode = objectStack[objectStack.length - 1].node; return _ol_xml_.createElementNS('http://www.opengis.net/gml', - GML2.MULTIGEOMETRY_TO_MEMBER_NODENAME_[parentNode.nodeName]); + GML2.MULTIGEOMETRY_TO_MEMBER_NODENAME_[parentNode.nodeName]); }; /** @@ -759,9 +760,9 @@ GML2.MULTIGEOMETRY_TO_MEMBER_NODENAME_ = { GML2.SURFACEORPOLYGONMEMBER_SERIALIZERS_ = { 'http://www.opengis.net/gml': { 'surfaceMember': _ol_xml_.makeChildAppender( - GML2.prototype.writeSurfaceOrPolygonMember_), + GML2.prototype.writeSurfaceOrPolygonMember_), 'polygonMember': _ol_xml_.makeChildAppender( - GML2.prototype.writeSurfaceOrPolygonMember_) + GML2.prototype.writeSurfaceOrPolygonMember_) } }; diff --git a/src/ol/format/GML3.js b/src/ol/format/GML3.js index 9cf97206fc..1f2f88895f 100644 --- a/src/ol/format/GML3.js +++ b/src/ol/format/GML3.js @@ -29,8 +29,8 @@ import _ol_xml_ from '../xml.js'; * @extends {ol.format.GMLBase} * @api */ -var GML3 = function(opt_options) { - var options = /** @type {olx.format.GMLOptions} */ +const GML3 = function(opt_options) { + const options = /** @type {olx.format.GMLOptions} */ (opt_options ? opt_options : {}); GMLBase.call(this, options); @@ -97,10 +97,10 @@ GML3.schemaLocation_ = GMLBase.GMLNS + */ GML3.prototype.readMultiCurve_ = function(node, objectStack) { /** @type {Array.} */ - var lineStrings = _ol_xml_.pushParseAndPop([], - this.MULTICURVE_PARSERS_, node, objectStack, this); + const lineStrings = _ol_xml_.pushParseAndPop([], + this.MULTICURVE_PARSERS_, node, objectStack, this); if (lineStrings) { - var multiLineString = new MultiLineString(null); + const multiLineString = new MultiLineString(null); multiLineString.setLineStrings(lineStrings); return multiLineString; } else { @@ -117,10 +117,10 @@ GML3.prototype.readMultiCurve_ = function(node, objectStack) { */ GML3.prototype.readMultiSurface_ = function(node, objectStack) { /** @type {Array.} */ - var polygons = _ol_xml_.pushParseAndPop([], - this.MULTISURFACE_PARSERS_, node, objectStack, this); + const polygons = _ol_xml_.pushParseAndPop([], + this.MULTISURFACE_PARSERS_, node, objectStack, this); if (polygons) { - var multiPolygon = new MultiPolygon(null); + const multiPolygon = new MultiPolygon(null); multiPolygon.setPolygons(polygons); return multiPolygon; } else { @@ -146,7 +146,7 @@ GML3.prototype.curveMemberParser_ = function(node, objectStack) { */ GML3.prototype.surfaceMemberParser_ = function(node, objectStack) { _ol_xml_.parseNode(this.SURFACEMEMBER_PARSERS_, - node, objectStack, this); + node, objectStack, this); }; @@ -158,7 +158,7 @@ GML3.prototype.surfaceMemberParser_ = function(node, objectStack) { */ GML3.prototype.readPatch_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop([null], - this.PATCHES_PARSERS_, node, objectStack, this); + this.PATCHES_PARSERS_, node, objectStack, this); }; @@ -170,7 +170,7 @@ GML3.prototype.readPatch_ = function(node, objectStack) { */ GML3.prototype.readSegment_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop([null], - this.SEGMENTS_PARSERS_, node, objectStack, this); + this.SEGMENTS_PARSERS_, node, objectStack, this); }; @@ -182,7 +182,7 @@ GML3.prototype.readSegment_ = function(node, objectStack) { */ GML3.prototype.readPolygonPatch_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop([null], - this.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack, this); + this.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack, this); }; @@ -194,8 +194,8 @@ GML3.prototype.readPolygonPatch_ = function(node, objectStack) { */ GML3.prototype.readLineStringSegment_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop([null], - this.GEOMETRY_FLAT_COORDINATES_PARSERS_, - node, objectStack, this); + this.GEOMETRY_FLAT_COORDINATES_PARSERS_, + node, objectStack, this); }; @@ -206,10 +206,10 @@ GML3.prototype.readLineStringSegment_ = function(node, objectStack) { */ GML3.prototype.interiorParser_ = function(node, objectStack) { /** @type {Array.|undefined} */ - var flatLinearRing = _ol_xml_.pushParseAndPop(undefined, - this.RING_PARSERS, node, objectStack, this); + const flatLinearRing = _ol_xml_.pushParseAndPop(undefined, + this.RING_PARSERS, node, objectStack, this); if (flatLinearRing) { - var flatLinearRings = /** @type {Array.>} */ + const flatLinearRings = /** @type {Array.>} */ (objectStack[objectStack.length - 1]); flatLinearRings.push(flatLinearRing); } @@ -223,10 +223,10 @@ GML3.prototype.interiorParser_ = function(node, objectStack) { */ GML3.prototype.exteriorParser_ = function(node, objectStack) { /** @type {Array.|undefined} */ - var flatLinearRing = _ol_xml_.pushParseAndPop(undefined, - this.RING_PARSERS, node, objectStack, this); + const flatLinearRing = _ol_xml_.pushParseAndPop(undefined, + this.RING_PARSERS, node, objectStack, this); if (flatLinearRing) { - var flatLinearRings = /** @type {Array.>} */ + const flatLinearRings = /** @type {Array.>} */ (objectStack[objectStack.length - 1]); flatLinearRings[0] = flatLinearRing; } @@ -241,19 +241,19 @@ GML3.prototype.exteriorParser_ = function(node, objectStack) { */ GML3.prototype.readSurface_ = function(node, objectStack) { /** @type {Array.>} */ - var flatLinearRings = _ol_xml_.pushParseAndPop([null], - this.SURFACE_PARSERS_, node, objectStack, this); + const flatLinearRings = _ol_xml_.pushParseAndPop([null], + this.SURFACE_PARSERS_, node, objectStack, this); if (flatLinearRings && flatLinearRings[0]) { - var polygon = new Polygon(null); - var flatCoordinates = flatLinearRings[0]; - var ends = [flatCoordinates.length]; - var i, ii; + const polygon = new Polygon(null); + const flatCoordinates = flatLinearRings[0]; + const ends = [flatCoordinates.length]; + let i, ii; for (i = 1, ii = flatLinearRings.length; i < ii; ++i) { extend(flatCoordinates, flatLinearRings[i]); ends.push(flatCoordinates.length); } polygon.setFlatCoordinates( - GeometryLayout.XYZ, flatCoordinates, ends); + GeometryLayout.XYZ, flatCoordinates, ends); return polygon; } else { return undefined; @@ -269,10 +269,10 @@ GML3.prototype.readSurface_ = function(node, objectStack) { */ GML3.prototype.readCurve_ = function(node, objectStack) { /** @type {Array.} */ - var flatCoordinates = _ol_xml_.pushParseAndPop([null], - this.CURVE_PARSERS_, node, objectStack, this); + const flatCoordinates = _ol_xml_.pushParseAndPop([null], + this.CURVE_PARSERS_, node, objectStack, this); if (flatCoordinates) { - var lineString = new LineString(null); + const lineString = new LineString(null); lineString.setFlatCoordinates(GeometryLayout.XYZ, flatCoordinates); return lineString; } else { @@ -289,11 +289,11 @@ GML3.prototype.readCurve_ = function(node, objectStack) { */ GML3.prototype.readEnvelope_ = function(node, objectStack) { /** @type {Array.} */ - var flatCoordinates = _ol_xml_.pushParseAndPop([null], - this.ENVELOPE_PARSERS_, node, objectStack, this); + const flatCoordinates = _ol_xml_.pushParseAndPop([null], + this.ENVELOPE_PARSERS_, node, objectStack, this); return createOrUpdate(flatCoordinates[1][0], - flatCoordinates[1][1], flatCoordinates[2][0], - flatCoordinates[2][1]); + flatCoordinates[1][1], flatCoordinates[2][0], + flatCoordinates[2][1]); }; @@ -304,11 +304,11 @@ GML3.prototype.readEnvelope_ = function(node, objectStack) { * @return {Array.|undefined} Flat coordinates. */ GML3.prototype.readFlatPos_ = function(node, objectStack) { - var s = _ol_xml_.getAllTextContent(node, false); - var re = /^\s*([+\-]?\d*\.?\d+(?:[eE][+\-]?\d+)?)\s*/; + let s = _ol_xml_.getAllTextContent(node, false); + const re = /^\s*([+\-]?\d*\.?\d+(?:[eE][+\-]?\d+)?)\s*/; /** @type {Array.} */ - var flatCoordinates = []; - var m; + const flatCoordinates = []; + let m; while ((m = re.exec(s))) { flatCoordinates.push(parseFloat(m[1])); s = s.substr(m[0].length); @@ -316,23 +316,23 @@ GML3.prototype.readFlatPos_ = function(node, objectStack) { if (s !== '') { return undefined; } - var context = objectStack[0]; - var containerSrs = context['srsName']; - var axisOrientation = 'enu'; + const context = objectStack[0]; + const containerSrs = context['srsName']; + let axisOrientation = 'enu'; if (containerSrs) { - var proj = getProjection(containerSrs); + const proj = getProjection(containerSrs); axisOrientation = proj.getAxisOrientation(); } if (axisOrientation === 'neu') { - var i, ii; + let i, ii; for (i = 0, ii = flatCoordinates.length; i < ii; i += 3) { - var y = flatCoordinates[i]; - var x = flatCoordinates[i + 1]; + const y = flatCoordinates[i]; + const x = flatCoordinates[i + 1]; flatCoordinates[i] = x; flatCoordinates[i + 1] = y; } } - var len = flatCoordinates.length; + const len = flatCoordinates.length; if (len == 2) { flatCoordinates.push(0); } @@ -350,33 +350,33 @@ GML3.prototype.readFlatPos_ = function(node, objectStack) { * @return {Array.|undefined} Flat coordinates. */ GML3.prototype.readFlatPosList_ = function(node, objectStack) { - var s = _ol_xml_.getAllTextContent(node, false).replace(/^\s*|\s*$/g, ''); - var context = objectStack[0]; - var containerSrs = context['srsName']; - var contextDimension = context['srsDimension']; - var axisOrientation = 'enu'; + const s = _ol_xml_.getAllTextContent(node, false).replace(/^\s*|\s*$/g, ''); + const context = objectStack[0]; + const containerSrs = context['srsName']; + const contextDimension = context['srsDimension']; + let axisOrientation = 'enu'; if (containerSrs) { - var proj = getProjection(containerSrs); + const proj = getProjection(containerSrs); axisOrientation = proj.getAxisOrientation(); } - var coords = s.split(/\s+/); + const coords = s.split(/\s+/); // The "dimension" attribute is from the GML 3.0.1 spec. - var dim = 2; + let dim = 2; if (node.getAttribute('srsDimension')) { dim = XSD.readNonNegativeIntegerString( - node.getAttribute('srsDimension')); + node.getAttribute('srsDimension')); } else if (node.getAttribute('dimension')) { dim = XSD.readNonNegativeIntegerString( - node.getAttribute('dimension')); + node.getAttribute('dimension')); } else if (node.parentNode.getAttribute('srsDimension')) { dim = XSD.readNonNegativeIntegerString( - node.parentNode.getAttribute('srsDimension')); + node.parentNode.getAttribute('srsDimension')); } else if (contextDimension) { dim = XSD.readNonNegativeIntegerString(contextDimension); } - var x, y, z; - var flatCoordinates = []; - for (var i = 0, ii = coords.length; i < ii; i += dim) { + let x, y, z; + const flatCoordinates = []; + for (let i = 0, ii = coords.length; i < ii; i += dim) { x = parseFloat(coords[i]); y = parseFloat(coords[i + 1]); z = (dim === 3) ? parseFloat(coords[i + 2]) : 0; @@ -425,22 +425,22 @@ GML3.prototype.GEOMETRY_PARSERS_ = { 'http://www.opengis.net/gml': { 'Point': _ol_xml_.makeReplacer(GMLBase.prototype.readPoint), 'MultiPoint': _ol_xml_.makeReplacer( - GMLBase.prototype.readMultiPoint), + GMLBase.prototype.readMultiPoint), 'LineString': _ol_xml_.makeReplacer( - GMLBase.prototype.readLineString), + GMLBase.prototype.readLineString), 'MultiLineString': _ol_xml_.makeReplacer( - GMLBase.prototype.readMultiLineString), + GMLBase.prototype.readMultiLineString), 'LinearRing': _ol_xml_.makeReplacer( - GMLBase.prototype.readLinearRing), + GMLBase.prototype.readLinearRing), 'Polygon': _ol_xml_.makeReplacer(GMLBase.prototype.readPolygon), 'MultiPolygon': _ol_xml_.makeReplacer( - GMLBase.prototype.readMultiPolygon), + GMLBase.prototype.readMultiPolygon), 'Surface': _ol_xml_.makeReplacer(GML3.prototype.readSurface_), 'MultiSurface': _ol_xml_.makeReplacer( - GML3.prototype.readMultiSurface_), + GML3.prototype.readMultiSurface_), 'Curve': _ol_xml_.makeReplacer(GML3.prototype.readCurve_), 'MultiCurve': _ol_xml_.makeReplacer( - GML3.prototype.readMultiCurve_), + GML3.prototype.readMultiCurve_), 'Envelope': _ol_xml_.makeReplacer(GML3.prototype.readEnvelope_) } }; @@ -454,9 +454,9 @@ GML3.prototype.GEOMETRY_PARSERS_ = { GML3.prototype.MULTICURVE_PARSERS_ = { 'http://www.opengis.net/gml': { 'curveMember': _ol_xml_.makeArrayPusher( - GML3.prototype.curveMemberParser_), + GML3.prototype.curveMemberParser_), 'curveMembers': _ol_xml_.makeArrayPusher( - GML3.prototype.curveMemberParser_) + GML3.prototype.curveMemberParser_) } }; @@ -469,9 +469,9 @@ GML3.prototype.MULTICURVE_PARSERS_ = { GML3.prototype.MULTISURFACE_PARSERS_ = { 'http://www.opengis.net/gml': { 'surfaceMember': _ol_xml_.makeArrayPusher( - GML3.prototype.surfaceMemberParser_), + GML3.prototype.surfaceMemberParser_), 'surfaceMembers': _ol_xml_.makeArrayPusher( - GML3.prototype.surfaceMemberParser_) + GML3.prototype.surfaceMemberParser_) } }; @@ -484,7 +484,7 @@ GML3.prototype.MULTISURFACE_PARSERS_ = { GML3.prototype.CURVEMEMBER_PARSERS_ = { 'http://www.opengis.net/gml': { 'LineString': _ol_xml_.makeArrayPusher( - GMLBase.prototype.readLineString), + GMLBase.prototype.readLineString), 'Curve': _ol_xml_.makeArrayPusher(GML3.prototype.readCurve_) } }; @@ -535,9 +535,9 @@ GML3.prototype.CURVE_PARSERS_ = { GML3.prototype.ENVELOPE_PARSERS_ = { 'http://www.opengis.net/gml': { 'lowerCorner': _ol_xml_.makeArrayPusher( - GML3.prototype.readFlatPosList_), + GML3.prototype.readFlatPosList_), 'upperCorner': _ol_xml_.makeArrayPusher( - GML3.prototype.readFlatPosList_) + GML3.prototype.readFlatPosList_) } }; @@ -550,7 +550,7 @@ GML3.prototype.ENVELOPE_PARSERS_ = { GML3.prototype.PATCHES_PARSERS_ = { 'http://www.opengis.net/gml': { 'PolygonPatch': _ol_xml_.makeReplacer( - GML3.prototype.readPolygonPatch_) + GML3.prototype.readPolygonPatch_) } }; @@ -563,7 +563,7 @@ GML3.prototype.PATCHES_PARSERS_ = { GML3.prototype.SEGMENTS_PARSERS_ = { 'http://www.opengis.net/gml': { 'LineStringSegment': _ol_xml_.makeReplacer( - GML3.prototype.readLineStringSegment_) + GML3.prototype.readLineStringSegment_) } }; @@ -575,17 +575,17 @@ GML3.prototype.SEGMENTS_PARSERS_ = { * @private */ GML3.prototype.writePos_ = function(node, value, objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsDimension = hasZ ? 3 : 2; + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsDimension = hasZ ? 3 : 2; node.setAttribute('srsDimension', srsDimension); - var srsName = context['srsName']; - var axisOrientation = 'enu'; + const srsName = context['srsName']; + let axisOrientation = 'enu'; if (srsName) { axisOrientation = getProjection(srsName).getAxisOrientation(); } - var point = value.getCoordinates(); - var coords; + const point = value.getCoordinates(); + let coords; // only 2d for simple features profile if (axisOrientation.substr(0, 2) === 'en') { coords = (point[0] + ' ' + point[1]); @@ -594,7 +594,7 @@ GML3.prototype.writePos_ = function(node, value, objectStack) { } if (hasZ) { // For newly created points, Z can be undefined. - var z = point[2] || 0; + const z = point[2] || 0; coords += ' ' + z; } XSD.writeStringTextNode(node, coords); @@ -609,16 +609,16 @@ GML3.prototype.writePos_ = function(node, value, objectStack) { * @private */ GML3.prototype.getCoords_ = function(point, opt_srsName, opt_hasZ) { - var axisOrientation = 'enu'; + let axisOrientation = 'enu'; if (opt_srsName) { axisOrientation = getProjection(opt_srsName).getAxisOrientation(); } - var coords = ((axisOrientation.substr(0, 2) === 'en') ? + let coords = ((axisOrientation.substr(0, 2) === 'en') ? point[0] + ' ' + point[1] : point[1] + ' ' + point[0]); if (opt_hasZ) { // For newly created points, Z can be undefined. - var z = point[2] || 0; + const z = point[2] || 0; coords += ' ' + z; } @@ -633,17 +633,17 @@ GML3.prototype.getCoords_ = function(point, opt_srsName, opt_hasZ) { * @private */ GML3.prototype.writePosList_ = function(node, value, objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsDimension = hasZ ? 3 : 2; + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsDimension = hasZ ? 3 : 2; node.setAttribute('srsDimension', srsDimension); - var srsName = context['srsName']; + const srsName = context['srsName']; // only 2d for simple features profile - var points = value.getCoordinates(); - var len = points.length; - var parts = new Array(len); - var point; - for (var i = 0; i < len; ++i) { + const points = value.getCoordinates(); + const len = points.length; + const parts = new Array(len); + let point; + for (let i = 0; i < len; ++i) { point = points[i]; parts[i] = this.getCoords_(point, srsName, hasZ); } @@ -658,12 +658,12 @@ GML3.prototype.writePosList_ = function(node, value, objectStack) { * @private */ GML3.prototype.writePoint_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const srsName = context['srsName']; if (srsName) { node.setAttribute('srsName', srsName); } - var pos = _ol_xml_.createElementNS(node.namespaceURI, 'pos'); + const pos = _ol_xml_.createElementNS(node.namespaceURI, 'pos'); node.appendChild(pos); this.writePos_(pos, geometry, objectStack); }; @@ -687,18 +687,18 @@ GML3.ENVELOPE_SERIALIZERS_ = { * @param {Array.<*>} objectStack Node stack. */ GML3.prototype.writeEnvelope = function(node, extent, objectStack) { - var context = objectStack[objectStack.length - 1]; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const srsName = context['srsName']; if (srsName) { node.setAttribute('srsName', srsName); } - var keys = ['lowerCorner', 'upperCorner']; - var values = [extent[0] + ' ' + extent[1], extent[2] + ' ' + extent[3]]; + const keys = ['lowerCorner', 'upperCorner']; + const values = [extent[0] + ' ' + extent[1], extent[2] + ' ' + extent[3]]; _ol_xml_.pushSerializeAndPop(/** @type {ol.XmlNodeStackItem} */ - ({node: node}), GML3.ENVELOPE_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, - values, - objectStack, keys, this); + ({node: node}), GML3.ENVELOPE_SERIALIZERS_, + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, + values, + objectStack, keys, this); }; @@ -709,12 +709,12 @@ GML3.prototype.writeEnvelope = function(node, extent, objectStack) { * @private */ GML3.prototype.writeLinearRing_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const srsName = context['srsName']; if (srsName) { node.setAttribute('srsName', srsName); } - var posList = _ol_xml_.createElementNS(node.namespaceURI, 'posList'); + const posList = _ol_xml_.createElementNS(node.namespaceURI, 'posList'); node.appendChild(posList); this.writePosList_(posList, geometry, objectStack); }; @@ -728,14 +728,14 @@ GML3.prototype.writeLinearRing_ = function(node, geometry, objectStack) { * @private */ GML3.prototype.RING_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) { - var context = objectStack[objectStack.length - 1]; - var parentNode = context.node; - var exteriorWritten = context['exteriorWritten']; + const context = objectStack[objectStack.length - 1]; + const parentNode = context.node; + const exteriorWritten = context['exteriorWritten']; if (exteriorWritten === undefined) { context['exteriorWritten'] = true; } return _ol_xml_.createElementNS(parentNode.namespaceURI, - exteriorWritten !== undefined ? 'interior' : 'exterior'); + exteriorWritten !== undefined ? 'interior' : 'exterior'); }; @@ -746,24 +746,24 @@ GML3.prototype.RING_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) { * @private */ GML3.prototype.writeSurfaceOrPolygon_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsName = context['srsName']; if (node.nodeName !== 'PolygonPatch' && srsName) { node.setAttribute('srsName', srsName); } if (node.nodeName === 'Polygon' || node.nodeName === 'PolygonPatch') { - var rings = geometry.getLinearRings(); + const rings = geometry.getLinearRings(); _ol_xml_.pushSerializeAndPop( - {node: node, hasZ: hasZ, srsName: srsName}, - GML3.RING_SERIALIZERS_, - this.RING_NODE_FACTORY_, - rings, objectStack, undefined, this); + {node: node, hasZ: hasZ, srsName: srsName}, + GML3.RING_SERIALIZERS_, + this.RING_NODE_FACTORY_, + rings, objectStack, undefined, this); } else if (node.nodeName === 'Surface') { - var patches = _ol_xml_.createElementNS(node.namespaceURI, 'patches'); + const patches = _ol_xml_.createElementNS(node.namespaceURI, 'patches'); node.appendChild(patches); this.writeSurfacePatches_( - patches, geometry, objectStack); + patches, geometry, objectStack); } }; @@ -775,21 +775,21 @@ GML3.prototype.writeSurfaceOrPolygon_ = function(node, geometry, objectStack) { * @private */ GML3.prototype.writeCurveOrLineString_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var srsName = context['srsName']; + const context = objectStack[objectStack.length - 1]; + const srsName = context['srsName']; if (node.nodeName !== 'LineStringSegment' && srsName) { node.setAttribute('srsName', srsName); } if (node.nodeName === 'LineString' || node.nodeName === 'LineStringSegment') { - var posList = _ol_xml_.createElementNS(node.namespaceURI, 'posList'); + const posList = _ol_xml_.createElementNS(node.namespaceURI, 'posList'); node.appendChild(posList); this.writePosList_(posList, geometry, objectStack); } else if (node.nodeName === 'Curve') { - var segments = _ol_xml_.createElementNS(node.namespaceURI, 'segments'); + const segments = _ol_xml_.createElementNS(node.namespaceURI, 'segments'); node.appendChild(segments); this.writeCurveSegments_(segments, - geometry, objectStack); + geometry, objectStack); } }; @@ -801,18 +801,18 @@ GML3.prototype.writeCurveOrLineString_ = function(node, geometry, objectStack) { * @private */ GML3.prototype.writeMultiSurfaceOrPolygon_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsName = context['srsName']; - var surface = context['surface']; + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsName = context['srsName']; + const surface = context['surface']; if (srsName) { node.setAttribute('srsName', srsName); } - var polygons = geometry.getPolygons(); + const polygons = geometry.getPolygons(); _ol_xml_.pushSerializeAndPop({node: node, hasZ: hasZ, srsName: srsName, surface: surface}, - GML3.SURFACEORPOLYGONMEMBER_SERIALIZERS_, - this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_, polygons, - objectStack, undefined, this); + GML3.SURFACEORPOLYGONMEMBER_SERIALIZERS_, + this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_, polygons, + objectStack, undefined, this); }; @@ -823,18 +823,18 @@ GML3.prototype.writeMultiSurfaceOrPolygon_ = function(node, geometry, objectStac * @private */ GML3.prototype.writeMultiPoint_ = function(node, geometry, - objectStack) { - var context = objectStack[objectStack.length - 1]; - var srsName = context['srsName']; - var hasZ = context['hasZ']; + objectStack) { + const context = objectStack[objectStack.length - 1]; + const srsName = context['srsName']; + const hasZ = context['hasZ']; if (srsName) { node.setAttribute('srsName', srsName); } - var points = geometry.getPoints(); + const points = geometry.getPoints(); _ol_xml_.pushSerializeAndPop({node: node, hasZ: hasZ, srsName: srsName}, - GML3.POINTMEMBER_SERIALIZERS_, - _ol_xml_.makeSimpleNodeFactory('pointMember'), points, - objectStack, undefined, this); + GML3.POINTMEMBER_SERIALIZERS_, + _ol_xml_.makeSimpleNodeFactory('pointMember'), points, + objectStack, undefined, this); }; @@ -845,18 +845,18 @@ GML3.prototype.writeMultiPoint_ = function(node, geometry, * @private */ GML3.prototype.writeMultiCurveOrLineString_ = function(node, geometry, objectStack) { - var context = objectStack[objectStack.length - 1]; - var hasZ = context['hasZ']; - var srsName = context['srsName']; - var curve = context['curve']; + const context = objectStack[objectStack.length - 1]; + const hasZ = context['hasZ']; + const srsName = context['srsName']; + const curve = context['curve']; if (srsName) { node.setAttribute('srsName', srsName); } - var lines = geometry.getLineStrings(); + const lines = geometry.getLineStrings(); _ol_xml_.pushSerializeAndPop({node: node, hasZ: hasZ, srsName: srsName, curve: curve}, - GML3.LINESTRINGORCURVEMEMBER_SERIALIZERS_, - this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_, lines, - objectStack, undefined, this); + GML3.LINESTRINGORCURVEMEMBER_SERIALIZERS_, + this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_, lines, + objectStack, undefined, this); }; @@ -867,7 +867,7 @@ GML3.prototype.writeMultiCurveOrLineString_ = function(node, geometry, objectSta * @private */ GML3.prototype.writeRing_ = function(node, ring, objectStack) { - var linearRing = _ol_xml_.createElementNS(node.namespaceURI, 'LinearRing'); + const linearRing = _ol_xml_.createElementNS(node.namespaceURI, 'LinearRing'); node.appendChild(linearRing); this.writeLinearRing_(linearRing, ring, objectStack); }; @@ -880,8 +880,8 @@ GML3.prototype.writeRing_ = function(node, ring, objectStack) { * @private */ GML3.prototype.writeSurfaceOrPolygonMember_ = function(node, polygon, objectStack) { - var child = this.GEOMETRY_NODE_FACTORY_( - polygon, objectStack); + const child = this.GEOMETRY_NODE_FACTORY_( + polygon, objectStack); if (child) { node.appendChild(child); this.writeSurfaceOrPolygon_(child, polygon, objectStack); @@ -896,7 +896,7 @@ GML3.prototype.writeSurfaceOrPolygonMember_ = function(node, polygon, objectStac * @private */ GML3.prototype.writePointMember_ = function(node, point, objectStack) { - var child = _ol_xml_.createElementNS(node.namespaceURI, 'Point'); + const child = _ol_xml_.createElementNS(node.namespaceURI, 'Point'); node.appendChild(child); this.writePoint_(child, point, objectStack); }; @@ -909,7 +909,7 @@ GML3.prototype.writePointMember_ = function(node, point, objectStack) { * @private */ GML3.prototype.writeLineStringOrCurveMember_ = function(node, line, objectStack) { - var child = this.GEOMETRY_NODE_FACTORY_(line, objectStack); + const child = this.GEOMETRY_NODE_FACTORY_(line, objectStack); if (child) { node.appendChild(child); this.writeCurveOrLineString_(child, line, objectStack); @@ -924,7 +924,7 @@ GML3.prototype.writeLineStringOrCurveMember_ = function(node, line, objectStack) * @private */ GML3.prototype.writeSurfacePatches_ = function(node, polygon, objectStack) { - var child = _ol_xml_.createElementNS(node.namespaceURI, 'PolygonPatch'); + const child = _ol_xml_.createElementNS(node.namespaceURI, 'PolygonPatch'); node.appendChild(child); this.writeSurfaceOrPolygon_(child, polygon, objectStack); }; @@ -937,8 +937,8 @@ GML3.prototype.writeSurfacePatches_ = function(node, polygon, objectStack) { * @private */ GML3.prototype.writeCurveSegments_ = function(node, line, objectStack) { - var child = _ol_xml_.createElementNS(node.namespaceURI, - 'LineStringSegment'); + const child = _ol_xml_.createElementNS(node.namespaceURI, + 'LineStringSegment'); node.appendChild(child); this.writeCurveOrLineString_(child, line, objectStack); }; @@ -950,14 +950,14 @@ GML3.prototype.writeCurveSegments_ = function(node, line, objectStack) { * @param {Array.<*>} objectStack Node stack. */ GML3.prototype.writeGeometryElement = function(node, geometry, objectStack) { - var context = /** @type {olx.format.WriteOptions} */ (objectStack[objectStack.length - 1]); - var item = _ol_obj_.assign({}, context); + const context = /** @type {olx.format.WriteOptions} */ (objectStack[objectStack.length - 1]); + const item = _ol_obj_.assign({}, context); item.node = node; - var value; + let value; if (Array.isArray(geometry)) { if (context.dataProjection) { value = transformExtent( - geometry, context.featureProjection, context.dataProjection); + geometry, context.featureProjection, context.dataProjection); } else { value = geometry; } @@ -965,9 +965,9 @@ GML3.prototype.writeGeometryElement = function(node, geometry, objectStack) { value = transformWithOptions(/** @type {ol.geom.Geometry} */ (geometry), true, context); } _ol_xml_.pushSerializeAndPop(/** @type {ol.XmlNodeStackItem} */ - (item), GML3.GEOMETRY_SERIALIZERS_, - this.GEOMETRY_NODE_FACTORY_, [value], - objectStack, undefined, this); + (item), GML3.GEOMETRY_SERIALIZERS_, + this.GEOMETRY_NODE_FACTORY_, [value], + objectStack, undefined, this); }; @@ -977,44 +977,45 @@ GML3.prototype.writeGeometryElement = function(node, geometry, objectStack) { * @param {Array.<*>} objectStack Node stack. */ GML3.prototype.writeFeatureElement = function(node, feature, objectStack) { - var fid = feature.getId(); + const fid = feature.getId(); if (fid) { node.setAttribute('fid', fid); } - var context = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var featureNS = context['featureNS']; - var geometryName = feature.getGeometryName(); + const context = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const featureNS = context['featureNS']; + const geometryName = feature.getGeometryName(); if (!context.serializers) { context.serializers = {}; context.serializers[featureNS] = {}; } - var properties = feature.getProperties(); - var keys = [], values = []; - for (var key in properties) { - var value = properties[key]; + const properties = feature.getProperties(); + const keys = []; + const values = []; + for (const key in properties) { + const value = properties[key]; if (value !== null) { keys.push(key); values.push(value); if (key == geometryName || value instanceof Geometry) { if (!(key in context.serializers[featureNS])) { context.serializers[featureNS][key] = _ol_xml_.makeChildAppender( - this.writeGeometryElement, this); + this.writeGeometryElement, this); } } else { if (!(key in context.serializers[featureNS])) { context.serializers[featureNS][key] = _ol_xml_.makeChildAppender( - XSD.writeStringTextNode); + XSD.writeStringTextNode); } } } } - var item = _ol_obj_.assign({}, context); + const item = _ol_obj_.assign({}, context); item.node = node; _ol_xml_.pushSerializeAndPop(/** @type {ol.XmlNodeStackItem} */ - (item), context.serializers, - _ol_xml_.makeSimpleNodeFactory(undefined, featureNS), - values, - objectStack, keys); + (item), context.serializers, + _ol_xml_.makeSimpleNodeFactory(undefined, featureNS), + values, + objectStack, keys); }; @@ -1025,20 +1026,20 @@ GML3.prototype.writeFeatureElement = function(node, feature, objectStack) { * @private */ GML3.prototype.writeFeatureMembers_ = function(node, features, objectStack) { - var context = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var featureType = context['featureType']; - var featureNS = context['featureNS']; - var serializers = {}; + const context = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const featureType = context['featureType']; + const featureNS = context['featureNS']; + const serializers = {}; serializers[featureNS] = {}; serializers[featureNS][featureType] = _ol_xml_.makeChildAppender( - this.writeFeatureElement, this); - var item = _ol_obj_.assign({}, context); + this.writeFeatureElement, this); + const item = _ol_obj_.assign({}, context); item.node = node; _ol_xml_.pushSerializeAndPop(/** @type {ol.XmlNodeStackItem} */ - (item), - serializers, - _ol_xml_.makeSimpleNodeFactory(featureType, featureNS), features, - objectStack); + (item), + serializers, + _ol_xml_.makeSimpleNodeFactory(featureType, featureNS), features, + objectStack); }; @@ -1049,9 +1050,9 @@ GML3.prototype.writeFeatureMembers_ = function(node, features, objectStack) { GML3.SURFACEORPOLYGONMEMBER_SERIALIZERS_ = { 'http://www.opengis.net/gml': { 'surfaceMember': _ol_xml_.makeChildAppender( - GML3.prototype.writeSurfaceOrPolygonMember_), + GML3.prototype.writeSurfaceOrPolygonMember_), 'polygonMember': _ol_xml_.makeChildAppender( - GML3.prototype.writeSurfaceOrPolygonMember_) + GML3.prototype.writeSurfaceOrPolygonMember_) } }; @@ -1063,7 +1064,7 @@ GML3.SURFACEORPOLYGONMEMBER_SERIALIZERS_ = { GML3.POINTMEMBER_SERIALIZERS_ = { 'http://www.opengis.net/gml': { 'pointMember': _ol_xml_.makeChildAppender( - GML3.prototype.writePointMember_) + GML3.prototype.writePointMember_) } }; @@ -1075,9 +1076,9 @@ GML3.POINTMEMBER_SERIALIZERS_ = { GML3.LINESTRINGORCURVEMEMBER_SERIALIZERS_ = { 'http://www.opengis.net/gml': { 'lineStringMember': _ol_xml_.makeChildAppender( - GML3.prototype.writeLineStringOrCurveMember_), + GML3.prototype.writeLineStringOrCurveMember_), 'curveMember': _ol_xml_.makeChildAppender( - GML3.prototype.writeLineStringOrCurveMember_) + GML3.prototype.writeLineStringOrCurveMember_) } }; @@ -1101,28 +1102,28 @@ GML3.RING_SERIALIZERS_ = { GML3.GEOMETRY_SERIALIZERS_ = { 'http://www.opengis.net/gml': { 'Curve': _ol_xml_.makeChildAppender( - GML3.prototype.writeCurveOrLineString_), + GML3.prototype.writeCurveOrLineString_), 'MultiCurve': _ol_xml_.makeChildAppender( - GML3.prototype.writeMultiCurveOrLineString_), + GML3.prototype.writeMultiCurveOrLineString_), 'Point': _ol_xml_.makeChildAppender(GML3.prototype.writePoint_), 'MultiPoint': _ol_xml_.makeChildAppender( - GML3.prototype.writeMultiPoint_), + GML3.prototype.writeMultiPoint_), 'LineString': _ol_xml_.makeChildAppender( - GML3.prototype.writeCurveOrLineString_), + GML3.prototype.writeCurveOrLineString_), 'MultiLineString': _ol_xml_.makeChildAppender( - GML3.prototype.writeMultiCurveOrLineString_), + GML3.prototype.writeMultiCurveOrLineString_), 'LinearRing': _ol_xml_.makeChildAppender( - GML3.prototype.writeLinearRing_), + GML3.prototype.writeLinearRing_), 'Polygon': _ol_xml_.makeChildAppender( - GML3.prototype.writeSurfaceOrPolygon_), + GML3.prototype.writeSurfaceOrPolygon_), 'MultiPolygon': _ol_xml_.makeChildAppender( - GML3.prototype.writeMultiSurfaceOrPolygon_), + GML3.prototype.writeMultiSurfaceOrPolygon_), 'Surface': _ol_xml_.makeChildAppender( - GML3.prototype.writeSurfaceOrPolygon_), + GML3.prototype.writeSurfaceOrPolygon_), 'MultiSurface': _ol_xml_.makeChildAppender( - GML3.prototype.writeMultiSurfaceOrPolygon_), + GML3.prototype.writeMultiSurfaceOrPolygon_), 'Envelope': _ol_xml_.makeChildAppender( - GML3.prototype.writeEnvelope) + GML3.prototype.writeEnvelope) } }; @@ -1149,9 +1150,9 @@ GML3.MULTIGEOMETRY_TO_MEMBER_NODENAME_ = { * @private */ GML3.prototype.MULTIGEOMETRY_MEMBER_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) { - var parentNode = objectStack[objectStack.length - 1].node; + const parentNode = objectStack[objectStack.length - 1].node; return _ol_xml_.createElementNS('http://www.opengis.net/gml', - GML3.MULTIGEOMETRY_TO_MEMBER_NODENAME_[parentNode.nodeName]); + GML3.MULTIGEOMETRY_TO_MEMBER_NODENAME_[parentNode.nodeName]); }; @@ -1164,12 +1165,12 @@ GML3.prototype.MULTIGEOMETRY_MEMBER_NODE_FACTORY_ = function(value, objectStack, * @private */ GML3.prototype.GEOMETRY_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) { - var context = objectStack[objectStack.length - 1]; - var multiSurface = context['multiSurface']; - var surface = context['surface']; - var curve = context['curve']; - var multiCurve = context['multiCurve']; - var nodeName; + const context = objectStack[objectStack.length - 1]; + const multiSurface = context['multiSurface']; + const surface = context['surface']; + const curve = context['curve']; + const multiCurve = context['multiCurve']; + let nodeName; if (!Array.isArray(value)) { nodeName = /** @type {ol.geom.Geometry} */ (value).getType(); if (nodeName === 'MultiPolygon' && multiSurface === true) { @@ -1185,7 +1186,7 @@ GML3.prototype.GEOMETRY_NODE_FACTORY_ = function(value, objectStack, opt_nodeNam nodeName = 'Envelope'; } return _ol_xml_.createElementNS('http://www.opengis.net/gml', - nodeName); + nodeName); }; @@ -1200,8 +1201,8 @@ GML3.prototype.GEOMETRY_NODE_FACTORY_ = function(value, objectStack, opt_nodeNam */ GML3.prototype.writeGeometryNode = function(geometry, opt_options) { opt_options = this.adaptOptions(opt_options); - var geom = _ol_xml_.createElementNS('http://www.opengis.net/gml', 'geom'); - var context = {node: geom, hasZ: this.hasZ, srsName: this.srsName, + const geom = _ol_xml_.createElementNS('http://www.opengis.net/gml', 'geom'); + const context = {node: geom, hasZ: this.hasZ, srsName: this.srsName, curve: this.curve_, surface: this.surface_, multiSurface: this.multiSurface_, multiCurve: this.multiCurve_}; if (opt_options) { @@ -1235,11 +1236,11 @@ GML3.prototype.writeFeatures; */ GML3.prototype.writeFeaturesNode = function(features, opt_options) { opt_options = this.adaptOptions(opt_options); - var node = _ol_xml_.createElementNS('http://www.opengis.net/gml', - 'featureMembers'); + const node = _ol_xml_.createElementNS('http://www.opengis.net/gml', + 'featureMembers'); _ol_xml_.setAttributeNS(node, 'http://www.w3.org/2001/XMLSchema-instance', - 'xsi:schemaLocation', this.schemaLocation); - var context = { + 'xsi:schemaLocation', this.schemaLocation); + const context = { srsName: this.srsName, hasZ: this.hasZ, curve: this.curve_, diff --git a/src/ol/format/GMLBase.js b/src/ol/format/GMLBase.js index bd7bcdec2a..ba99c01cd9 100644 --- a/src/ol/format/GMLBase.js +++ b/src/ol/format/GMLBase.js @@ -36,8 +36,8 @@ import _ol_xml_ from '../xml.js'; * Optional configuration object. * @extends {ol.format.XMLFeature} */ -var GMLBase = function(opt_options) { - var options = /** @type {olx.format.GMLOptions} */ +const GMLBase = function(opt_options) { + const options = /** @type {olx.format.GMLOptions} */ (opt_options ? opt_options : {}); /** @@ -70,9 +70,9 @@ var GMLBase = function(opt_options) { this.FEATURE_COLLECTION_PARSERS = {}; this.FEATURE_COLLECTION_PARSERS[GMLBase.GMLNS] = { 'featureMember': _ol_xml_.makeReplacer( - GMLBase.prototype.readFeaturesInternal), + GMLBase.prototype.readFeaturesInternal), 'featureMembers': _ol_xml_.makeReplacer( - GMLBase.prototype.readFeaturesInternal) + GMLBase.prototype.readFeaturesInternal) }; XMLFeature.call(this); @@ -109,34 +109,36 @@ GMLBase.ONLY_WHITESPACE_RE_ = /^[\s\xa0]*$/; * @return {Array. | undefined} Features. */ GMLBase.prototype.readFeaturesInternal = function(node, objectStack) { - var localName = node.localName; - var features = null; + const localName = node.localName; + let features = null; if (localName == 'FeatureCollection') { if (node.namespaceURI === 'http://www.opengis.net/wfs') { features = _ol_xml_.pushParseAndPop([], - this.FEATURE_COLLECTION_PARSERS, node, - objectStack, this); + this.FEATURE_COLLECTION_PARSERS, node, + objectStack, this); } else { features = _ol_xml_.pushParseAndPop(null, - this.FEATURE_COLLECTION_PARSERS, node, - objectStack, this); + this.FEATURE_COLLECTION_PARSERS, node, + objectStack, this); } } else if (localName == 'featureMembers' || localName == 'featureMember') { - var context = objectStack[0]; - var featureType = context['featureType']; - var featureNS = context['featureNS']; - var i, ii, prefix = 'p', defaultPrefix = 'p0'; + const context = objectStack[0]; + let featureType = context['featureType']; + let featureNS = context['featureNS']; + let i, ii; + const prefix = 'p'; + const defaultPrefix = 'p0'; if (!featureType && node.childNodes) { featureType = [], featureNS = {}; for (i = 0, ii = node.childNodes.length; i < ii; ++i) { - var child = node.childNodes[i]; + const child = node.childNodes[i]; if (child.nodeType === 1) { - var ft = child.nodeName.split(':').pop(); + const ft = child.nodeName.split(':').pop(); if (featureType.indexOf(ft) === -1) { - var key = ''; - var count = 0; - var uri = child.namespaceURI; - for (var candidate in featureNS) { + let key = ''; + let count = 0; + const uri = child.namespaceURI; + for (const candidate in featureNS) { if (featureNS[candidate] === uri) { key = candidate; break; @@ -158,16 +160,16 @@ GMLBase.prototype.readFeaturesInternal = function(node, objectStack) { } } if (typeof featureNS === 'string') { - var ns = featureNS; + const ns = featureNS; featureNS = {}; featureNS[defaultPrefix] = ns; } - var parsersNS = {}; - var featureTypes = Array.isArray(featureType) ? featureType : [featureType]; - for (var p in featureNS) { - var parsers = {}; + const parsersNS = {}; + const featureTypes = Array.isArray(featureType) ? featureType : [featureType]; + for (const p in featureNS) { + const parsers = {}; for (i = 0, ii = featureTypes.length; i < ii; ++i) { - var featurePrefix = featureTypes[i].indexOf(':') === -1 ? + const featurePrefix = featureTypes[i].indexOf(':') === -1 ? defaultPrefix : featureTypes[i].split(':')[0]; if (featurePrefix === p) { parsers[featureTypes[i].split(':').pop()] = @@ -197,12 +199,12 @@ GMLBase.prototype.readFeaturesInternal = function(node, objectStack) { * @return {ol.geom.Geometry|undefined} Geometry. */ GMLBase.prototype.readGeometryElement = function(node, objectStack) { - var context = /** @type {Object} */ (objectStack[0]); + const context = /** @type {Object} */ (objectStack[0]); context['srsName'] = node.firstElementChild.getAttribute('srsName'); context['srsDimension'] = node.firstElementChild.getAttribute('srsDimension'); /** @type {ol.geom.Geometry} */ - var geometry = _ol_xml_.pushParseAndPop(null, - this.GEOMETRY_PARSERS_, node, objectStack, this); + const geometry = _ol_xml_.pushParseAndPop(null, + this.GEOMETRY_PARSERS_, node, objectStack, this); if (geometry) { return ( /** @type {ol.geom.Geometry} */ transformWithOptions(geometry, false, context) @@ -219,19 +221,20 @@ GMLBase.prototype.readGeometryElement = function(node, objectStack) { * @return {ol.Feature} Feature. */ GMLBase.prototype.readFeatureElement = function(node, objectStack) { - var n; - var fid = node.getAttribute('fid') || + let n; + const fid = node.getAttribute('fid') || _ol_xml_.getAttributeNS(node, GMLBase.GMLNS, 'id'); - var values = {}, geometryName; + const values = {}; + let geometryName; for (n = node.firstElementChild; n; n = n.nextElementSibling) { - var localName = n.localName; + const localName = n.localName; // Assume attribute elements have one child node and that the child // is a text or CDATA node (to be treated as text). // Otherwise assume it is a geometry node. if (n.childNodes.length === 0 || (n.childNodes.length === 1 && (n.firstChild.nodeType === 3 || n.firstChild.nodeType === 4))) { - var value = _ol_xml_.getAllTextContent(n, false); + let value = _ol_xml_.getAllTextContent(n, false); if (GMLBase.ONLY_WHITESPACE_RE_.test(value)) { value = undefined; } @@ -244,7 +247,7 @@ GMLBase.prototype.readFeatureElement = function(node, objectStack) { values[localName] = this.readGeometryElement(n, objectStack); } } - var feature = new Feature(values); + const feature = new Feature(values); if (geometryName) { feature.setGeometryName(geometryName); } @@ -261,10 +264,10 @@ GMLBase.prototype.readFeatureElement = function(node, objectStack) { * @return {ol.geom.Point|undefined} Point. */ GMLBase.prototype.readPoint = function(node, objectStack) { - var flatCoordinates = + const flatCoordinates = this.readFlatCoordinatesFromNode_(node, objectStack); if (flatCoordinates) { - var point = new Point(null); + const point = new Point(null); point.setFlatCoordinates(GeometryLayout.XYZ, flatCoordinates); return point; } @@ -278,8 +281,8 @@ GMLBase.prototype.readPoint = function(node, objectStack) { */ GMLBase.prototype.readMultiPoint = function(node, objectStack) { /** @type {Array.>} */ - var coordinates = _ol_xml_.pushParseAndPop([], - this.MULTIPOINT_PARSERS_, node, objectStack, this); + const coordinates = _ol_xml_.pushParseAndPop([], + this.MULTIPOINT_PARSERS_, node, objectStack, this); if (coordinates) { return new MultiPoint(coordinates); } else { @@ -295,10 +298,10 @@ GMLBase.prototype.readMultiPoint = function(node, objectStack) { */ GMLBase.prototype.readMultiLineString = function(node, objectStack) { /** @type {Array.} */ - var lineStrings = _ol_xml_.pushParseAndPop([], - this.MULTILINESTRING_PARSERS_, node, objectStack, this); + const lineStrings = _ol_xml_.pushParseAndPop([], + this.MULTILINESTRING_PARSERS_, node, objectStack, this); if (lineStrings) { - var multiLineString = new MultiLineString(null); + const multiLineString = new MultiLineString(null); multiLineString.setLineStrings(lineStrings); return multiLineString; } else { @@ -314,10 +317,10 @@ GMLBase.prototype.readMultiLineString = function(node, objectStack) { */ GMLBase.prototype.readMultiPolygon = function(node, objectStack) { /** @type {Array.} */ - var polygons = _ol_xml_.pushParseAndPop([], - this.MULTIPOLYGON_PARSERS_, node, objectStack, this); + const polygons = _ol_xml_.pushParseAndPop([], + this.MULTIPOLYGON_PARSERS_, node, objectStack, this); if (polygons) { - var multiPolygon = new MultiPolygon(null); + const multiPolygon = new MultiPolygon(null); multiPolygon.setPolygons(polygons); return multiPolygon; } else { @@ -333,7 +336,7 @@ GMLBase.prototype.readMultiPolygon = function(node, objectStack) { */ GMLBase.prototype.pointMemberParser_ = function(node, objectStack) { _ol_xml_.parseNode(this.POINTMEMBER_PARSERS_, - node, objectStack, this); + node, objectStack, this); }; @@ -344,7 +347,7 @@ GMLBase.prototype.pointMemberParser_ = function(node, objectStack) { */ GMLBase.prototype.lineStringMemberParser_ = function(node, objectStack) { _ol_xml_.parseNode(this.LINESTRINGMEMBER_PARSERS_, - node, objectStack, this); + node, objectStack, this); }; @@ -355,7 +358,7 @@ GMLBase.prototype.lineStringMemberParser_ = function(node, objectStack) { */ GMLBase.prototype.polygonMemberParser_ = function(node, objectStack) { _ol_xml_.parseNode(this.POLYGONMEMBER_PARSERS_, node, - objectStack, this); + objectStack, this); }; @@ -365,10 +368,10 @@ GMLBase.prototype.polygonMemberParser_ = function(node, objectStack) { * @return {ol.geom.LineString|undefined} LineString. */ GMLBase.prototype.readLineString = function(node, objectStack) { - var flatCoordinates = + const flatCoordinates = this.readFlatCoordinatesFromNode_(node, objectStack); if (flatCoordinates) { - var lineString = new LineString(null); + const lineString = new LineString(null); lineString.setFlatCoordinates(GeometryLayout.XYZ, flatCoordinates); return lineString; } else { @@ -384,9 +387,9 @@ GMLBase.prototype.readLineString = function(node, objectStack) { * @return {Array.|undefined} LinearRing flat coordinates. */ GMLBase.prototype.readFlatLinearRing_ = function(node, objectStack) { - var ring = _ol_xml_.pushParseAndPop(null, - this.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, - objectStack, this); + const ring = _ol_xml_.pushParseAndPop(null, + this.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, + objectStack, this); if (ring) { return ring; } else { @@ -401,10 +404,10 @@ GMLBase.prototype.readFlatLinearRing_ = function(node, objectStack) { * @return {ol.geom.LinearRing|undefined} LinearRing. */ GMLBase.prototype.readLinearRing = function(node, objectStack) { - var flatCoordinates = + const flatCoordinates = this.readFlatCoordinatesFromNode_(node, objectStack); if (flatCoordinates) { - var ring = new LinearRing(null); + const ring = new LinearRing(null); ring.setFlatCoordinates(GeometryLayout.XYZ, flatCoordinates); return ring; } else { @@ -420,19 +423,19 @@ GMLBase.prototype.readLinearRing = function(node, objectStack) { */ GMLBase.prototype.readPolygon = function(node, objectStack) { /** @type {Array.>} */ - var flatLinearRings = _ol_xml_.pushParseAndPop([null], - this.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack, this); + const flatLinearRings = _ol_xml_.pushParseAndPop([null], + this.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack, this); if (flatLinearRings && flatLinearRings[0]) { - var polygon = new Polygon(null); - var flatCoordinates = flatLinearRings[0]; - var ends = [flatCoordinates.length]; - var i, ii; + const polygon = new Polygon(null); + const flatCoordinates = flatLinearRings[0]; + const ends = [flatCoordinates.length]; + let i, ii; for (i = 1, ii = flatLinearRings.length; i < ii; ++i) { extend(flatCoordinates, flatLinearRings[i]); ends.push(flatCoordinates.length); } polygon.setFlatCoordinates( - GeometryLayout.XYZ, flatCoordinates, ends); + GeometryLayout.XYZ, flatCoordinates, ends); return polygon; } else { return undefined; @@ -448,8 +451,8 @@ GMLBase.prototype.readPolygon = function(node, objectStack) { */ GMLBase.prototype.readFlatCoordinatesFromNode_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop(null, - this.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, - objectStack, this); + this.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, + objectStack, this); }; @@ -461,9 +464,9 @@ GMLBase.prototype.readFlatCoordinatesFromNode_ = function(node, objectStack) { GMLBase.prototype.MULTIPOINT_PARSERS_ = { 'http://www.opengis.net/gml': { 'pointMember': _ol_xml_.makeArrayPusher( - GMLBase.prototype.pointMemberParser_), + GMLBase.prototype.pointMemberParser_), 'pointMembers': _ol_xml_.makeArrayPusher( - GMLBase.prototype.pointMemberParser_) + GMLBase.prototype.pointMemberParser_) } }; @@ -476,9 +479,9 @@ GMLBase.prototype.MULTIPOINT_PARSERS_ = { GMLBase.prototype.MULTILINESTRING_PARSERS_ = { 'http://www.opengis.net/gml': { 'lineStringMember': _ol_xml_.makeArrayPusher( - GMLBase.prototype.lineStringMemberParser_), + GMLBase.prototype.lineStringMemberParser_), 'lineStringMembers': _ol_xml_.makeArrayPusher( - GMLBase.prototype.lineStringMemberParser_) + GMLBase.prototype.lineStringMemberParser_) } }; @@ -491,9 +494,9 @@ GMLBase.prototype.MULTILINESTRING_PARSERS_ = { GMLBase.prototype.MULTIPOLYGON_PARSERS_ = { 'http://www.opengis.net/gml': { 'polygonMember': _ol_xml_.makeArrayPusher( - GMLBase.prototype.polygonMemberParser_), + GMLBase.prototype.polygonMemberParser_), 'polygonMembers': _ol_xml_.makeArrayPusher( - GMLBase.prototype.polygonMemberParser_) + GMLBase.prototype.polygonMemberParser_) } }; @@ -506,7 +509,7 @@ GMLBase.prototype.MULTIPOLYGON_PARSERS_ = { GMLBase.prototype.POINTMEMBER_PARSERS_ = { 'http://www.opengis.net/gml': { 'Point': _ol_xml_.makeArrayPusher( - GMLBase.prototype.readFlatCoordinatesFromNode_) + GMLBase.prototype.readFlatCoordinatesFromNode_) } }; @@ -519,7 +522,7 @@ GMLBase.prototype.POINTMEMBER_PARSERS_ = { GMLBase.prototype.LINESTRINGMEMBER_PARSERS_ = { 'http://www.opengis.net/gml': { 'LineString': _ol_xml_.makeArrayPusher( - GMLBase.prototype.readLineString) + GMLBase.prototype.readLineString) } }; @@ -532,7 +535,7 @@ GMLBase.prototype.LINESTRINGMEMBER_PARSERS_ = { GMLBase.prototype.POLYGONMEMBER_PARSERS_ = { 'http://www.opengis.net/gml': { 'Polygon': _ol_xml_.makeArrayPusher( - GMLBase.prototype.readPolygon) + GMLBase.prototype.readPolygon) } }; @@ -545,7 +548,7 @@ GMLBase.prototype.POLYGONMEMBER_PARSERS_ = { GMLBase.prototype.RING_PARSERS = { 'http://www.opengis.net/gml': { 'LinearRing': _ol_xml_.makeReplacer( - GMLBase.prototype.readFlatLinearRing_) + GMLBase.prototype.readFlatLinearRing_) } }; @@ -554,8 +557,8 @@ GMLBase.prototype.RING_PARSERS = { * @inheritDoc */ GMLBase.prototype.readGeometryFromNode = function(node, opt_options) { - var geometry = this.readGeometryElement(node, - [this.getReadOptions(node, opt_options ? opt_options : {})]); + const geometry = this.readGeometryElement(node, + [this.getReadOptions(node, opt_options ? opt_options : {})]); return geometry ? geometry : null; }; @@ -576,14 +579,14 @@ GMLBase.prototype.readFeatures; * @inheritDoc */ GMLBase.prototype.readFeaturesFromNode = function(node, opt_options) { - var options = { + const options = { featureType: this.featureType, featureNS: this.featureNS }; if (opt_options) { _ol_obj_.assign(options, this.getReadOptions(node, opt_options)); } - var features = this.readFeaturesInternal(node, [options]); + const features = this.readFeaturesInternal(node, [options]); return features || []; }; diff --git a/src/ol/format/GPX.js b/src/ol/format/GPX.js index 134d301e6f..23475077cb 100644 --- a/src/ol/format/GPX.js +++ b/src/ol/format/GPX.js @@ -23,9 +23,9 @@ import _ol_xml_ from '../xml.js'; * @param {olx.format.GPXOptions=} opt_options Options. * @api */ -var GPX = function(opt_options) { +const GPX = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; XMLFeature.call(this); @@ -48,7 +48,7 @@ inherits(GPX, XMLFeature); * @const * @type {Array.} */ -var NAMESPACE_URIS = [ +const NAMESPACE_URIS = [ null, 'http://www.topografix.com/GPX/1/0', 'http://www.topografix.com/GPX/1/1' @@ -59,7 +59,7 @@ var NAMESPACE_URIS = [ * @const * @type {string} */ -var SCHEMA_LOCATION = 'http://www.topografix.com/GPX/1/1 ' + +const SCHEMA_LOCATION = 'http://www.topografix.com/GPX/1/1 ' + 'http://www.topografix.com/GPX/1/1/gpx.xsd'; @@ -67,7 +67,7 @@ var SCHEMA_LOCATION = 'http://www.topografix.com/GPX/1/1 ' + * @const * @type {Object.): (ol.Feature|undefined)>} */ -var FEATURE_READER = { +const FEATURE_READER = { 'rte': readRte, 'trk': readTrk, 'wpt': readWpt @@ -78,264 +78,264 @@ var FEATURE_READER = { * @const * @type {Object.>} */ -var GPX_PARSERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'rte': _ol_xml_.makeArrayPusher(readRte), - 'trk': _ol_xml_.makeArrayPusher(readTrk), - 'wpt': _ol_xml_.makeArrayPusher(readWpt) - }); +const GPX_PARSERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'rte': _ol_xml_.makeArrayPusher(readRte), + 'trk': _ol_xml_.makeArrayPusher(readTrk), + 'wpt': _ol_xml_.makeArrayPusher(readWpt) + }); /** * @const * @type {Object.>} */ -var LINK_PARSERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'text': _ol_xml_.makeObjectPropertySetter(XSD.readString, 'linkText'), - 'type': _ol_xml_.makeObjectPropertySetter(XSD.readString, 'linkType') - }); +const LINK_PARSERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'text': _ol_xml_.makeObjectPropertySetter(XSD.readString, 'linkText'), + 'type': _ol_xml_.makeObjectPropertySetter(XSD.readString, 'linkType') + }); /** * @const * @type {Object.>} */ -var RTE_PARSERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'name': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'cmt': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'desc': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'src': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'link': parseLink, - 'number': _ol_xml_.makeObjectPropertySetter(XSD.readNonNegativeInteger), - 'extensions': parseExtensions, - 'type': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'rtept': parseRtePt - }); +const RTE_PARSERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'name': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'cmt': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'desc': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'src': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'link': parseLink, + 'number': _ol_xml_.makeObjectPropertySetter(XSD.readNonNegativeInteger), + 'extensions': parseExtensions, + 'type': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'rtept': parseRtePt + }); /** * @const * @type {Object.>} */ -var RTEPT_PARSERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'ele': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'time': _ol_xml_.makeObjectPropertySetter(XSD.readDateTime) - }); +const RTEPT_PARSERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'ele': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'time': _ol_xml_.makeObjectPropertySetter(XSD.readDateTime) + }); /** * @const * @type {Object.>} */ -var TRK_PARSERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'name': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'cmt': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'desc': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'src': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'link': parseLink, - 'number': _ol_xml_.makeObjectPropertySetter(XSD.readNonNegativeInteger), - 'type': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'extensions': parseExtensions, - 'trkseg': parseTrkSeg - }); +const TRK_PARSERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'name': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'cmt': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'desc': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'src': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'link': parseLink, + 'number': _ol_xml_.makeObjectPropertySetter(XSD.readNonNegativeInteger), + 'type': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'extensions': parseExtensions, + 'trkseg': parseTrkSeg + }); /** * @const * @type {Object.>} */ -var TRKSEG_PARSERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'trkpt': parseTrkPt - }); +const TRKSEG_PARSERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'trkpt': parseTrkPt + }); /** * @const * @type {Object.>} */ -var TRKPT_PARSERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'ele': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'time': _ol_xml_.makeObjectPropertySetter(XSD.readDateTime) - }); +const TRKPT_PARSERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'ele': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'time': _ol_xml_.makeObjectPropertySetter(XSD.readDateTime) + }); /** * @const * @type {Object.>} */ -var WPT_PARSERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'ele': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'time': _ol_xml_.makeObjectPropertySetter(XSD.readDateTime), - 'magvar': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'geoidheight': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'name': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'cmt': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'desc': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'src': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'link': parseLink, - 'sym': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'type': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'fix': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'sat': _ol_xml_.makeObjectPropertySetter(XSD.readNonNegativeInteger), - 'hdop': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'vdop': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'pdop': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'ageofdgpsdata': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'dgpsid': _ol_xml_.makeObjectPropertySetter(XSD.readNonNegativeInteger), - 'extensions': parseExtensions - }); +const WPT_PARSERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'ele': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'time': _ol_xml_.makeObjectPropertySetter(XSD.readDateTime), + 'magvar': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'geoidheight': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'name': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'cmt': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'desc': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'src': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'link': parseLink, + 'sym': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'type': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'fix': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'sat': _ol_xml_.makeObjectPropertySetter(XSD.readNonNegativeInteger), + 'hdop': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'vdop': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'pdop': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'ageofdgpsdata': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'dgpsid': _ol_xml_.makeObjectPropertySetter(XSD.readNonNegativeInteger), + 'extensions': parseExtensions + }); /** * @const * @type {Array.} */ -var LINK_SEQUENCE = ['text', 'type']; +const LINK_SEQUENCE = ['text', 'type']; /** * @const * @type {Object.>} */ -var LINK_SERIALIZERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'text': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'type': _ol_xml_.makeChildAppender(XSD.writeStringTextNode) - }); +const LINK_SERIALIZERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'text': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'type': _ol_xml_.makeChildAppender(XSD.writeStringTextNode) + }); /** * @const * @type {Object.>} */ -var RTE_SEQUENCE = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, [ - 'name', 'cmt', 'desc', 'src', 'link', 'number', 'type', 'rtept' - ]); +const RTE_SEQUENCE = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, [ + 'name', 'cmt', 'desc', 'src', 'link', 'number', 'type', 'rtept' + ]); /** * @const * @type {Object.>} */ -var RTE_SERIALIZERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'name': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'cmt': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'desc': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'src': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'link': _ol_xml_.makeChildAppender(writeLink), - 'number': _ol_xml_.makeChildAppender(XSD.writeNonNegativeIntegerTextNode), - 'type': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'rtept': _ol_xml_.makeArraySerializer(_ol_xml_.makeChildAppender(writeWptType)) - }); +const RTE_SERIALIZERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'name': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'cmt': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'desc': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'src': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'link': _ol_xml_.makeChildAppender(writeLink), + 'number': _ol_xml_.makeChildAppender(XSD.writeNonNegativeIntegerTextNode), + 'type': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'rtept': _ol_xml_.makeArraySerializer(_ol_xml_.makeChildAppender(writeWptType)) + }); /** * @const * @type {Object.>} */ -var RTEPT_TYPE_SEQUENCE = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, [ - 'ele', 'time' - ]); +const RTEPT_TYPE_SEQUENCE = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, [ + 'ele', 'time' + ]); /** * @const * @type {Object.>} */ -var TRK_SEQUENCE = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, [ - 'name', 'cmt', 'desc', 'src', 'link', 'number', 'type', 'trkseg' - ]); +const TRK_SEQUENCE = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, [ + 'name', 'cmt', 'desc', 'src', 'link', 'number', 'type', 'trkseg' + ]); /** * @const * @type {Object.>} */ -var TRK_SERIALIZERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'name': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'cmt': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'desc': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'src': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'link': _ol_xml_.makeChildAppender(writeLink), - 'number': _ol_xml_.makeChildAppender(XSD.writeNonNegativeIntegerTextNode), - 'type': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'trkseg': _ol_xml_.makeArraySerializer(_ol_xml_.makeChildAppender(writeTrkSeg)) - }); +const TRK_SERIALIZERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'name': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'cmt': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'desc': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'src': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'link': _ol_xml_.makeChildAppender(writeLink), + 'number': _ol_xml_.makeChildAppender(XSD.writeNonNegativeIntegerTextNode), + 'type': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'trkseg': _ol_xml_.makeArraySerializer(_ol_xml_.makeChildAppender(writeTrkSeg)) + }); /** * @const * @type {function(*, Array.<*>, string=): (Node|undefined)} */ -var TRKSEG_NODE_FACTORY = _ol_xml_.makeSimpleNodeFactory('trkpt'); +const TRKSEG_NODE_FACTORY = _ol_xml_.makeSimpleNodeFactory('trkpt'); /** * @const * @type {Object.>} */ -var TRKSEG_SERIALIZERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'trkpt': _ol_xml_.makeChildAppender(writeWptType) - }); +const TRKSEG_SERIALIZERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'trkpt': _ol_xml_.makeChildAppender(writeWptType) + }); /** * @const * @type {Object.>} */ -var WPT_TYPE_SEQUENCE = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, [ - 'ele', 'time', 'magvar', 'geoidheight', 'name', 'cmt', 'desc', 'src', - 'link', 'sym', 'type', 'fix', 'sat', 'hdop', 'vdop', 'pdop', - 'ageofdgpsdata', 'dgpsid' - ]); +const WPT_TYPE_SEQUENCE = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, [ + 'ele', 'time', 'magvar', 'geoidheight', 'name', 'cmt', 'desc', 'src', + 'link', 'sym', 'type', 'fix', 'sat', 'hdop', 'vdop', 'pdop', + 'ageofdgpsdata', 'dgpsid' + ]); /** * @const * @type {Object.>} */ -var WPT_TYPE_SERIALIZERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'ele': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'time': _ol_xml_.makeChildAppender(XSD.writeDateTimeTextNode), - 'magvar': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'geoidheight': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'name': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'cmt': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'desc': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'src': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'link': _ol_xml_.makeChildAppender(writeLink), - 'sym': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'type': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'fix': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'sat': _ol_xml_.makeChildAppender(XSD.writeNonNegativeIntegerTextNode), - 'hdop': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'vdop': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'pdop': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'ageofdgpsdata': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'dgpsid': _ol_xml_.makeChildAppender(XSD.writeNonNegativeIntegerTextNode) - }); +const WPT_TYPE_SERIALIZERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'ele': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'time': _ol_xml_.makeChildAppender(XSD.writeDateTimeTextNode), + 'magvar': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'geoidheight': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'name': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'cmt': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'desc': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'src': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'link': _ol_xml_.makeChildAppender(writeLink), + 'sym': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'type': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'fix': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'sat': _ol_xml_.makeChildAppender(XSD.writeNonNegativeIntegerTextNode), + 'hdop': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'vdop': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'pdop': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'ageofdgpsdata': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'dgpsid': _ol_xml_.makeChildAppender(XSD.writeNonNegativeIntegerTextNode) + }); /** * @const * @type {Object.} */ -var GEOMETRY_TYPE_TO_NODENAME = { +const GEOMETRY_TYPE_TO_NODENAME = { 'Point': 'wpt', 'LineString': 'rte', 'MultiLineString': 'trk' @@ -349,11 +349,11 @@ var GEOMETRY_TYPE_TO_NODENAME = { * @return {Node|undefined} Node. */ function GPX_NODE_FACTORY(value, objectStack, opt_nodeName) { - var geometry = /** @type {ol.Feature} */ (value).getGeometry(); + const geometry = /** @type {ol.Feature} */ (value).getGeometry(); if (geometry) { - var nodeName = GEOMETRY_TYPE_TO_NODENAME[geometry.getType()]; + const nodeName = GEOMETRY_TYPE_TO_NODENAME[geometry.getType()]; if (nodeName) { - var parentNode = objectStack[objectStack.length - 1].node; + const parentNode = objectStack[objectStack.length - 1].node; return _ol_xml_.createElementNS(parentNode.namespaceURI, nodeName); } } @@ -364,12 +364,12 @@ function GPX_NODE_FACTORY(value, objectStack, opt_nodeName) { * @const * @type {Object.>} */ -var GPX_SERIALIZERS = _ol_xml_.makeStructureNS( - NAMESPACE_URIS, { - 'rte': _ol_xml_.makeChildAppender(writeRte), - 'trk': _ol_xml_.makeChildAppender(writeTrk), - 'wpt': _ol_xml_.makeChildAppender(writeWpt) - }); +const GPX_SERIALIZERS = _ol_xml_.makeStructureNS( + NAMESPACE_URIS, { + 'rte': _ol_xml_.makeChildAppender(writeRte), + 'trk': _ol_xml_.makeChildAppender(writeTrk), + 'wpt': _ol_xml_.makeChildAppender(writeWpt) + }); /** @@ -381,8 +381,8 @@ var GPX_SERIALIZERS = _ol_xml_.makeStructureNS( */ function appendCoordinate(flatCoordinates, layoutOptions, node, values) { flatCoordinates.push( - parseFloat(node.getAttribute('lon')), - parseFloat(node.getAttribute('lat'))); + parseFloat(node.getAttribute('lon')), + parseFloat(node.getAttribute('lat'))); if ('ele' in values) { flatCoordinates.push(/** @type {number} */ (values['ele'])); delete values['ele']; @@ -411,8 +411,8 @@ function appendCoordinate(flatCoordinates, layoutOptions, node, values) { * @return {ol.geom.GeometryLayout} Layout. */ GPX.applyLayoutOptions_ = function(layoutOptions, flatCoordinates, ends) { - var layout = GeometryLayout.XY; - var stride = 2; + let layout = GeometryLayout.XY; + let stride = 2; if (layoutOptions.hasZ && layoutOptions.hasM) { layout = GeometryLayout.XYZM; stride = 4; @@ -424,7 +424,7 @@ GPX.applyLayoutOptions_ = function(layoutOptions, flatCoordinates, ends) { stride = 3; } if (stride !== 4) { - var i, ii; + let i, ii; for (i = 0, ii = flatCoordinates.length / 4; i < ii; i++) { flatCoordinates[i * stride] = flatCoordinates[i * 4]; flatCoordinates[i * stride + 1] = flatCoordinates[i * 4 + 1]; @@ -451,8 +451,8 @@ GPX.applyLayoutOptions_ = function(layoutOptions, flatCoordinates, ends) { * @param {Array.<*>} objectStack Object stack. */ function parseLink(node, objectStack) { - var values = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var href = node.getAttribute('href'); + const values = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const href = node.getAttribute('href'); if (href !== null) { values['link'] = href; } @@ -465,7 +465,7 @@ function parseLink(node, objectStack) { * @param {Array.<*>} objectStack Object stack. */ function parseExtensions(node, objectStack) { - var values = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const values = /** @type {Object} */ (objectStack[objectStack.length - 1]); values['extensionsNode_'] = node; } @@ -475,13 +475,13 @@ function parseExtensions(node, objectStack) { * @param {Array.<*>} objectStack Object stack. */ function parseRtePt(node, objectStack) { - var values = _ol_xml_.pushParseAndPop( - {}, RTEPT_PARSERS, node, objectStack); + const values = _ol_xml_.pushParseAndPop( + {}, RTEPT_PARSERS, node, objectStack); if (values) { - var rteValues = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var flatCoordinates = /** @type {Array.} */ + const rteValues = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const flatCoordinates = /** @type {Array.} */ (rteValues['flatCoordinates']); - var layoutOptions = /** @type {ol.LayoutOptions} */ + const layoutOptions = /** @type {ol.LayoutOptions} */ (rteValues['layoutOptions']); appendCoordinate(flatCoordinates, layoutOptions, node, values); } @@ -493,12 +493,12 @@ function parseRtePt(node, objectStack) { * @param {Array.<*>} objectStack Object stack. */ function parseTrkPt(node, objectStack) { - var values = _ol_xml_.pushParseAndPop({}, TRKPT_PARSERS, node, objectStack); + const values = _ol_xml_.pushParseAndPop({}, TRKPT_PARSERS, node, objectStack); if (values) { - var trkValues = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var flatCoordinates = /** @type {Array.} */ + const trkValues = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const flatCoordinates = /** @type {Array.} */ (trkValues['flatCoordinates']); - var layoutOptions = /** @type {ol.LayoutOptions} */ + const layoutOptions = /** @type {ol.LayoutOptions} */ (trkValues['layoutOptions']); appendCoordinate(flatCoordinates, layoutOptions, node, values); } @@ -510,11 +510,11 @@ function parseTrkPt(node, objectStack) { * @param {Array.<*>} objectStack Object stack. */ function parseTrkSeg(node, objectStack) { - var values = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const values = /** @type {Object} */ (objectStack[objectStack.length - 1]); _ol_xml_.parseNode(TRKSEG_PARSERS, node, objectStack); - var flatCoordinates = /** @type {Array.} */ + const flatCoordinates = /** @type {Array.} */ (values['flatCoordinates']); - var ends = /** @type {Array.} */ (values['ends']); + const ends = /** @type {Array.} */ (values['ends']); ends.push(flatCoordinates.length); } @@ -525,24 +525,24 @@ function parseTrkSeg(node, objectStack) { * @return {ol.Feature|undefined} Track. */ function readRte(node, objectStack) { - var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]); - var values = _ol_xml_.pushParseAndPop({ + const options = /** @type {olx.format.ReadOptions} */ (objectStack[0]); + const values = _ol_xml_.pushParseAndPop({ 'flatCoordinates': [], 'layoutOptions': {} }, RTE_PARSERS, node, objectStack); if (!values) { return undefined; } - var flatCoordinates = /** @type {Array.} */ + const flatCoordinates = /** @type {Array.} */ (values['flatCoordinates']); delete values['flatCoordinates']; - var layoutOptions = /** @type {ol.LayoutOptions} */ (values['layoutOptions']); + const layoutOptions = /** @type {ol.LayoutOptions} */ (values['layoutOptions']); delete values['layoutOptions']; - var layout = GPX.applyLayoutOptions_(layoutOptions, flatCoordinates); - var geometry = new LineString(null); + const layout = GPX.applyLayoutOptions_(layoutOptions, flatCoordinates); + const geometry = new LineString(null); geometry.setFlatCoordinates(layout, flatCoordinates); transformWithOptions(geometry, false, options); - var feature = new Feature(geometry); + const feature = new Feature(geometry); feature.setProperties(values); return feature; } @@ -554,8 +554,8 @@ function readRte(node, objectStack) { * @return {ol.Feature|undefined} Track. */ function readTrk(node, objectStack) { - var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]); - var values = _ol_xml_.pushParseAndPop({ + const options = /** @type {olx.format.ReadOptions} */ (objectStack[0]); + const values = _ol_xml_.pushParseAndPop({ 'flatCoordinates': [], 'ends': [], 'layoutOptions': {} @@ -563,18 +563,18 @@ function readTrk(node, objectStack) { if (!values) { return undefined; } - var flatCoordinates = /** @type {Array.} */ + const flatCoordinates = /** @type {Array.} */ (values['flatCoordinates']); delete values['flatCoordinates']; - var ends = /** @type {Array.} */ (values['ends']); + const ends = /** @type {Array.} */ (values['ends']); delete values['ends']; - var layoutOptions = /** @type {ol.LayoutOptions} */ (values['layoutOptions']); + const layoutOptions = /** @type {ol.LayoutOptions} */ (values['layoutOptions']); delete values['layoutOptions']; - var layout = GPX.applyLayoutOptions_(layoutOptions, flatCoordinates, ends); - var geometry = new MultiLineString(null); + const layout = GPX.applyLayoutOptions_(layoutOptions, flatCoordinates, ends); + const geometry = new MultiLineString(null); geometry.setFlatCoordinates(layout, flatCoordinates, ends); transformWithOptions(geometry, false, options); - var feature = new Feature(geometry); + const feature = new Feature(geometry); feature.setProperties(values); return feature; } @@ -586,17 +586,17 @@ function readTrk(node, objectStack) { * @return {ol.Feature|undefined} Waypoint. */ function readWpt(node, objectStack) { - var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]); - var values = _ol_xml_.pushParseAndPop({}, WPT_PARSERS, node, objectStack); + const options = /** @type {olx.format.ReadOptions} */ (objectStack[0]); + const values = _ol_xml_.pushParseAndPop({}, WPT_PARSERS, node, objectStack); if (!values) { return undefined; } - var layoutOptions = /** @type {ol.LayoutOptions} */ ({}); - var coordinates = appendCoordinate([], layoutOptions, node, values); - var layout = GPX.applyLayoutOptions_(layoutOptions, coordinates); - var geometry = new Point(coordinates, layout); + const layoutOptions = /** @type {ol.LayoutOptions} */ ({}); + const coordinates = appendCoordinate([], layoutOptions, node, values); + const layout = GPX.applyLayoutOptions_(layoutOptions, coordinates); + const geometry = new Point(coordinates, layout); transformWithOptions(geometry, false, options); - var feature = new Feature(geometry); + const feature = new Feature(geometry); feature.setProperties(values); return feature; } @@ -610,10 +610,10 @@ GPX.prototype.handleReadExtensions_ = function(features) { if (!features) { features = []; } - for (var i = 0, ii = features.length; i < ii; ++i) { - var feature = features[i]; + for (let i = 0, ii = features.length; i < ii; ++i) { + const feature = features[i]; if (this.readExtensions_) { - var extensionsNode = feature.get('extensionsNode_') || null; + const extensionsNode = feature.get('extensionsNode_') || null; this.readExtensions_(feature, extensionsNode); } feature.set('extensionsNode_', undefined); @@ -642,11 +642,11 @@ GPX.prototype.readFeatureFromNode = function(node, opt_options) { if (!includes(NAMESPACE_URIS, node.namespaceURI)) { return null; } - var featureReader = FEATURE_READER[node.localName]; + const featureReader = FEATURE_READER[node.localName]; if (!featureReader) { return null; } - var feature = featureReader(node, [this.getReadOptions(node, opt_options)]); + const feature = featureReader(node, [this.getReadOptions(node, opt_options)]); if (!feature) { return null; } @@ -678,8 +678,8 @@ GPX.prototype.readFeaturesFromNode = function(node, opt_options) { } if (node.localName == 'gpx') { /** @type {Array.} */ - var features = _ol_xml_.pushParseAndPop([], GPX_PARSERS, - node, [this.getReadOptions(node, opt_options)]); + const features = _ol_xml_.pushParseAndPop([], GPX_PARSERS, + node, [this.getReadOptions(node, opt_options)]); if (features) { this.handleReadExtensions_(features); return features; @@ -709,15 +709,15 @@ GPX.prototype.readProjection; */ function writeLink(node, value, objectStack) { node.setAttribute('href', value); - var context = objectStack[objectStack.length - 1]; - var properties = context['properties']; - var link = [ + const context = objectStack[objectStack.length - 1]; + const properties = context['properties']; + const link = [ properties['linkText'], properties['linkType'] ]; _ol_xml_.pushSerializeAndPop(/** @type {ol.XmlNodeStackItem} */ ({node: node}), - LINK_SERIALIZERS, _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, - link, objectStack, LINK_SEQUENCE); + LINK_SERIALIZERS, _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, + link, objectStack, LINK_SEQUENCE); } @@ -727,14 +727,14 @@ function writeLink(node, value, objectStack) { * @param {Array.<*>} objectStack Object stack. */ function writeWptType(node, coordinate, objectStack) { - var context = objectStack[objectStack.length - 1]; - var parentNode = context.node; - var namespaceURI = parentNode.namespaceURI; - var properties = context['properties']; + const context = objectStack[objectStack.length - 1]; + const parentNode = context.node; + const namespaceURI = parentNode.namespaceURI; + const properties = context['properties']; //FIXME Projection handling _ol_xml_.setAttributeNS(node, null, 'lat', coordinate[1]); _ol_xml_.setAttributeNS(node, null, 'lon', coordinate[0]); - var geometryLayout = context['geometryLayout']; + const geometryLayout = context['geometryLayout']; switch (geometryLayout) { case GeometryLayout.XYZM: if (coordinate[3] !== 0) { @@ -754,14 +754,14 @@ function writeWptType(node, coordinate, objectStack) { default: // pass } - var orderedKeys = (node.nodeName == 'rtept') ? + const orderedKeys = (node.nodeName == 'rtept') ? RTEPT_TYPE_SEQUENCE[namespaceURI] : WPT_TYPE_SEQUENCE[namespaceURI]; - var values = _ol_xml_.makeSequence(properties, orderedKeys); + const values = _ol_xml_.makeSequence(properties, orderedKeys); _ol_xml_.pushSerializeAndPop(/** @type {ol.XmlNodeStackItem} */ - ({node: node, 'properties': properties}), - WPT_TYPE_SERIALIZERS, _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, - values, objectStack, orderedKeys); + ({node: node, 'properties': properties}), + WPT_TYPE_SERIALIZERS, _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, + values, objectStack, orderedKeys); } @@ -771,21 +771,21 @@ function writeWptType(node, coordinate, objectStack) { * @param {Array.<*>} objectStack Object stack. */ function writeRte(node, feature, objectStack) { - var options = /** @type {olx.format.WriteOptions} */ (objectStack[0]); - var properties = feature.getProperties(); - var context = {node: node, 'properties': properties}; - var geometry = feature.getGeometry(); + const options = /** @type {olx.format.WriteOptions} */ (objectStack[0]); + const properties = feature.getProperties(); + const context = {node: node, 'properties': properties}; + let geometry = feature.getGeometry(); if (geometry) { geometry = /** @type {ol.geom.LineString} */ (transformWithOptions(geometry, true, options)); context['geometryLayout'] = geometry.getLayout(); properties['rtept'] = geometry.getCoordinates(); } - var parentNode = objectStack[objectStack.length - 1].node; - var orderedKeys = RTE_SEQUENCE[parentNode.namespaceURI]; - var values = _ol_xml_.makeSequence(properties, orderedKeys); + const parentNode = objectStack[objectStack.length - 1].node; + const orderedKeys = RTE_SEQUENCE[parentNode.namespaceURI]; + const values = _ol_xml_.makeSequence(properties, orderedKeys); _ol_xml_.pushSerializeAndPop(context, - RTE_SERIALIZERS, _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, - values, objectStack, orderedKeys); + RTE_SERIALIZERS, _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, + values, objectStack, orderedKeys); } @@ -795,22 +795,22 @@ function writeRte(node, feature, objectStack) { * @param {Array.<*>} objectStack Object stack. */ function writeTrk(node, feature, objectStack) { - var options = /** @type {olx.format.WriteOptions} */ (objectStack[0]); - var properties = feature.getProperties(); + const options = /** @type {olx.format.WriteOptions} */ (objectStack[0]); + const properties = feature.getProperties(); /** @type {ol.XmlNodeStackItem} */ - var context = {node: node, 'properties': properties}; - var geometry = feature.getGeometry(); + const context = {node: node, 'properties': properties}; + let geometry = feature.getGeometry(); if (geometry) { geometry = /** @type {ol.geom.MultiLineString} */ (transformWithOptions(geometry, true, options)); properties['trkseg'] = geometry.getLineStrings(); } - var parentNode = objectStack[objectStack.length - 1].node; - var orderedKeys = TRK_SEQUENCE[parentNode.namespaceURI]; - var values = _ol_xml_.makeSequence(properties, orderedKeys); + const parentNode = objectStack[objectStack.length - 1].node; + const orderedKeys = TRK_SEQUENCE[parentNode.namespaceURI]; + const values = _ol_xml_.makeSequence(properties, orderedKeys); _ol_xml_.pushSerializeAndPop(context, - TRK_SERIALIZERS, _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, - values, objectStack, orderedKeys); + TRK_SERIALIZERS, _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, + values, objectStack, orderedKeys); } @@ -821,11 +821,11 @@ function writeTrk(node, feature, objectStack) { */ function writeTrkSeg(node, lineString, objectStack) { /** @type {ol.XmlNodeStackItem} */ - var context = {node: node, 'geometryLayout': lineString.getLayout(), + const context = {node: node, 'geometryLayout': lineString.getLayout(), 'properties': {}}; _ol_xml_.pushSerializeAndPop(context, - TRKSEG_SERIALIZERS, TRKSEG_NODE_FACTORY, - lineString.getCoordinates(), objectStack); + TRKSEG_SERIALIZERS, TRKSEG_NODE_FACTORY, + lineString.getCoordinates(), objectStack); } @@ -835,10 +835,10 @@ function writeTrkSeg(node, lineString, objectStack) { * @param {Array.<*>} objectStack Object stack. */ function writeWpt(node, feature, objectStack) { - var options = /** @type {olx.format.WriteOptions} */ (objectStack[0]); - var context = objectStack[objectStack.length - 1]; + const options = /** @type {olx.format.WriteOptions} */ (objectStack[0]); + const context = objectStack[objectStack.length - 1]; context['properties'] = feature.getProperties(); - var geometry = feature.getGeometry(); + let geometry = feature.getGeometry(); if (geometry) { geometry = /** @type {ol.geom.Point} */ (transformWithOptions(geometry, true, options)); @@ -876,17 +876,17 @@ GPX.prototype.writeFeatures; GPX.prototype.writeFeaturesNode = function(features, opt_options) { opt_options = this.adaptOptions(opt_options); //FIXME Serialize metadata - var gpx = _ol_xml_.createElementNS('http://www.topografix.com/GPX/1/1', 'gpx'); - var xmlnsUri = 'http://www.w3.org/2000/xmlns/'; - var xmlSchemaInstanceUri = 'http://www.w3.org/2001/XMLSchema-instance'; + const gpx = _ol_xml_.createElementNS('http://www.topografix.com/GPX/1/1', 'gpx'); + const xmlnsUri = 'http://www.w3.org/2000/xmlns/'; + const xmlSchemaInstanceUri = 'http://www.w3.org/2001/XMLSchema-instance'; _ol_xml_.setAttributeNS(gpx, xmlnsUri, 'xmlns:xsi', xmlSchemaInstanceUri); _ol_xml_.setAttributeNS(gpx, xmlSchemaInstanceUri, 'xsi:schemaLocation', - SCHEMA_LOCATION); + SCHEMA_LOCATION); gpx.setAttribute('version', '1.1'); gpx.setAttribute('creator', 'OpenLayers'); _ol_xml_.pushSerializeAndPop(/** @type {ol.XmlNodeStackItem} */ - ({node: gpx}), GPX_SERIALIZERS, GPX_NODE_FACTORY, features, [opt_options]); + ({node: gpx}), GPX_SERIALIZERS, GPX_NODE_FACTORY, features, [opt_options]); return gpx; }; export default GPX; diff --git a/src/ol/format/GeoJSON.js b/src/ol/format/GeoJSON.js index fd2a73028f..9ed1e7aae6 100644 --- a/src/ol/format/GeoJSON.js +++ b/src/ol/format/GeoJSON.js @@ -28,9 +28,9 @@ import {get as getProjection} from '../proj.js'; * @param {olx.format.GeoJSONOptions=} opt_options Options. * @api */ -var GeoJSON = function(opt_options) { +const GeoJSON = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; JSONFeature.call(this); @@ -38,8 +38,8 @@ var GeoJSON = function(opt_options) { * @inheritDoc */ this.defaultDataProjection = getProjection( - options.defaultDataProjection ? - options.defaultDataProjection : 'EPSG:4326'); + options.defaultDataProjection ? + options.defaultDataProjection : 'EPSG:4326'); if (options.featureProjection) { @@ -69,7 +69,7 @@ inherits(GeoJSON, JSONFeature); * @const * @type {Object.} */ -var GEOMETRY_READERS = { +const GEOMETRY_READERS = { 'Point': readPointGeometry, 'LineString': readLineStringGeometry, 'Polygon': readPolygonGeometry, @@ -84,7 +84,7 @@ var GEOMETRY_READERS = { * @const * @type {Object.} */ -var GEOMETRY_WRITERS = { +const GEOMETRY_WRITERS = { 'Point': writePointGeometry, 'LineString': writeLineStringGeometry, 'Polygon': writePolygonGeometry, @@ -105,10 +105,10 @@ function readGeometry(object, opt_options) { if (!object) { return null; } - var geometryReader = GEOMETRY_READERS[object.type]; + const geometryReader = GEOMETRY_READERS[object.type]; return ( /** @type {ol.geom.Geometry} */ transformWithOptions( - geometryReader(object), false, opt_options) + geometryReader(object), false, opt_options) ); } @@ -119,14 +119,14 @@ function readGeometry(object, opt_options) { * @return {ol.geom.GeometryCollection} Geometry collection. */ function readGeometryCollectionGeometry(object, opt_options) { - var geometries = object.geometries.map( - /** + const geometries = object.geometries.map( + /** * @param {GeoJSONGeometry} geometry Geometry. * @return {ol.geom.Geometry} geometry Geometry. */ - function(geometry) { - return readGeometry(geometry, opt_options); - }); + function(geometry) { + return readGeometry(geometry, opt_options); + }); return new GeometryCollection(geometries); } @@ -191,7 +191,7 @@ function readPolygonGeometry(object) { * @return {GeoJSONGeometry|GeoJSONGeometryCollection} GeoJSON geometry. */ function writeGeometry(geometry, opt_options) { - var geometryWriter = GEOMETRY_WRITERS[geometry.getType()]; + const geometryWriter = GEOMETRY_WRITERS[geometry.getType()]; return geometryWriter(/** @type {ol.geom.Geometry} */ ( transformWithOptions(geometry, true, opt_options)), opt_options); } @@ -215,8 +215,8 @@ function writeEmptyGeometryCollectionGeometry(geometry) { * @return {GeoJSONGeometryCollection} GeoJSON geometry collection. */ function writeGeometryCollectionGeometry(geometry, opt_options) { - var geometries = geometry.getGeometriesArray().map(function(geometry) { - var options = _ol_obj_.assign({}, opt_options); + const geometries = geometry.getGeometriesArray().map(function(geometry) { + const options = _ol_obj_.assign({}, opt_options); delete options.featureProjection; return writeGeometry(geometry, options); }); @@ -272,7 +272,7 @@ function writeMultiPointGeometry(geometry, opt_options) { * @return {GeoJSONGeometry} GeoJSON geometry. */ function writeMultiPolygonGeometry(geometry, opt_options) { - var right; + let right; if (opt_options) { right = opt_options.rightHanded; } @@ -302,7 +302,7 @@ function writePointGeometry(geometry, opt_options) { * @return {GeoJSONGeometry} GeoJSON geometry. */ function writePolygonGeometry(geometry, opt_options) { - var right; + let right; if (opt_options) { right = opt_options.rightHanded; } @@ -349,7 +349,7 @@ GeoJSON.prototype.readFeatureFromObject = function(object, opt_options) { /** * @type {GeoJSONFeature} */ - var geoJSONFeature = null; + let geoJSONFeature = null; if (object.type === 'Feature') { geoJSONFeature = /** @type {GeoJSONFeature} */ (object); } else { @@ -359,8 +359,8 @@ GeoJSON.prototype.readFeatureFromObject = function(object, opt_options) { }); } - var geometry = readGeometry(geoJSONFeature.geometry, opt_options); - var feature = new Feature(); + const geometry = readGeometry(geoJSONFeature.geometry, opt_options); + const feature = new Feature(); if (this.geometryName_) { feature.setGeometryName(this.geometryName_); } else if (this.extractGeometryName_ && geoJSONFeature.geometry_name !== undefined) { @@ -381,18 +381,18 @@ GeoJSON.prototype.readFeatureFromObject = function(object, opt_options) { * @inheritDoc */ GeoJSON.prototype.readFeaturesFromObject = function(object, opt_options) { - var geoJSONObject = /** @type {GeoJSONObject} */ (object); + const geoJSONObject = /** @type {GeoJSONObject} */ (object); /** @type {Array.} */ - var features = null; + let features = null; if (geoJSONObject.type === 'FeatureCollection') { - var geoJSONFeatureCollection = /** @type {GeoJSONFeatureCollection} */ + const geoJSONFeatureCollection = /** @type {GeoJSONFeatureCollection} */ (object); features = []; - var geoJSONFeatures = geoJSONFeatureCollection.features; - var i, ii; + const geoJSONFeatures = geoJSONFeatureCollection.features; + let i, ii; for (i = 0, ii = geoJSONFeatures.length; i < ii; ++i) { features.push(this.readFeatureFromObject(geoJSONFeatures[i], - opt_options)); + opt_options)); } } else { features = [this.readFeatureFromObject(object, opt_options)]; @@ -436,9 +436,9 @@ GeoJSON.prototype.readProjection; * @inheritDoc */ GeoJSON.prototype.readProjectionFromObject = function(object) { - var geoJSONObject = /** @type {GeoJSONObject} */ (object); - var crs = geoJSONObject.crs; - var projection; + const geoJSONObject = /** @type {GeoJSONObject} */ (object); + const crs = geoJSONObject.crs; + let projection; if (crs) { if (crs.type == 'name') { projection = getProjection(crs.properties.name); @@ -477,20 +477,20 @@ GeoJSON.prototype.writeFeature; GeoJSON.prototype.writeFeatureObject = function(feature, opt_options) { opt_options = this.adaptOptions(opt_options); - var object = /** @type {GeoJSONFeature} */ ({ + const object = /** @type {GeoJSONFeature} */ ({ 'type': 'Feature' }); - var id = feature.getId(); + const id = feature.getId(); if (id !== undefined) { object.id = id; } - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); if (geometry) { object.geometry = writeGeometry(geometry, opt_options); } else { object.geometry = null; } - var properties = feature.getProperties(); + const properties = feature.getProperties(); delete properties[feature.getGeometryName()]; if (!_ol_obj_.isEmpty(properties)) { object.properties = properties; @@ -524,8 +524,8 @@ GeoJSON.prototype.writeFeatures; */ GeoJSON.prototype.writeFeaturesObject = function(features, opt_options) { opt_options = this.adaptOptions(opt_options); - var objects = []; - var i, ii; + const objects = []; + let i, ii; for (i = 0, ii = features.length; i < ii; ++i) { objects.push(this.writeFeatureObject(features[i], opt_options)); } diff --git a/src/ol/format/IGC.js b/src/ol/format/IGC.js index 8a6f1bb542..04174e8f9c 100644 --- a/src/ol/format/IGC.js +++ b/src/ol/format/IGC.js @@ -13,7 +13,7 @@ import {get as getProjection} from '../proj.js'; * IGC altitude/z. One of 'barometric', 'gps', 'none'. * @enum {string} */ -var IGCZ = { +const IGCZ = { BAROMETRIC: 'barometric', GPS: 'gps', NONE: 'none' @@ -28,9 +28,9 @@ var IGCZ = { * @param {olx.format.IGCOptions=} opt_options Options. * @api */ -var IGC = function(opt_options) { +const IGC = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; TextFeature.call(this); @@ -53,7 +53,7 @@ inherits(IGC, TextFeature); * @const * @type {RegExp} */ -var B_RECORD_RE = +const B_RECORD_RE = /^B(\d{2})(\d{2})(\d{2})(\d{2})(\d{5})([NS])(\d{3})(\d{5})([EW])([AV])(\d{5})(\d{5})/; @@ -61,14 +61,14 @@ var B_RECORD_RE = * @const * @type {RegExp} */ -var H_RECORD_RE = /^H.([A-Z]{3}).*?:(.*)/; +const H_RECORD_RE = /^H.([A-Z]{3}).*?:(.*)/; /** * @const * @type {RegExp} */ -var HFDTE_RECORD_RE = /^HFDTE(\d{2})(\d{2})(\d{2})/; +const HFDTE_RECORD_RE = /^HFDTE(\d{2})(\d{2})(\d{2})/; /** @@ -77,7 +77,7 @@ var HFDTE_RECORD_RE = /^HFDTE(\d{2})(\d{2})(\d{2})/; * @const * @type {RegExp} */ -var NEWLINE_RE = /\r\n|\r|\n/; +const NEWLINE_RE = /\r\n|\r|\n/; /** @@ -96,36 +96,36 @@ IGC.prototype.readFeature; * @inheritDoc */ IGC.prototype.readFeatureFromText = function(text, opt_options) { - var altitudeMode = this.altitudeMode_; - var lines = text.split(NEWLINE_RE); + const altitudeMode = this.altitudeMode_; + const lines = text.split(NEWLINE_RE); /** @type {Object.} */ - var properties = {}; - var flatCoordinates = []; - var year = 2000; - var month = 0; - var day = 1; - var lastDateTime = -1; - var i, ii; + const properties = {}; + const flatCoordinates = []; + let year = 2000; + let month = 0; + let day = 1; + let lastDateTime = -1; + let i, ii; for (i = 0, ii = lines.length; i < ii; ++i) { - var line = lines[i]; - var m; + const line = lines[i]; + let m; if (line.charAt(0) == 'B') { m = B_RECORD_RE.exec(line); if (m) { - var hour = parseInt(m[1], 10); - var minute = parseInt(m[2], 10); - var second = parseInt(m[3], 10); - var y = parseInt(m[4], 10) + parseInt(m[5], 10) / 60000; + const hour = parseInt(m[1], 10); + const minute = parseInt(m[2], 10); + const second = parseInt(m[3], 10); + let y = parseInt(m[4], 10) + parseInt(m[5], 10) / 60000; if (m[6] == 'S') { y = -y; } - var x = parseInt(m[7], 10) + parseInt(m[8], 10) / 60000; + let x = parseInt(m[7], 10) + parseInt(m[8], 10) / 60000; if (m[9] == 'W') { x = -x; } flatCoordinates.push(x, y); if (altitudeMode != IGCZ.NONE) { - var z; + let z; if (altitudeMode == IGCZ.GPS) { z = parseInt(m[11], 10); } else if (altitudeMode == IGCZ.BAROMETRIC) { @@ -135,7 +135,7 @@ IGC.prototype.readFeatureFromText = function(text, opt_options) { } flatCoordinates.push(z); } - var dateTime = Date.UTC(year, month, day, hour, minute, second); + let dateTime = Date.UTC(year, month, day, hour, minute, second); // Detect UTC midnight wrap around. if (dateTime < lastDateTime) { dateTime = Date.UTC(year, month, day + 1, hour, minute, second); @@ -160,10 +160,10 @@ IGC.prototype.readFeatureFromText = function(text, opt_options) { if (flatCoordinates.length === 0) { return null; } - var lineString = new LineString(null); - var layout = altitudeMode == IGCZ.NONE ? GeometryLayout.XYM : GeometryLayout.XYZM; + const lineString = new LineString(null); + const layout = altitudeMode == IGCZ.NONE ? GeometryLayout.XYM : GeometryLayout.XYZM; lineString.setFlatCoordinates(layout, flatCoordinates); - var feature = new Feature(transformWithOptions(lineString, false, opt_options)); + const feature = new Feature(transformWithOptions(lineString, false, opt_options)); feature.setProperties(properties); return feature; }; @@ -186,7 +186,7 @@ IGC.prototype.readFeatures; * @inheritDoc */ IGC.prototype.readFeaturesFromText = function(text, opt_options) { - var feature = this.readFeatureFromText(text, opt_options); + const feature = this.readFeatureFromText(text, opt_options); if (feature) { return [feature]; } else { diff --git a/src/ol/format/JSONFeature.js b/src/ol/format/JSONFeature.js index 8f61b8ea6d..a51a1d923e 100644 --- a/src/ol/format/JSONFeature.js +++ b/src/ol/format/JSONFeature.js @@ -15,7 +15,7 @@ import FormatType from '../format/FormatType.js'; * @abstract * @extends {ol.format.Feature} */ -var JSONFeature = function() { +const JSONFeature = function() { FeatureFormat.call(this); }; @@ -28,7 +28,7 @@ inherits(JSONFeature, FeatureFormat); */ function getObject(source) { if (typeof source === 'string') { - var object = JSON.parse(source); + const object = JSON.parse(source); return object ? /** @type {Object} */ (object) : null; } else if (source !== null) { return source; @@ -51,7 +51,7 @@ JSONFeature.prototype.getType = function() { */ JSONFeature.prototype.readFeature = function(source, opt_options) { return this.readFeatureFromObject( - getObject(source), this.getReadOptions(source, opt_options)); + getObject(source), this.getReadOptions(source, opt_options)); }; @@ -60,7 +60,7 @@ JSONFeature.prototype.readFeature = function(source, opt_options) { */ JSONFeature.prototype.readFeatures = function(source, opt_options) { return this.readFeaturesFromObject( - getObject(source), this.getReadOptions(source, opt_options)); + getObject(source), this.getReadOptions(source, opt_options)); }; @@ -89,7 +89,7 @@ JSONFeature.prototype.readFeaturesFromObject = function(object, opt_options) {}; */ JSONFeature.prototype.readGeometry = function(source, opt_options) { return this.readGeometryFromObject( - getObject(source), this.getReadOptions(source, opt_options)); + getObject(source), this.getReadOptions(source, opt_options)); }; diff --git a/src/ol/format/KML.js b/src/ol/format/KML.js index 95c0831a29..acec8cca99 100644 --- a/src/ol/format/KML.js +++ b/src/ol/format/KML.js @@ -41,9 +41,9 @@ import _ol_xml_ from '../xml.js'; * @param {olx.format.KMLOptions=} opt_options Options. * @api */ -var KML = function(opt_options) { +const KML = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; XMLFeature.call(this); @@ -291,16 +291,16 @@ KML.ICON_ANCHOR_UNITS_MAP_ = { * @private */ KML.createNameStyleFunction_ = function(foundStyle, name) { - var textStyle = null; - var textOffset = [0, 0]; - var textAlign = 'start'; + let textStyle = null; + const textOffset = [0, 0]; + let textAlign = 'start'; if (foundStyle.getImage()) { - var imageSize = foundStyle.getImage().getImageSize(); + let imageSize = foundStyle.getImage().getImageSize(); if (imageSize === null) { imageSize = KML.DEFAULT_IMAGE_STYLE_SIZE_; } if (imageSize.length == 2) { - var imageScale = foundStyle.getImage().getScale(); + const imageScale = foundStyle.getImage().getScale(); // Offset the label to be centered to the right of the icon, if there is // one. textOffset[0] = imageScale * imageSize[0] / 2; @@ -311,7 +311,7 @@ KML.createNameStyleFunction_ = function(foundStyle, name) { if (foundStyle.getText() !== null) { // clone the text style, customizing it with name, alignments and offset. // Note that kml does not support many text options that OpenLayers does (rotation, textBaseline). - var foundText = foundStyle.getText(); + const foundText = foundStyle.getText(); textStyle = foundText.clone(); textStyle.setFont(foundText.getFont() || KML.DEFAULT_TEXT_STYLE_.getFont()); textStyle.setScale(foundText.getScale() || KML.DEFAULT_TEXT_STYLE_.getScale()); @@ -325,7 +325,7 @@ KML.createNameStyleFunction_ = function(foundStyle, name) { textStyle.setOffsetY(textOffset[1]); textStyle.setTextAlign(textAlign); - var nameStyle = new Style({ + const nameStyle = new Style({ text: textStyle }); return nameStyle; @@ -344,7 +344,7 @@ KML.createNameStyleFunction_ = function(foundStyle, name) { * @private */ KML.createFeatureStyleFunction_ = function(style, styleUrl, - defaultStyle, sharedStyles, showPointNames) { + defaultStyle, sharedStyles, showPointNames) { return ( /** @@ -353,10 +353,10 @@ KML.createFeatureStyleFunction_ = function(style, styleUrl, * @this {ol.Feature} */ function(resolution) { - var drawName = showPointNames; + let drawName = showPointNames; /** @type {ol.style.Style|undefined} */ - var nameStyle; - var name = ''; + let nameStyle; + let name = ''; if (drawName) { if (this.getGeometry()) { drawName = (this.getGeometry().getType() === @@ -372,24 +372,24 @@ KML.createFeatureStyleFunction_ = function(style, styleUrl, if (style) { if (drawName) { nameStyle = KML.createNameStyleFunction_(style[0], - name); + name); return style.concat(nameStyle); } return style; } if (styleUrl) { - var foundStyle = KML.findStyle_(styleUrl, defaultStyle, - sharedStyles); + const foundStyle = KML.findStyle_(styleUrl, defaultStyle, + sharedStyles); if (drawName) { nameStyle = KML.createNameStyleFunction_(foundStyle[0], - name); + name); return foundStyle.concat(nameStyle); } return foundStyle; } if (drawName) { nameStyle = KML.createNameStyleFunction_(defaultStyle[0], - name); + name); return defaultStyle.concat(nameStyle); } return defaultStyle; @@ -417,7 +417,7 @@ KML.findStyle_ = function(styleValue, defaultStyle, sharedStyles) { styleValue = '#' + styleValue; } return KML.findStyle_( - sharedStyles[styleValue], defaultStyle, sharedStyles); + sharedStyles[styleValue], defaultStyle, sharedStyles); } else { return defaultStyle; } @@ -430,12 +430,12 @@ KML.findStyle_ = function(styleValue, defaultStyle, sharedStyles) { * @return {ol.Color|undefined} Color. */ KML.readColor_ = function(node) { - var s = _ol_xml_.getAllTextContent(node, false); + const s = _ol_xml_.getAllTextContent(node, false); // The KML specification states that colors should not include a leading `#` // but we tolerate them. - var m = /^\s*#?\s*([0-9A-Fa-f]{8})\s*$/.exec(s); + const m = /^\s*#?\s*([0-9A-Fa-f]{8})\s*$/.exec(s); if (m) { - var hexColor = m[1]; + const hexColor = m[1]; return [ parseInt(hexColor.substr(6, 2), 16), parseInt(hexColor.substr(4, 2), 16), @@ -455,17 +455,17 @@ KML.readColor_ = function(node) { * @return {Array.|undefined} Flat coordinates. */ KML.readFlatCoordinates_ = function(node) { - var s = _ol_xml_.getAllTextContent(node, false); - var flatCoordinates = []; + let s = _ol_xml_.getAllTextContent(node, false); + const flatCoordinates = []; // The KML specification states that coordinate tuples should not include // spaces, but we tolerate them. - var re = + const re = /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*,\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)(?:\s*,\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?))?\s*/i; - var m; + let m; while ((m = re.exec(s))) { - var x = parseFloat(m[1]); - var y = parseFloat(m[2]); - var z = m[3] ? parseFloat(m[3]) : 0; + const x = parseFloat(m[1]); + const y = parseFloat(m[2]); + const z = m[3] ? parseFloat(m[3]) : 0; flatCoordinates.push(x, y, z); s = s.substr(m[0].length); } @@ -482,13 +482,13 @@ KML.readFlatCoordinates_ = function(node) { * @return {string} URI. */ KML.readURI_ = function(node) { - var s = _ol_xml_.getAllTextContent(node, false).trim(); - var baseURI = node.baseURI; + const s = _ol_xml_.getAllTextContent(node, false).trim(); + let baseURI = node.baseURI; if (!baseURI || baseURI == 'about:blank') { baseURI = window.location.href; } if (baseURI) { - var url = new URL(s, baseURI); + const url = new URL(s, baseURI); return url.href; } else { return s; @@ -502,9 +502,9 @@ KML.readURI_ = function(node) { * @return {ol.KMLVec2_} Vec2. */ KML.readVec2_ = function(node) { - var xunits = node.getAttribute('xunits'); - var yunits = node.getAttribute('yunits'); - var origin; + const xunits = node.getAttribute('xunits'); + const yunits = node.getAttribute('yunits'); + let origin; if (xunits !== 'insetPixels') { if (yunits !== 'insetPixels') { origin = IconOrigin.BOTTOM_LEFT; @@ -546,7 +546,7 @@ KML.readScale_ = function(node) { */ KML.readStyleMapValue_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop(undefined, - KML.STYLE_MAP_PARSERS_, node, objectStack); + KML.STYLE_MAP_PARSERS_, node, objectStack); }; /** * @param {Node} node Node. @@ -560,25 +560,25 @@ KML.IconStyleParser_ = function(node, objectStack) { // FIXME viewBoundScale // FIXME viewFormat // FIXME httpQuery - var object = _ol_xml_.pushParseAndPop( - {}, KML.ICON_STYLE_PARSERS_, node, objectStack); + const object = _ol_xml_.pushParseAndPop( + {}, KML.ICON_STYLE_PARSERS_, node, objectStack); if (!object) { return; } - var styleObject = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var IconObject = 'Icon' in object ? object['Icon'] : {}; - var drawIcon = (!('Icon' in object) || Object.keys(IconObject).length > 0); - var src; - var href = /** @type {string|undefined} */ + const styleObject = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const IconObject = 'Icon' in object ? object['Icon'] : {}; + const drawIcon = (!('Icon' in object) || Object.keys(IconObject).length > 0); + let src; + const href = /** @type {string|undefined} */ (IconObject['href']); if (href) { src = href; } else if (drawIcon) { src = KML.DEFAULT_IMAGE_STYLE_SRC_; } - var anchor, anchorXUnits, anchorYUnits; - var anchorOrigin = IconOrigin.BOTTOM_LEFT; - var hotSpot = /** @type {ol.KMLVec2_|undefined} */ + let anchor, anchorXUnits, anchorYUnits; + let anchorOrigin = IconOrigin.BOTTOM_LEFT; + const hotSpot = /** @type {ol.KMLVec2_|undefined} */ (object['hotSpot']); if (hotSpot) { anchor = [hotSpot.x, hotSpot.y]; @@ -595,32 +595,32 @@ KML.IconStyleParser_ = function(node, objectStack) { anchorYUnits = IconAnchorUnits.FRACTION; } - var offset; - var x = /** @type {number|undefined} */ + let offset; + const x = /** @type {number|undefined} */ (IconObject['x']); - var y = /** @type {number|undefined} */ + const y = /** @type {number|undefined} */ (IconObject['y']); if (x !== undefined && y !== undefined) { offset = [x, y]; } - var size; - var w = /** @type {number|undefined} */ + let size; + const w = /** @type {number|undefined} */ (IconObject['w']); - var h = /** @type {number|undefined} */ + const h = /** @type {number|undefined} */ (IconObject['h']); if (w !== undefined && h !== undefined) { size = [w, h]; } - var rotation; - var heading = /** @type {number} */ + let rotation; + const heading = /** @type {number} */ (object['heading']); if (heading !== undefined) { rotation = toRadians(heading); } - var scale = /** @type {number|undefined} */ + let scale = /** @type {number|undefined} */ (object['scale']); if (drawIcon) { @@ -631,7 +631,7 @@ KML.IconStyleParser_ = function(node, objectStack) { } } - var imageStyle = new Icon({ + const imageStyle = new Icon({ anchor: anchor, anchorOrigin: anchorOrigin, anchorXUnits: anchorXUnits, @@ -659,13 +659,13 @@ KML.IconStyleParser_ = function(node, objectStack) { */ KML.LabelStyleParser_ = function(node, objectStack) { // FIXME colorMode - var object = _ol_xml_.pushParseAndPop( - {}, KML.LABEL_STYLE_PARSERS_, node, objectStack); + const object = _ol_xml_.pushParseAndPop( + {}, KML.LABEL_STYLE_PARSERS_, node, objectStack); if (!object) { return; } - var styleObject = objectStack[objectStack.length - 1]; - var textStyle = new Text({ + const styleObject = objectStack[objectStack.length - 1]; + const textStyle = new Text({ fill: new Fill({ color: /** @type {ol.Color} */ ('color' in object ? object['color'] : KML.DEFAULT_COLOR_) @@ -688,13 +688,13 @@ KML.LineStyleParser_ = function(node, objectStack) { // FIXME gx:outerWidth // FIXME gx:physicalWidth // FIXME gx:labelVisibility - var object = _ol_xml_.pushParseAndPop( - {}, KML.LINE_STYLE_PARSERS_, node, objectStack); + const object = _ol_xml_.pushParseAndPop( + {}, KML.LINE_STYLE_PARSERS_, node, objectStack); if (!object) { return; } - var styleObject = objectStack[objectStack.length - 1]; - var strokeStyle = new Stroke({ + const styleObject = objectStack[objectStack.length - 1]; + const strokeStyle = new Stroke({ color: /** @type {ol.Color} */ ('color' in object ? object['color'] : KML.DEFAULT_COLOR_), width: /** @type {number} */ ('width' in object ? object['width'] : 1) @@ -710,22 +710,22 @@ KML.LineStyleParser_ = function(node, objectStack) { */ KML.PolyStyleParser_ = function(node, objectStack) { // FIXME colorMode - var object = _ol_xml_.pushParseAndPop( - {}, KML.POLY_STYLE_PARSERS_, node, objectStack); + const object = _ol_xml_.pushParseAndPop( + {}, KML.POLY_STYLE_PARSERS_, node, objectStack); if (!object) { return; } - var styleObject = objectStack[objectStack.length - 1]; - var fillStyle = new Fill({ + const styleObject = objectStack[objectStack.length - 1]; + const fillStyle = new Fill({ color: /** @type {ol.Color} */ ('color' in object ? object['color'] : KML.DEFAULT_COLOR_) }); styleObject['fillStyle'] = fillStyle; - var fill = /** @type {boolean|undefined} */ (object['fill']); + const fill = /** @type {boolean|undefined} */ (object['fill']); if (fill !== undefined) { styleObject['fill'] = fill; } - var outline = + const outline = /** @type {boolean|undefined} */ (object['outline']); if (outline !== undefined) { styleObject['outline'] = outline; @@ -741,7 +741,7 @@ KML.PolyStyleParser_ = function(node, objectStack) { */ KML.readFlatLinearRing_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop(null, - KML.FLAT_LINEAR_RING_PARSERS_, node, objectStack); + KML.FLAT_LINEAR_RING_PARSERS_, node, objectStack); }; @@ -751,17 +751,17 @@ KML.readFlatLinearRing_ = function(node, objectStack) { * @private */ KML.gxCoordParser_ = function(node, objectStack) { - var gxTrackObject = /** @type {ol.KMLGxTrackObject_} */ + const gxTrackObject = /** @type {ol.KMLGxTrackObject_} */ (objectStack[objectStack.length - 1]); - var flatCoordinates = gxTrackObject.flatCoordinates; - var s = _ol_xml_.getAllTextContent(node, false); - var re = + const flatCoordinates = gxTrackObject.flatCoordinates; + const s = _ol_xml_.getAllTextContent(node, false); + const re = /^\s*([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s+([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s+([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s*$/i; - var m = re.exec(s); + const m = re.exec(s); if (m) { - var x = parseFloat(m[1]); - var y = parseFloat(m[2]); - var z = parseFloat(m[3]); + const x = parseFloat(m[1]); + const y = parseFloat(m[2]); + const z = parseFloat(m[3]); flatCoordinates.push(x, y, z, 0); } else { flatCoordinates.push(0, 0, 0, 0); @@ -776,12 +776,12 @@ KML.gxCoordParser_ = function(node, objectStack) { * @return {ol.geom.MultiLineString|undefined} MultiLineString. */ KML.readGxMultiTrack_ = function(node, objectStack) { - var lineStrings = _ol_xml_.pushParseAndPop([], - KML.GX_MULTITRACK_GEOMETRY_PARSERS_, node, objectStack); + const lineStrings = _ol_xml_.pushParseAndPop([], + KML.GX_MULTITRACK_GEOMETRY_PARSERS_, node, objectStack); if (!lineStrings) { return undefined; } - var multiLineString = new MultiLineString(null); + const multiLineString = new MultiLineString(null); multiLineString.setLineStrings(lineStrings); return multiLineString; }; @@ -794,22 +794,22 @@ KML.readGxMultiTrack_ = function(node, objectStack) { * @return {ol.geom.LineString|undefined} LineString. */ KML.readGxTrack_ = function(node, objectStack) { - var gxTrackObject = _ol_xml_.pushParseAndPop( - /** @type {ol.KMLGxTrackObject_} */ ({ - flatCoordinates: [], - whens: [] - }), KML.GX_TRACK_PARSERS_, node, objectStack); + const gxTrackObject = _ol_xml_.pushParseAndPop( + /** @type {ol.KMLGxTrackObject_} */ ({ + flatCoordinates: [], + whens: [] + }), KML.GX_TRACK_PARSERS_, node, objectStack); if (!gxTrackObject) { return undefined; } - var flatCoordinates = gxTrackObject.flatCoordinates; - var whens = gxTrackObject.whens; - var i, ii; + const flatCoordinates = gxTrackObject.flatCoordinates; + const whens = gxTrackObject.whens; + let i, ii; for (i = 0, ii = Math.min(flatCoordinates.length, whens.length); i < ii; ++i) { flatCoordinates[4 * i + 3] = whens[i]; } - var lineString = new LineString(null); + const lineString = new LineString(null); lineString.setFlatCoordinates(GeometryLayout.XYZM, flatCoordinates); return lineString; }; @@ -822,8 +822,8 @@ KML.readGxTrack_ = function(node, objectStack) { * @return {Object} Icon object. */ KML.readIcon_ = function(node, objectStack) { - var iconObject = _ol_xml_.pushParseAndPop( - {}, KML.ICON_PARSERS_, node, objectStack); + const iconObject = _ol_xml_.pushParseAndPop( + {}, KML.ICON_PARSERS_, node, objectStack); if (iconObject) { return iconObject; } else { @@ -840,7 +840,7 @@ KML.readIcon_ = function(node, objectStack) { */ KML.readFlatCoordinatesFromNode_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop(null, - KML.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, objectStack); + KML.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, objectStack); }; @@ -851,13 +851,13 @@ KML.readFlatCoordinatesFromNode_ = function(node, objectStack) { * @return {ol.geom.LineString|undefined} LineString. */ KML.readLineString_ = function(node, objectStack) { - var properties = _ol_xml_.pushParseAndPop({}, - KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node, - objectStack); - var flatCoordinates = + const properties = _ol_xml_.pushParseAndPop({}, + KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node, + objectStack); + const flatCoordinates = KML.readFlatCoordinatesFromNode_(node, objectStack); if (flatCoordinates) { - var lineString = new LineString(null); + const lineString = new LineString(null); lineString.setFlatCoordinates(GeometryLayout.XYZ, flatCoordinates); lineString.setProperties(properties); return lineString; @@ -874,15 +874,15 @@ KML.readLineString_ = function(node, objectStack) { * @return {ol.geom.Polygon|undefined} Polygon. */ KML.readLinearRing_ = function(node, objectStack) { - var properties = _ol_xml_.pushParseAndPop({}, - KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node, - objectStack); - var flatCoordinates = + const properties = _ol_xml_.pushParseAndPop({}, + KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node, + objectStack); + const flatCoordinates = KML.readFlatCoordinatesFromNode_(node, objectStack); if (flatCoordinates) { - var polygon = new Polygon(null); + const polygon = new Polygon(null); polygon.setFlatCoordinates(GeometryLayout.XYZ, flatCoordinates, - [flatCoordinates.length]); + [flatCoordinates.length]); polygon.setProperties(properties); return polygon; } else { @@ -898,8 +898,8 @@ KML.readLinearRing_ = function(node, objectStack) { * @return {ol.geom.Geometry} Geometry. */ KML.readMultiGeometry_ = function(node, objectStack) { - var geometries = _ol_xml_.pushParseAndPop([], - KML.MULTI_GEOMETRY_PARSERS_, node, objectStack); + const geometries = _ol_xml_.pushParseAndPop([], + KML.MULTI_GEOMETRY_PARSERS_, node, objectStack); if (!geometries) { return null; } @@ -907,10 +907,10 @@ KML.readMultiGeometry_ = function(node, objectStack) { return new GeometryCollection(geometries); } /** @type {ol.geom.Geometry} */ - var multiGeometry; - var homogeneous = true; - var type = geometries[0].getType(); - var geometry, i, ii; + let multiGeometry; + let homogeneous = true; + const type = geometries[0].getType(); + let geometry, i, ii; for (i = 1, ii = geometries.length; i < ii; ++i) { geometry = geometries[i]; if (geometry.getType() != type) { @@ -919,10 +919,10 @@ KML.readMultiGeometry_ = function(node, objectStack) { } } if (homogeneous) { - var layout; - var flatCoordinates; + let layout; + let flatCoordinates; if (type == GeometryType.POINT) { - var point = geometries[0]; + const point = geometries[0]; layout = point.getLayout(); flatCoordinates = point.getFlatCoordinates(); for (i = 1, ii = geometries.length; i < ii; ++i) { @@ -959,13 +959,13 @@ KML.readMultiGeometry_ = function(node, objectStack) { * @return {ol.geom.Point|undefined} Point. */ KML.readPoint_ = function(node, objectStack) { - var properties = _ol_xml_.pushParseAndPop({}, - KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node, - objectStack); - var flatCoordinates = + const properties = _ol_xml_.pushParseAndPop({}, + KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node, + objectStack); + const flatCoordinates = KML.readFlatCoordinatesFromNode_(node, objectStack); if (flatCoordinates) { - var point = new Point(null); + const point = new Point(null); point.setFlatCoordinates(GeometryLayout.XYZ, flatCoordinates); point.setProperties(properties); return point; @@ -982,22 +982,22 @@ KML.readPoint_ = function(node, objectStack) { * @return {ol.geom.Polygon|undefined} Polygon. */ KML.readPolygon_ = function(node, objectStack) { - var properties = _ol_xml_.pushParseAndPop(/** @type {Object} */ ({}), - KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node, - objectStack); - var flatLinearRings = _ol_xml_.pushParseAndPop([null], - KML.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack); + const properties = _ol_xml_.pushParseAndPop(/** @type {Object} */ ({}), + KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node, + objectStack); + const flatLinearRings = _ol_xml_.pushParseAndPop([null], + KML.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack); if (flatLinearRings && flatLinearRings[0]) { - var polygon = new Polygon(null); - var flatCoordinates = flatLinearRings[0]; - var ends = [flatCoordinates.length]; - var i, ii; + const polygon = new Polygon(null); + const flatCoordinates = flatLinearRings[0]; + const ends = [flatCoordinates.length]; + let i, ii; for (i = 1, ii = flatLinearRings.length; i < ii; ++i) { extend(flatCoordinates, flatLinearRings[i]); ends.push(flatCoordinates.length); } polygon.setFlatCoordinates( - GeometryLayout.XYZ, flatCoordinates, ends); + GeometryLayout.XYZ, flatCoordinates, ends); polygon.setProperties(properties); return polygon; } else { @@ -1013,31 +1013,31 @@ KML.readPolygon_ = function(node, objectStack) { * @return {Array.} Style. */ KML.readStyle_ = function(node, objectStack) { - var styleObject = _ol_xml_.pushParseAndPop( - {}, KML.STYLE_PARSERS_, node, objectStack); + const styleObject = _ol_xml_.pushParseAndPop( + {}, KML.STYLE_PARSERS_, node, objectStack); if (!styleObject) { return null; } - var fillStyle = /** @type {ol.style.Fill} */ + let fillStyle = /** @type {ol.style.Fill} */ ('fillStyle' in styleObject ? styleObject['fillStyle'] : KML.DEFAULT_FILL_STYLE_); - var fill = /** @type {boolean|undefined} */ (styleObject['fill']); + const fill = /** @type {boolean|undefined} */ (styleObject['fill']); if (fill !== undefined && !fill) { fillStyle = null; } - var imageStyle = /** @type {ol.style.Image} */ + let imageStyle = /** @type {ol.style.Image} */ ('imageStyle' in styleObject ? styleObject['imageStyle'] : KML.DEFAULT_IMAGE_STYLE_); if (imageStyle == KML.DEFAULT_NO_IMAGE_STYLE_) { imageStyle = undefined; } - var textStyle = /** @type {ol.style.Text} */ + const textStyle = /** @type {ol.style.Text} */ ('textStyle' in styleObject ? styleObject['textStyle'] : KML.DEFAULT_TEXT_STYLE_); - var strokeStyle = /** @type {ol.style.Stroke} */ + let strokeStyle = /** @type {ol.style.Stroke} */ ('strokeStyle' in styleObject ? styleObject['strokeStyle'] : KML.DEFAULT_STROKE_STYLE_); - var outline = /** @type {boolean|undefined} */ + const outline = /** @type {boolean|undefined} */ (styleObject['outline']); if (outline !== undefined && !outline) { strokeStyle = null; @@ -1061,12 +1061,12 @@ KML.readStyle_ = function(node, objectStack) { * @private */ KML.setCommonGeometryProperties_ = function(multiGeometry, - geometries) { - var ii = geometries.length; - var extrudes = new Array(geometries.length); - var tessellates = new Array(geometries.length); - var altitudeModes = new Array(geometries.length); - var geometry, i, hasExtrude, hasTessellate, hasAltitudeMode; + geometries) { + const ii = geometries.length; + const extrudes = new Array(geometries.length); + const tessellates = new Array(geometries.length); + const altitudeModes = new Array(geometries.length); + let geometry, i, hasExtrude, hasTessellate, hasAltitudeMode; hasExtrude = hasTessellate = hasAltitudeMode = false; for (i = 0; i < ii; ++i) { geometry = geometries[i]; @@ -1095,9 +1095,9 @@ KML.setCommonGeometryProperties_ = function(multiGeometry, * @private */ KML.DataParser_ = function(node, objectStack) { - var name = node.getAttribute('name'); + const name = node.getAttribute('name'); _ol_xml_.parseNode(KML.DATA_PARSERS_, node, objectStack); - var featureObject = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const featureObject = /** @type {Object} */ (objectStack[objectStack.length - 1]); if (name !== null) { featureObject[name] = featureObject.value; } else if (featureObject.displayName !== null) { @@ -1131,20 +1131,20 @@ KML.RegionParser_ = function(node, objectStack) { * @private */ KML.PairDataParser_ = function(node, objectStack) { - var pairObject = _ol_xml_.pushParseAndPop( - {}, KML.PAIR_PARSERS_, node, objectStack); + const pairObject = _ol_xml_.pushParseAndPop( + {}, KML.PAIR_PARSERS_, node, objectStack); if (!pairObject) { return; } - var key = /** @type {string|undefined} */ + const key = /** @type {string|undefined} */ (pairObject['key']); if (key && key == 'normal') { - var styleUrl = /** @type {string|undefined} */ + const styleUrl = /** @type {string|undefined} */ (pairObject['styleUrl']); if (styleUrl) { objectStack[objectStack.length - 1] = styleUrl; } - var Style = /** @type {ol.style.Style} */ + const Style = /** @type {ol.style.Style} */ (pairObject['Style']); if (Style) { objectStack[objectStack.length - 1] = Style; @@ -1159,11 +1159,11 @@ KML.PairDataParser_ = function(node, objectStack) { * @private */ KML.PlacemarkStyleMapParser_ = function(node, objectStack) { - var styleMapValue = KML.readStyleMapValue_(node, objectStack); + const styleMapValue = KML.readStyleMapValue_(node, objectStack); if (!styleMapValue) { return; } - var placemarkObject = objectStack[objectStack.length - 1]; + const placemarkObject = objectStack[objectStack.length - 1]; if (Array.isArray(styleMapValue)) { placemarkObject['Style'] = styleMapValue; } else if (typeof styleMapValue === 'string') { @@ -1190,10 +1190,10 @@ KML.SchemaDataParser_ = function(node, objectStack) { * @private */ KML.SimpleDataParser_ = function(node, objectStack) { - var name = node.getAttribute('name'); + const name = node.getAttribute('name'); if (name !== null) { - var data = XSD.readString(node); - var featureObject = + const data = XSD.readString(node); + const featureObject = /** @type {Object} */ (objectStack[objectStack.length - 1]); featureObject[name] = data; } @@ -1206,12 +1206,12 @@ KML.SimpleDataParser_ = function(node, objectStack) { * @private */ KML.LatLonAltBoxParser_ = function(node, objectStack) { - var object = _ol_xml_.pushParseAndPop({}, KML.LAT_LON_ALT_BOX_PARSERS_, node, objectStack); + const object = _ol_xml_.pushParseAndPop({}, KML.LAT_LON_ALT_BOX_PARSERS_, node, objectStack); if (!object) { return; } - var regionObject = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var extent = [ + const regionObject = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const extent = [ parseFloat(object['west']), parseFloat(object['south']), parseFloat(object['east']), @@ -1230,11 +1230,11 @@ KML.LatLonAltBoxParser_ = function(node, objectStack) { * @private */ KML.LodParser_ = function(node, objectStack) { - var object = _ol_xml_.pushParseAndPop({}, KML.LOD_PARSERS_, node, objectStack); + const object = _ol_xml_.pushParseAndPop({}, KML.LOD_PARSERS_, node, objectStack); if (!object) { return; } - var lodObject = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const lodObject = /** @type {Object} */ (objectStack[objectStack.length - 1]); lodObject['minLodPixels'] = parseFloat(object['minLodPixels']); lodObject['maxLodPixels'] = parseFloat(object['maxLodPixels']); lodObject['minFadeExtent'] = parseFloat(object['minFadeExtent']); @@ -1249,10 +1249,10 @@ KML.LodParser_ = function(node, objectStack) { */ KML.innerBoundaryIsParser_ = function(node, objectStack) { /** @type {Array.|undefined} */ - var flatLinearRing = _ol_xml_.pushParseAndPop(undefined, - KML.INNER_BOUNDARY_IS_PARSERS_, node, objectStack); + const flatLinearRing = _ol_xml_.pushParseAndPop(undefined, + KML.INNER_BOUNDARY_IS_PARSERS_, node, objectStack); if (flatLinearRing) { - var flatLinearRings = /** @type {Array.>} */ + const flatLinearRings = /** @type {Array.>} */ (objectStack[objectStack.length - 1]); flatLinearRings.push(flatLinearRing); } @@ -1266,10 +1266,10 @@ KML.innerBoundaryIsParser_ = function(node, objectStack) { */ KML.outerBoundaryIsParser_ = function(node, objectStack) { /** @type {Array.|undefined} */ - var flatLinearRing = _ol_xml_.pushParseAndPop(undefined, - KML.OUTER_BOUNDARY_IS_PARSERS_, node, objectStack); + const flatLinearRing = _ol_xml_.pushParseAndPop(undefined, + KML.OUTER_BOUNDARY_IS_PARSERS_, node, objectStack); if (flatLinearRing) { - var flatLinearRings = /** @type {Array.>} */ + const flatLinearRings = /** @type {Array.>} */ (objectStack[objectStack.length - 1]); flatLinearRings[0] = flatLinearRing; } @@ -1292,11 +1292,11 @@ KML.LinkParser_ = function(node, objectStack) { * @private */ KML.whenParser_ = function(node, objectStack) { - var gxTrackObject = /** @type {ol.KMLGxTrackObject_} */ + const gxTrackObject = /** @type {ol.KMLGxTrackObject_} */ (objectStack[objectStack.length - 1]); - var whens = gxTrackObject.whens; - var s = _ol_xml_.getAllTextContent(node, false); - var when = Date.parse(s); + const whens = gxTrackObject.whens; + const s = _ol_xml_.getAllTextContent(node, false); + const when = Date.parse(s); whens.push(isNaN(when) ? 0 : when); }; @@ -1307,10 +1307,10 @@ KML.whenParser_ = function(node, objectStack) { * @private */ KML.DATA_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'displayName': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'value': _ol_xml_.makeObjectPropertySetter(XSD.readString) - }); + KML.NAMESPACE_URIS_, { + 'displayName': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'value': _ol_xml_.makeObjectPropertySetter(XSD.readString) + }); /** @@ -1319,10 +1319,10 @@ KML.DATA_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.EXTENDED_DATA_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'Data': KML.DataParser_, - 'SchemaData': KML.SchemaDataParser_ - }); + KML.NAMESPACE_URIS_, { + 'Data': KML.DataParser_, + 'SchemaData': KML.SchemaDataParser_ + }); /** @@ -1331,10 +1331,10 @@ KML.EXTENDED_DATA_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.REGION_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'LatLonAltBox': KML.LatLonAltBoxParser_, - 'Lod': KML.LodParser_ - }); + KML.NAMESPACE_URIS_, { + 'LatLonAltBox': KML.LatLonAltBoxParser_, + 'Lod': KML.LodParser_ + }); /** @@ -1343,15 +1343,15 @@ KML.REGION_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.LAT_LON_ALT_BOX_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'altitudeMode': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'minAltitude': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'maxAltitude': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'north': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'south': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'east': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'west': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal) - }); + KML.NAMESPACE_URIS_, { + 'altitudeMode': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'minAltitude': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'maxAltitude': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'north': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'south': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'east': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'west': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal) + }); /** @@ -1360,12 +1360,12 @@ KML.LAT_LON_ALT_BOX_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.LOD_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'minLodPixels': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'maxLodPixels': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'minFadeExtent': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'maxFadeExtent': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal) - }); + KML.NAMESPACE_URIS_, { + 'minLodPixels': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'maxLodPixels': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'minFadeExtent': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'maxFadeExtent': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal) + }); /** @@ -1374,11 +1374,11 @@ KML.LOD_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'extrude': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean), - 'tessellate': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean), - 'altitudeMode': _ol_xml_.makeObjectPropertySetter(XSD.readString) - }); + KML.NAMESPACE_URIS_, { + 'extrude': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean), + 'tessellate': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean), + 'altitudeMode': _ol_xml_.makeObjectPropertySetter(XSD.readString) + }); /** @@ -1387,9 +1387,9 @@ KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.FLAT_LINEAR_RING_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'coordinates': _ol_xml_.makeReplacer(KML.readFlatCoordinates_) - }); + KML.NAMESPACE_URIS_, { + 'coordinates': _ol_xml_.makeReplacer(KML.readFlatCoordinates_) + }); /** @@ -1398,10 +1398,10 @@ KML.FLAT_LINEAR_RING_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.FLAT_LINEAR_RINGS_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'innerBoundaryIs': KML.innerBoundaryIsParser_, - 'outerBoundaryIs': KML.outerBoundaryIsParser_ - }); + KML.NAMESPACE_URIS_, { + 'innerBoundaryIs': KML.innerBoundaryIsParser_, + 'outerBoundaryIs': KML.outerBoundaryIsParser_ + }); /** @@ -1410,12 +1410,12 @@ KML.FLAT_LINEAR_RINGS_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.GX_TRACK_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'when': KML.whenParser_ - }, _ol_xml_.makeStructureNS( - KML.GX_NAMESPACE_URIS_, { - 'coord': KML.gxCoordParser_ - })); + KML.NAMESPACE_URIS_, { + 'when': KML.whenParser_ + }, _ol_xml_.makeStructureNS( + KML.GX_NAMESPACE_URIS_, { + 'coord': KML.gxCoordParser_ + })); /** @@ -1424,9 +1424,9 @@ KML.GX_TRACK_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.GEOMETRY_FLAT_COORDINATES_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'coordinates': _ol_xml_.makeReplacer(KML.readFlatCoordinates_) - }); + KML.NAMESPACE_URIS_, { + 'coordinates': _ol_xml_.makeReplacer(KML.readFlatCoordinates_) + }); /** @@ -1435,15 +1435,15 @@ KML.GEOMETRY_FLAT_COORDINATES_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.ICON_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'href': _ol_xml_.makeObjectPropertySetter(KML.readURI_) - }, _ol_xml_.makeStructureNS( - KML.GX_NAMESPACE_URIS_, { - 'x': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'y': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'w': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'h': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal) - })); + KML.NAMESPACE_URIS_, { + 'href': _ol_xml_.makeObjectPropertySetter(KML.readURI_) + }, _ol_xml_.makeStructureNS( + KML.GX_NAMESPACE_URIS_, { + 'x': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'y': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'w': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'h': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal) + })); /** @@ -1452,12 +1452,12 @@ KML.ICON_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.ICON_STYLE_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'Icon': _ol_xml_.makeObjectPropertySetter(KML.readIcon_), - 'heading': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), - 'hotSpot': _ol_xml_.makeObjectPropertySetter(KML.readVec2_), - 'scale': _ol_xml_.makeObjectPropertySetter(KML.readScale_) - }); + KML.NAMESPACE_URIS_, { + 'Icon': _ol_xml_.makeObjectPropertySetter(KML.readIcon_), + 'heading': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal), + 'hotSpot': _ol_xml_.makeObjectPropertySetter(KML.readVec2_), + 'scale': _ol_xml_.makeObjectPropertySetter(KML.readScale_) + }); /** @@ -1466,9 +1466,9 @@ KML.ICON_STYLE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.INNER_BOUNDARY_IS_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'LinearRing': _ol_xml_.makeReplacer(KML.readFlatLinearRing_) - }); + KML.NAMESPACE_URIS_, { + 'LinearRing': _ol_xml_.makeReplacer(KML.readFlatLinearRing_) + }); /** @@ -1477,10 +1477,10 @@ KML.INNER_BOUNDARY_IS_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.LABEL_STYLE_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'color': _ol_xml_.makeObjectPropertySetter(KML.readColor_), - 'scale': _ol_xml_.makeObjectPropertySetter(KML.readScale_) - }); + KML.NAMESPACE_URIS_, { + 'color': _ol_xml_.makeObjectPropertySetter(KML.readColor_), + 'scale': _ol_xml_.makeObjectPropertySetter(KML.readScale_) + }); /** @@ -1489,10 +1489,10 @@ KML.LABEL_STYLE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.LINE_STYLE_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'color': _ol_xml_.makeObjectPropertySetter(KML.readColor_), - 'width': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal) - }); + KML.NAMESPACE_URIS_, { + 'color': _ol_xml_.makeObjectPropertySetter(KML.readColor_), + 'width': _ol_xml_.makeObjectPropertySetter(XSD.readDecimal) + }); /** @@ -1501,13 +1501,13 @@ KML.LINE_STYLE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.MULTI_GEOMETRY_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'LineString': _ol_xml_.makeArrayPusher(KML.readLineString_), - 'LinearRing': _ol_xml_.makeArrayPusher(KML.readLinearRing_), - 'MultiGeometry': _ol_xml_.makeArrayPusher(KML.readMultiGeometry_), - 'Point': _ol_xml_.makeArrayPusher(KML.readPoint_), - 'Polygon': _ol_xml_.makeArrayPusher(KML.readPolygon_) - }); + KML.NAMESPACE_URIS_, { + 'LineString': _ol_xml_.makeArrayPusher(KML.readLineString_), + 'LinearRing': _ol_xml_.makeArrayPusher(KML.readLinearRing_), + 'MultiGeometry': _ol_xml_.makeArrayPusher(KML.readMultiGeometry_), + 'Point': _ol_xml_.makeArrayPusher(KML.readPoint_), + 'Polygon': _ol_xml_.makeArrayPusher(KML.readPolygon_) + }); /** @@ -1516,9 +1516,9 @@ KML.MULTI_GEOMETRY_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.GX_MULTITRACK_GEOMETRY_PARSERS_ = _ol_xml_.makeStructureNS( - KML.GX_NAMESPACE_URIS_, { - 'Track': _ol_xml_.makeArrayPusher(KML.readGxTrack_) - }); + KML.GX_NAMESPACE_URIS_, { + 'Track': _ol_xml_.makeArrayPusher(KML.readGxTrack_) + }); /** @@ -1527,17 +1527,17 @@ KML.GX_MULTITRACK_GEOMETRY_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.NETWORK_LINK_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'ExtendedData': KML.ExtendedDataParser_, - 'Region': KML.RegionParser_, - 'Link': KML.LinkParser_, - 'address': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'description': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'name': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'open': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean), - 'phoneNumber': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'visibility': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean) - }); + KML.NAMESPACE_URIS_, { + 'ExtendedData': KML.ExtendedDataParser_, + 'Region': KML.RegionParser_, + 'Link': KML.LinkParser_, + 'address': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'description': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'name': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'open': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean), + 'phoneNumber': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'visibility': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean) + }); /** @@ -1546,9 +1546,9 @@ KML.NETWORK_LINK_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.LINK_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'href': _ol_xml_.makeObjectPropertySetter(KML.readURI_) - }); + KML.NAMESPACE_URIS_, { + 'href': _ol_xml_.makeObjectPropertySetter(KML.readURI_) + }); /** @@ -1557,9 +1557,9 @@ KML.LINK_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.OUTER_BOUNDARY_IS_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'LinearRing': _ol_xml_.makeReplacer(KML.readFlatLinearRing_) - }); + KML.NAMESPACE_URIS_, { + 'LinearRing': _ol_xml_.makeReplacer(KML.readFlatLinearRing_) + }); /** @@ -1568,11 +1568,11 @@ KML.OUTER_BOUNDARY_IS_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.PAIR_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'Style': _ol_xml_.makeObjectPropertySetter(KML.readStyle_), - 'key': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'styleUrl': _ol_xml_.makeObjectPropertySetter(KML.readURI_) - }); + KML.NAMESPACE_URIS_, { + 'Style': _ol_xml_.makeObjectPropertySetter(KML.readStyle_), + 'key': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'styleUrl': _ol_xml_.makeObjectPropertySetter(KML.readURI_) + }); /** @@ -1581,36 +1581,36 @@ KML.PAIR_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.PLACEMARK_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'ExtendedData': KML.ExtendedDataParser_, - 'Region': KML.RegionParser_, - 'MultiGeometry': _ol_xml_.makeObjectPropertySetter( - KML.readMultiGeometry_, 'geometry'), - 'LineString': _ol_xml_.makeObjectPropertySetter( - KML.readLineString_, 'geometry'), - 'LinearRing': _ol_xml_.makeObjectPropertySetter( - KML.readLinearRing_, 'geometry'), - 'Point': _ol_xml_.makeObjectPropertySetter( - KML.readPoint_, 'geometry'), - 'Polygon': _ol_xml_.makeObjectPropertySetter( - KML.readPolygon_, 'geometry'), - 'Style': _ol_xml_.makeObjectPropertySetter(KML.readStyle_), - 'StyleMap': KML.PlacemarkStyleMapParser_, - 'address': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'description': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'name': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'open': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean), - 'phoneNumber': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'styleUrl': _ol_xml_.makeObjectPropertySetter(KML.readURI_), - 'visibility': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean) - }, _ol_xml_.makeStructureNS( - KML.GX_NAMESPACE_URIS_, { - 'MultiTrack': _ol_xml_.makeObjectPropertySetter( - KML.readGxMultiTrack_, 'geometry'), - 'Track': _ol_xml_.makeObjectPropertySetter( - KML.readGxTrack_, 'geometry') - } - )); + KML.NAMESPACE_URIS_, { + 'ExtendedData': KML.ExtendedDataParser_, + 'Region': KML.RegionParser_, + 'MultiGeometry': _ol_xml_.makeObjectPropertySetter( + KML.readMultiGeometry_, 'geometry'), + 'LineString': _ol_xml_.makeObjectPropertySetter( + KML.readLineString_, 'geometry'), + 'LinearRing': _ol_xml_.makeObjectPropertySetter( + KML.readLinearRing_, 'geometry'), + 'Point': _ol_xml_.makeObjectPropertySetter( + KML.readPoint_, 'geometry'), + 'Polygon': _ol_xml_.makeObjectPropertySetter( + KML.readPolygon_, 'geometry'), + 'Style': _ol_xml_.makeObjectPropertySetter(KML.readStyle_), + 'StyleMap': KML.PlacemarkStyleMapParser_, + 'address': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'description': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'name': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'open': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean), + 'phoneNumber': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'styleUrl': _ol_xml_.makeObjectPropertySetter(KML.readURI_), + 'visibility': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean) + }, _ol_xml_.makeStructureNS( + KML.GX_NAMESPACE_URIS_, { + 'MultiTrack': _ol_xml_.makeObjectPropertySetter( + KML.readGxMultiTrack_, 'geometry'), + 'Track': _ol_xml_.makeObjectPropertySetter( + KML.readGxTrack_, 'geometry') + } + )); /** @@ -1619,11 +1619,11 @@ KML.PLACEMARK_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.POLY_STYLE_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'color': _ol_xml_.makeObjectPropertySetter(KML.readColor_), - 'fill': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean), - 'outline': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean) - }); + KML.NAMESPACE_URIS_, { + 'color': _ol_xml_.makeObjectPropertySetter(KML.readColor_), + 'fill': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean), + 'outline': _ol_xml_.makeObjectPropertySetter(XSD.readBoolean) + }); /** @@ -1632,9 +1632,9 @@ KML.POLY_STYLE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.SCHEMA_DATA_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'SimpleData': KML.SimpleDataParser_ - }); + KML.NAMESPACE_URIS_, { + 'SimpleData': KML.SimpleDataParser_ + }); /** @@ -1643,12 +1643,12 @@ KML.SCHEMA_DATA_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.STYLE_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'IconStyle': KML.IconStyleParser_, - 'LabelStyle': KML.LabelStyleParser_, - 'LineStyle': KML.LineStyleParser_, - 'PolyStyle': KML.PolyStyleParser_ - }); + KML.NAMESPACE_URIS_, { + 'IconStyle': KML.IconStyleParser_, + 'LabelStyle': KML.LabelStyleParser_, + 'LineStyle': KML.LineStyleParser_, + 'PolyStyle': KML.PolyStyleParser_ + }); /** @@ -1657,9 +1657,9 @@ KML.STYLE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ KML.STYLE_MAP_PARSERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'Pair': KML.PairDataParser_ - }); + KML.NAMESPACE_URIS_, { + 'Pair': KML.PairDataParser_ + }); /** @@ -1670,16 +1670,16 @@ KML.STYLE_MAP_PARSERS_ = _ol_xml_.makeStructureNS( */ KML.prototype.readDocumentOrFolder_ = function(node, objectStack) { // FIXME use scope somehow - var parsersNS = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'Document': _ol_xml_.makeArrayExtender(this.readDocumentOrFolder_, this), - 'Folder': _ol_xml_.makeArrayExtender(this.readDocumentOrFolder_, this), - 'Placemark': _ol_xml_.makeArrayPusher(this.readPlacemark_, this), - 'Style': this.readSharedStyle_.bind(this), - 'StyleMap': this.readSharedStyleMap_.bind(this) - }); + const parsersNS = _ol_xml_.makeStructureNS( + KML.NAMESPACE_URIS_, { + 'Document': _ol_xml_.makeArrayExtender(this.readDocumentOrFolder_, this), + 'Folder': _ol_xml_.makeArrayExtender(this.readDocumentOrFolder_, this), + 'Placemark': _ol_xml_.makeArrayPusher(this.readPlacemark_, this), + 'Style': this.readSharedStyle_.bind(this), + 'StyleMap': this.readSharedStyleMap_.bind(this) + }); /** @type {Array.} */ - var features = _ol_xml_.pushParseAndPop([], parsersNS, node, objectStack, this); + const features = _ol_xml_.pushParseAndPop([], parsersNS, node, objectStack, this); if (features) { return features; } else { @@ -1695,19 +1695,19 @@ KML.prototype.readDocumentOrFolder_ = function(node, objectStack) { * @return {ol.Feature|undefined} Feature. */ KML.prototype.readPlacemark_ = function(node, objectStack) { - var object = _ol_xml_.pushParseAndPop({'geometry': null}, - KML.PLACEMARK_PARSERS_, node, objectStack); + const object = _ol_xml_.pushParseAndPop({'geometry': null}, + KML.PLACEMARK_PARSERS_, node, objectStack); if (!object) { return undefined; } - var feature = new Feature(); - var id = node.getAttribute('id'); + const feature = new Feature(); + const id = node.getAttribute('id'); if (id !== null) { feature.setId(id); } - var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]); + const options = /** @type {olx.format.ReadOptions} */ (objectStack[0]); - var geometry = object['geometry']; + const geometry = object['geometry']; if (geometry) { transformWithOptions(geometry, false, options); } @@ -1715,11 +1715,11 @@ KML.prototype.readPlacemark_ = function(node, objectStack) { delete object['geometry']; if (this.extractStyles_) { - var style = object['Style']; - var styleUrl = object['styleUrl']; - var styleFunction = KML.createFeatureStyleFunction_( - style, styleUrl, this.defaultStyle_, this.sharedStyles_, - this.showPointNames_); + const style = object['Style']; + const styleUrl = object['styleUrl']; + const styleFunction = KML.createFeatureStyleFunction_( + style, styleUrl, this.defaultStyle_, this.sharedStyles_, + this.showPointNames_); feature.setStyle(styleFunction); } delete object['Style']; @@ -1738,17 +1738,17 @@ KML.prototype.readPlacemark_ = function(node, objectStack) { * @private */ KML.prototype.readSharedStyle_ = function(node, objectStack) { - var id = node.getAttribute('id'); + const id = node.getAttribute('id'); if (id !== null) { - var style = KML.readStyle_(node, objectStack); + const style = KML.readStyle_(node, objectStack); if (style) { - var styleUri; - var baseURI = node.baseURI; + let styleUri; + let baseURI = node.baseURI; if (!baseURI || baseURI == 'about:blank') { baseURI = window.location.href; } if (baseURI) { - var url = new URL('#' + id, baseURI); + const url = new URL('#' + id, baseURI); styleUri = url.href; } else { styleUri = '#' + id; @@ -1765,21 +1765,21 @@ KML.prototype.readSharedStyle_ = function(node, objectStack) { * @private */ KML.prototype.readSharedStyleMap_ = function(node, objectStack) { - var id = node.getAttribute('id'); + const id = node.getAttribute('id'); if (id === null) { return; } - var styleMapValue = KML.readStyleMapValue_(node, objectStack); + const styleMapValue = KML.readStyleMapValue_(node, objectStack); if (!styleMapValue) { return; } - var styleUri; - var baseURI = node.baseURI; + let styleUri; + let baseURI = node.baseURI; if (!baseURI || baseURI == 'about:blank') { baseURI = window.location.href; } if (baseURI) { - var url = new URL('#' + id, baseURI); + const url = new URL('#' + id, baseURI); styleUri = url.href; } else { styleUri = '#' + id; @@ -1809,8 +1809,8 @@ KML.prototype.readFeatureFromNode = function(node, opt_options) { if (!includes(KML.NAMESPACE_URIS_, node.namespaceURI)) { return null; } - var feature = this.readPlacemark_( - node, [this.getReadOptions(node, opt_options)]); + const feature = this.readPlacemark_( + node, [this.getReadOptions(node, opt_options)]); if (feature) { return feature; } else { @@ -1840,19 +1840,19 @@ KML.prototype.readFeaturesFromNode = function(node, opt_options) { if (!includes(KML.NAMESPACE_URIS_, node.namespaceURI)) { return []; } - var features; - var localName = node.localName; + let features; + const localName = node.localName; if (localName == 'Document' || localName == 'Folder') { features = this.readDocumentOrFolder_( - node, [this.getReadOptions(node, opt_options)]); + node, [this.getReadOptions(node, opt_options)]); if (features) { return features; } else { return []; } } else if (localName == 'Placemark') { - var feature = this.readPlacemark_( - node, [this.getReadOptions(node, opt_options)]); + const feature = this.readPlacemark_( + node, [this.getReadOptions(node, opt_options)]); if (feature) { return [feature]; } else { @@ -1860,9 +1860,9 @@ KML.prototype.readFeaturesFromNode = function(node, opt_options) { } } else if (localName == 'kml') { features = []; - var n; + let n; for (n = node.firstElementChild; n; n = n.nextElementSibling) { - var fs = this.readFeaturesFromNode(n, opt_options); + const fs = this.readFeaturesFromNode(n, opt_options); if (fs) { extend(features, fs); } @@ -1887,7 +1887,7 @@ KML.prototype.readName = function(source) { } else if (_ol_xml_.isNode(source)) { return this.readNameFromNode(/** @type {Node} */ (source)); } else if (typeof source === 'string') { - var doc = _ol_xml_.parse(source); + const doc = _ol_xml_.parse(source); return this.readNameFromDocument(doc); } else { return undefined; @@ -1900,10 +1900,10 @@ KML.prototype.readName = function(source) { * @return {string|undefined} Name. */ KML.prototype.readNameFromDocument = function(doc) { - var n; + let n; for (n = doc.firstChild; n; n = n.nextSibling) { if (n.nodeType == Node.ELEMENT_NODE) { - var name = this.readNameFromNode(n); + const name = this.readNameFromNode(n); if (name) { return name; } @@ -1918,7 +1918,7 @@ KML.prototype.readNameFromDocument = function(doc) { * @return {string|undefined} Name. */ KML.prototype.readNameFromNode = function(node) { - var n; + let n; for (n = node.firstElementChild; n; n = n.nextElementSibling) { if (includes(KML.NAMESPACE_URIS_, n.namespaceURI) && n.localName == 'name') { @@ -1926,13 +1926,13 @@ KML.prototype.readNameFromNode = function(node) { } } for (n = node.firstElementChild; n; n = n.nextElementSibling) { - var localName = n.localName; + const localName = n.localName; if (includes(KML.NAMESPACE_URIS_, n.namespaceURI) && (localName == 'Document' || localName == 'Folder' || localName == 'Placemark' || localName == 'kml')) { - var name = this.readNameFromNode(n); + const name = this.readNameFromNode(n); if (name) { return name; } @@ -1950,15 +1950,15 @@ KML.prototype.readNameFromNode = function(node) { * @api */ KML.prototype.readNetworkLinks = function(source) { - var networkLinks = []; + const networkLinks = []; if (_ol_xml_.isDocument(source)) { extend(networkLinks, this.readNetworkLinksFromDocument( - /** @type {Document} */ (source))); + /** @type {Document} */ (source))); } else if (_ol_xml_.isNode(source)) { extend(networkLinks, this.readNetworkLinksFromNode( - /** @type {Node} */ (source))); + /** @type {Node} */ (source))); } else if (typeof source === 'string') { - var doc = _ol_xml_.parse(source); + const doc = _ol_xml_.parse(source); extend(networkLinks, this.readNetworkLinksFromDocument(doc)); } return networkLinks; @@ -1970,8 +1970,8 @@ KML.prototype.readNetworkLinks = function(source) { * @return {Array.} Network links. */ KML.prototype.readNetworkLinksFromDocument = function(doc) { - var n, networkLinks = []; - for (n = doc.firstChild; n; n = n.nextSibling) { + const networkLinks = []; + for (let n = doc.firstChild; n; n = n.nextSibling) { if (n.nodeType == Node.ELEMENT_NODE) { extend(networkLinks, this.readNetworkLinksFromNode(n)); } @@ -1985,17 +1985,17 @@ KML.prototype.readNetworkLinksFromDocument = function(doc) { * @return {Array.} Network links. */ KML.prototype.readNetworkLinksFromNode = function(node) { - var n, networkLinks = []; - for (n = node.firstElementChild; n; n = n.nextElementSibling) { + const networkLinks = []; + for (let n = node.firstElementChild; n; n = n.nextElementSibling) { if (includes(KML.NAMESPACE_URIS_, n.namespaceURI) && n.localName == 'NetworkLink') { - var obj = _ol_xml_.pushParseAndPop({}, KML.NETWORK_LINK_PARSERS_, - n, []); + const obj = _ol_xml_.pushParseAndPop({}, KML.NETWORK_LINK_PARSERS_, + n, []); networkLinks.push(obj); } } - for (n = node.firstElementChild; n; n = n.nextElementSibling) { - var localName = n.localName; + for (let n = node.firstElementChild; n; n = n.nextElementSibling) { + const localName = n.localName; if (includes(KML.NAMESPACE_URIS_, n.namespaceURI) && (localName == 'Document' || localName == 'Folder' || @@ -2015,15 +2015,15 @@ KML.prototype.readNetworkLinksFromNode = function(node) { * @api */ KML.prototype.readRegion = function(source) { - var regions = []; + const regions = []; if (_ol_xml_.isDocument(source)) { extend(regions, this.readRegionFromDocument( - /** @type {Document} */ (source))); + /** @type {Document} */ (source))); } else if (_ol_xml_.isNode(source)) { extend(regions, this.readRegionFromNode( - /** @type {Node} */ (source))); + /** @type {Node} */ (source))); } else if (typeof source === 'string') { - var doc = _ol_xml_.parse(source); + const doc = _ol_xml_.parse(source); extend(regions, this.readRegionFromDocument(doc)); } return regions; @@ -2035,8 +2035,8 @@ KML.prototype.readRegion = function(source) { * @return {Array.} Region. */ KML.prototype.readRegionFromDocument = function(doc) { - var n, regions = []; - for (n = doc.firstChild; n; n = n.nextSibling) { + const regions = []; + for (let n = doc.firstChild; n; n = n.nextSibling) { if (n.nodeType == Node.ELEMENT_NODE) { extend(regions, this.readRegionFromNode(n)); } @@ -2051,17 +2051,17 @@ KML.prototype.readRegionFromDocument = function(doc) { * @api */ KML.prototype.readRegionFromNode = function(node) { - var n, regions = []; - for (n = node.firstElementChild; n; n = n.nextElementSibling) { + const regions = []; + for (let n = node.firstElementChild; n; n = n.nextElementSibling) { if (includes(KML.NAMESPACE_URIS_, n.namespaceURI) && n.localName == 'Region') { - var obj = _ol_xml_.pushParseAndPop({}, KML.REGION_PARSERS_, - n, []); + const obj = _ol_xml_.pushParseAndPop({}, KML.REGION_PARSERS_, + n, []); regions.push(obj); } } - for (n = node.firstElementChild; n; n = n.nextElementSibling) { - var localName = n.localName; + for (let n = node.firstElementChild; n; n = n.nextElementSibling) { + const localName = n.localName; if (includes(KML.NAMESPACE_URIS_, n.namespaceURI) && (localName == 'Document' || localName == 'Folder' || @@ -2090,12 +2090,12 @@ KML.prototype.readProjection; * @private */ KML.writeColorTextNode_ = function(node, color) { - var rgba = asArray(color); - var opacity = (rgba.length == 4) ? rgba[3] : 1; - var abgr = [opacity * 255, rgba[2], rgba[1], rgba[0]]; - var i; + const rgba = asArray(color); + const opacity = (rgba.length == 4) ? rgba[3] : 1; + const abgr = [opacity * 255, rgba[2], rgba[1], rgba[0]]; + let i; for (i = 0; i < 4; ++i) { - var hex = parseInt(abgr[i], 10).toString(16); + const hex = parseInt(abgr[i], 10).toString(16); abgr[i] = (hex.length == 1) ? '0' + hex : hex; } XSD.writeStringTextNode(node, abgr.join('')); @@ -2109,12 +2109,12 @@ KML.writeColorTextNode_ = function(node, color) { * @private */ KML.writeCoordinatesTextNode_ = function(node, coordinates, objectStack) { - var context = objectStack[objectStack.length - 1]; + const context = objectStack[objectStack.length - 1]; - var layout = context['layout']; - var stride = context['stride']; + const layout = context['layout']; + const stride = context['stride']; - var dimension; + let dimension; if (layout == GeometryLayout.XY || layout == GeometryLayout.XYM) { dimension = 2; @@ -2125,9 +2125,9 @@ KML.writeCoordinatesTextNode_ = function(node, coordinates, objectStack) { assert(false, 34); // Invalid geometry layout } - var d, i; - var ii = coordinates.length; - var text = ''; + let d, i; + const ii = coordinates.length; + let text = ''; if (ii > 0) { text += coordinates[0]; for (d = 1; d < dimension; ++d) { @@ -2152,22 +2152,22 @@ KML.writeCoordinatesTextNode_ = function(node, coordinates, objectStack) { */ KML.writeDataNode_ = function(node, pair, objectStack) { node.setAttribute('name', pair.name); - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; - var value = pair.value; + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const value = pair.value; if (typeof value == 'object') { if (value !== null && value.displayName) { _ol_xml_.pushSerializeAndPop(context, KML.EXTENDEDDATA_NODE_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, [value.displayName], objectStack, ['displayName']); + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, [value.displayName], objectStack, ['displayName']); } if (value !== null && value.value) { _ol_xml_.pushSerializeAndPop(context, KML.EXTENDEDDATA_NODE_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, [value.value], objectStack, ['value']); + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, [value.value], objectStack, ['value']); } } else { _ol_xml_.pushSerializeAndPop(context, KML.EXTENDEDDATA_NODE_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, [value], objectStack, ['value']); + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, [value], objectStack, ['value']); } }; @@ -2200,10 +2200,10 @@ KML.writeDataNodeValue_ = function(node, value) { * @private */ KML.writeDocument_ = function(node, features, objectStack) { - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; _ol_xml_.pushSerializeAndPop(context, KML.DOCUMENT_SERIALIZERS_, - KML.DOCUMENT_NODE_FACTORY_, features, objectStack, undefined, - this); + KML.DOCUMENT_NODE_FACTORY_, features, objectStack, undefined, + this); }; @@ -2214,13 +2214,14 @@ KML.writeDocument_ = function(node, features, objectStack) { * @private */ KML.writeExtendedData_ = function(node, namesAndValues, objectStack) { - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; - var names = namesAndValues.names, values = namesAndValues.values; - var length = names.length; + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const names = namesAndValues.names; + const values = namesAndValues.values; + const length = names.length; - for (var i = 0; i < length; i++) { + for (let i = 0; i < length; i++) { _ol_xml_.pushSerializeAndPop(context, KML.EXTENDEDDATA_NODE_SERIALIZERS_, - KML.DATA_NODE_FACTORY_, [{name: names[i], value: values[i]}], objectStack); + KML.DATA_NODE_FACTORY_, [{name: names[i], value: values[i]}], objectStack); } }; @@ -2232,18 +2233,18 @@ KML.writeExtendedData_ = function(node, namesAndValues, objectStack) { * @private */ KML.writeIcon_ = function(node, icon, objectStack) { - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; - var parentNode = objectStack[objectStack.length - 1].node; - var orderedKeys = KML.ICON_SEQUENCE_[parentNode.namespaceURI]; - var values = _ol_xml_.makeSequence(icon, orderedKeys); + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const parentNode = objectStack[objectStack.length - 1].node; + let orderedKeys = KML.ICON_SEQUENCE_[parentNode.namespaceURI]; + let values = _ol_xml_.makeSequence(icon, orderedKeys); _ol_xml_.pushSerializeAndPop(context, - KML.ICON_SERIALIZERS_, _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, - values, objectStack, orderedKeys); + KML.ICON_SERIALIZERS_, _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, + values, objectStack, orderedKeys); orderedKeys = KML.ICON_SEQUENCE_[KML.GX_NAMESPACE_URIS_[0]]; values = _ol_xml_.makeSequence(icon, orderedKeys); _ol_xml_.pushSerializeAndPop(context, KML.ICON_SERIALIZERS_, - KML.GX_NODE_FACTORY_, values, objectStack, orderedKeys); + KML.GX_NODE_FACTORY_, values, objectStack, orderedKeys); }; @@ -2254,20 +2255,20 @@ KML.writeIcon_ = function(node, icon, objectStack) { * @private */ KML.writeIconStyle_ = function(node, style, objectStack) { - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; - var properties = {}; - var src = style.getSrc(); - var size = style.getSize(); - var iconImageSize = style.getImageSize(); - var iconProperties = { + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const properties = {}; + const src = style.getSrc(); + const size = style.getSize(); + const iconImageSize = style.getImageSize(); + const iconProperties = { 'href': src }; if (size) { iconProperties['w'] = size[0]; iconProperties['h'] = size[1]; - var anchor = style.getAnchor(); // top-left - var origin = style.getOrigin(); // top-left + const anchor = style.getAnchor(); // top-left + const origin = style.getOrigin(); // top-left if (origin && iconImageSize && origin[0] !== 0 && origin[1] !== size[1]) { iconProperties['x'] = origin[0]; @@ -2275,7 +2276,7 @@ KML.writeIconStyle_ = function(node, style, objectStack) { } if (anchor && (anchor[0] !== size[0] / 2 || anchor[1] !== size[1] / 2)) { - var /** @type {ol.KMLVec2_} */ hotSpot = { + const /** @type {ol.KMLVec2_} */ hotSpot = { x: anchor[0], xunits: IconAnchorUnits.PIXELS, y: size[1] - anchor[1], @@ -2287,21 +2288,21 @@ KML.writeIconStyle_ = function(node, style, objectStack) { properties['Icon'] = iconProperties; - var scale = style.getScale(); + const scale = style.getScale(); if (scale !== 1) { properties['scale'] = scale; } - var rotation = style.getRotation(); + const rotation = style.getRotation(); if (rotation !== 0) { properties['heading'] = rotation; // 0-360 } - var parentNode = objectStack[objectStack.length - 1].node; - var orderedKeys = KML.ICON_STYLE_SEQUENCE_[parentNode.namespaceURI]; - var values = _ol_xml_.makeSequence(properties, orderedKeys); + const parentNode = objectStack[objectStack.length - 1].node; + const orderedKeys = KML.ICON_STYLE_SEQUENCE_[parentNode.namespaceURI]; + const values = _ol_xml_.makeSequence(properties, orderedKeys); _ol_xml_.pushSerializeAndPop(context, KML.ICON_STYLE_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); }; @@ -2312,22 +2313,22 @@ KML.writeIconStyle_ = function(node, style, objectStack) { * @private */ KML.writeLabelStyle_ = function(node, style, objectStack) { - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; - var properties = {}; - var fill = style.getFill(); + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const properties = {}; + const fill = style.getFill(); if (fill) { properties['color'] = fill.getColor(); } - var scale = style.getScale(); + const scale = style.getScale(); if (scale && scale !== 1) { properties['scale'] = scale; } - var parentNode = objectStack[objectStack.length - 1].node; - var orderedKeys = + const parentNode = objectStack[objectStack.length - 1].node; + const orderedKeys = KML.LABEL_STYLE_SEQUENCE_[parentNode.namespaceURI]; - var values = _ol_xml_.makeSequence(properties, orderedKeys); + const values = _ol_xml_.makeSequence(properties, orderedKeys); _ol_xml_.pushSerializeAndPop(context, KML.LABEL_STYLE_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); }; @@ -2338,16 +2339,16 @@ KML.writeLabelStyle_ = function(node, style, objectStack) { * @private */ KML.writeLineStyle_ = function(node, style, objectStack) { - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; - var properties = { + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const properties = { 'color': style.getColor(), 'width': style.getWidth() }; - var parentNode = objectStack[objectStack.length - 1].node; - var orderedKeys = KML.LINE_STYLE_SEQUENCE_[parentNode.namespaceURI]; - var values = _ol_xml_.makeSequence(properties, orderedKeys); + const parentNode = objectStack[objectStack.length - 1].node; + const orderedKeys = KML.LINE_STYLE_SEQUENCE_[parentNode.namespaceURI]; + const values = _ol_xml_.makeSequence(properties, orderedKeys); _ol_xml_.pushSerializeAndPop(context, KML.LINE_STYLE_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); }; @@ -2359,12 +2360,12 @@ KML.writeLineStyle_ = function(node, style, objectStack) { */ KML.writeMultiGeometry_ = function(node, geometry, objectStack) { /** @type {ol.XmlNodeStackItem} */ - var context = {node: node}; - var type = geometry.getType(); + const context = {node: node}; + const type = geometry.getType(); /** @type {Array.} */ - var geometries; + let geometries; /** @type {function(*, Array.<*>, string=): (Node|undefined)} */ - var factory; + let factory; if (type == GeometryType.GEOMETRY_COLLECTION) { geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries(); factory = KML.GEOMETRY_NODE_FACTORY_; @@ -2383,8 +2384,8 @@ KML.writeMultiGeometry_ = function(node, geometry, objectStack) { assert(false, 39); // Unknown geometry type } _ol_xml_.pushSerializeAndPop(context, - KML.MULTI_GEOMETRY_SERIALIZERS_, factory, - geometries, objectStack); + KML.MULTI_GEOMETRY_SERIALIZERS_, factory, + geometries, objectStack); }; @@ -2395,10 +2396,10 @@ KML.writeMultiGeometry_ = function(node, geometry, objectStack) { * @private */ KML.writeBoundaryIs_ = function(node, linearRing, objectStack) { - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; _ol_xml_.pushSerializeAndPop(context, - KML.BOUNDARY_IS_SERIALIZERS_, - KML.LINEAR_RING_NODE_FACTORY_, [linearRing], objectStack); + KML.BOUNDARY_IS_SERIALIZERS_, + KML.LINEAR_RING_NODE_FACTORY_, [linearRing], objectStack); }; @@ -2412,7 +2413,7 @@ KML.writeBoundaryIs_ = function(node, linearRing, objectStack) { * @private */ KML.writePlacemark_ = function(node, feature, objectStack) { - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; // set id if (feature.getId()) { @@ -2420,53 +2421,53 @@ KML.writePlacemark_ = function(node, feature, objectStack) { } // serialize properties (properties unknown to KML are not serialized) - var properties = feature.getProperties(); + const properties = feature.getProperties(); // don't export these to ExtendedData - var filter = {'address': 1, 'description': 1, 'name': 1, 'open': 1, + const filter = {'address': 1, 'description': 1, 'name': 1, 'open': 1, 'phoneNumber': 1, 'styleUrl': 1, 'visibility': 1}; filter[feature.getGeometryName()] = 1; - var keys = Object.keys(properties || {}).sort().filter(function(v) { + const keys = Object.keys(properties || {}).sort().filter(function(v) { return !filter[v]; }); if (keys.length > 0) { - var sequence = _ol_xml_.makeSequence(properties, keys); - var namesAndValues = {names: keys, values: sequence}; + const sequence = _ol_xml_.makeSequence(properties, keys); + const namesAndValues = {names: keys, values: sequence}; _ol_xml_.pushSerializeAndPop(context, KML.PLACEMARK_SERIALIZERS_, - KML.EXTENDEDDATA_NODE_FACTORY_, [namesAndValues], objectStack); + KML.EXTENDEDDATA_NODE_FACTORY_, [namesAndValues], objectStack); } - var styleFunction = feature.getStyleFunction(); + const styleFunction = feature.getStyleFunction(); if (styleFunction) { // FIXME the styles returned by the style function are supposed to be // resolution-independent here - var styles = styleFunction.call(feature, 0); + const styles = styleFunction.call(feature, 0); if (styles) { - var style = Array.isArray(styles) ? styles[0] : styles; + const style = Array.isArray(styles) ? styles[0] : styles; if (this.writeStyles_) { properties['Style'] = style; } - var textStyle = style.getText(); + const textStyle = style.getText(); if (textStyle) { properties['name'] = textStyle.getText(); } } } - var parentNode = objectStack[objectStack.length - 1].node; - var orderedKeys = KML.PLACEMARK_SEQUENCE_[parentNode.namespaceURI]; - var values = _ol_xml_.makeSequence(properties, orderedKeys); + const parentNode = objectStack[objectStack.length - 1].node; + const orderedKeys = KML.PLACEMARK_SEQUENCE_[parentNode.namespaceURI]; + const values = _ol_xml_.makeSequence(properties, orderedKeys); _ol_xml_.pushSerializeAndPop(context, KML.PLACEMARK_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); // serialize geometry - var options = /** @type {olx.format.WriteOptions} */ (objectStack[0]); - var geometry = feature.getGeometry(); + const options = /** @type {olx.format.WriteOptions} */ (objectStack[0]); + let geometry = feature.getGeometry(); if (geometry) { geometry = transformWithOptions(geometry, true, options); } _ol_xml_.pushSerializeAndPop(context, KML.PLACEMARK_SERIALIZERS_, - KML.GEOMETRY_NODE_FACTORY_, [geometry], objectStack); + KML.GEOMETRY_NODE_FACTORY_, [geometry], objectStack); }; @@ -2477,20 +2478,20 @@ KML.writePlacemark_ = function(node, feature, objectStack) { * @private */ KML.writePrimitiveGeometry_ = function(node, geometry, objectStack) { - var flatCoordinates = geometry.getFlatCoordinates(); - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const flatCoordinates = geometry.getFlatCoordinates(); + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; context['layout'] = geometry.getLayout(); context['stride'] = geometry.getStride(); // serialize properties (properties unknown to KML are not serialized) - var properties = geometry.getProperties(); + const properties = geometry.getProperties(); properties.coordinates = flatCoordinates; - var parentNode = objectStack[objectStack.length - 1].node; - var orderedKeys = KML.PRIMITIVE_GEOMETRY_SEQUENCE_[parentNode.namespaceURI]; - var values = _ol_xml_.makeSequence(properties, orderedKeys); + const parentNode = objectStack[objectStack.length - 1].node; + const orderedKeys = KML.PRIMITIVE_GEOMETRY_SEQUENCE_[parentNode.namespaceURI]; + const values = _ol_xml_.makeSequence(properties, orderedKeys); _ol_xml_.pushSerializeAndPop(context, KML.PRIMITIVE_GEOMETRY_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); }; @@ -2501,19 +2502,19 @@ KML.writePrimitiveGeometry_ = function(node, geometry, objectStack) { * @private */ KML.writePolygon_ = function(node, polygon, objectStack) { - var linearRings = polygon.getLinearRings(); - var outerRing = linearRings.shift(); - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const linearRings = polygon.getLinearRings(); + const outerRing = linearRings.shift(); + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; // inner rings _ol_xml_.pushSerializeAndPop(context, - KML.POLYGON_SERIALIZERS_, - KML.INNER_BOUNDARY_NODE_FACTORY_, - linearRings, objectStack); + KML.POLYGON_SERIALIZERS_, + KML.INNER_BOUNDARY_NODE_FACTORY_, + linearRings, objectStack); // outer ring _ol_xml_.pushSerializeAndPop(context, - KML.POLYGON_SERIALIZERS_, - KML.OUTER_BOUNDARY_NODE_FACTORY_, - [outerRing], objectStack); + KML.POLYGON_SERIALIZERS_, + KML.OUTER_BOUNDARY_NODE_FACTORY_, + [outerRing], objectStack); }; @@ -2524,9 +2525,9 @@ KML.writePolygon_ = function(node, polygon, objectStack) { * @private */ KML.writePolyStyle_ = function(node, style, objectStack) { - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; _ol_xml_.pushSerializeAndPop(context, KML.POLY_STYLE_SERIALIZERS_, - KML.COLOR_NODE_FACTORY_, [style.getColor()], objectStack); + KML.COLOR_NODE_FACTORY_, [style.getColor()], objectStack); }; @@ -2538,7 +2539,7 @@ KML.writePolyStyle_ = function(node, style, objectStack) { KML.writeScaleTextNode_ = function(node, scale) { // the Math is to remove any excess decimals created by float arithmetic XSD.writeDecimalTextNode(node, - Math.round(scale * 1e6) / 1e6); + Math.round(scale * 1e6) / 1e6); }; @@ -2549,12 +2550,12 @@ KML.writeScaleTextNode_ = function(node, scale) { * @private */ KML.writeStyle_ = function(node, style, objectStack) { - var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; - var properties = {}; - var fillStyle = style.getFill(); - var strokeStyle = style.getStroke(); - var imageStyle = style.getImage(); - var textStyle = style.getText(); + const /** @type {ol.XmlNodeStackItem} */ context = {node: node}; + const properties = {}; + const fillStyle = style.getFill(); + const strokeStyle = style.getStroke(); + const imageStyle = style.getImage(); + const textStyle = style.getText(); if (imageStyle instanceof Icon) { properties['IconStyle'] = imageStyle; } @@ -2567,11 +2568,11 @@ KML.writeStyle_ = function(node, style, objectStack) { if (fillStyle) { properties['PolyStyle'] = fillStyle; } - var parentNode = objectStack[objectStack.length - 1].node; - var orderedKeys = KML.STYLE_SEQUENCE_[parentNode.namespaceURI]; - var values = _ol_xml_.makeSequence(properties, orderedKeys); + const parentNode = objectStack[objectStack.length - 1].node; + const orderedKeys = KML.STYLE_SEQUENCE_[parentNode.namespaceURI]; + const values = _ol_xml_.makeSequence(properties, orderedKeys); _ol_xml_.pushSerializeAndPop(context, KML.STYLE_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys); }; @@ -2594,9 +2595,9 @@ KML.writeVec2_ = function(node, vec2) { * @private */ KML.KML_SEQUENCE_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, [ - 'Document', 'Placemark' - ]); + KML.NAMESPACE_URIS_, [ + 'Document', 'Placemark' + ]); /** @@ -2605,10 +2606,10 @@ KML.KML_SEQUENCE_ = _ol_xml_.makeStructureNS( * @private */ KML.KML_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'Document': _ol_xml_.makeChildAppender(KML.writeDocument_), - 'Placemark': _ol_xml_.makeChildAppender(KML.writePlacemark_) - }); + KML.NAMESPACE_URIS_, { + 'Document': _ol_xml_.makeChildAppender(KML.writeDocument_), + 'Placemark': _ol_xml_.makeChildAppender(KML.writePlacemark_) + }); /** @@ -2617,9 +2618,9 @@ KML.KML_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.DOCUMENT_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'Placemark': _ol_xml_.makeChildAppender(KML.writePlacemark_) - }); + KML.NAMESPACE_URIS_, { + 'Placemark': _ol_xml_.makeChildAppender(KML.writePlacemark_) + }); /** @@ -2628,11 +2629,11 @@ KML.DOCUMENT_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.EXTENDEDDATA_NODE_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'Data': _ol_xml_.makeChildAppender(KML.writeDataNode_), - 'value': _ol_xml_.makeChildAppender(KML.writeDataNodeValue_), - 'displayName': _ol_xml_.makeChildAppender(KML.writeDataNodeName_) - }); + KML.NAMESPACE_URIS_, { + 'Data': _ol_xml_.makeChildAppender(KML.writeDataNode_), + 'value': _ol_xml_.makeChildAppender(KML.writeDataNodeValue_), + 'displayName': _ol_xml_.makeChildAppender(KML.writeDataNodeName_) + }); /** @@ -2657,12 +2658,12 @@ KML.GEOMETRY_TYPE_TO_NODENAME_ = { * @private */ KML.ICON_SEQUENCE_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, [ - 'href' - ], - _ol_xml_.makeStructureNS(KML.GX_NAMESPACE_URIS_, [ - 'x', 'y', 'w', 'h' - ])); + KML.NAMESPACE_URIS_, [ + 'href' + ], + _ol_xml_.makeStructureNS(KML.GX_NAMESPACE_URIS_, [ + 'x', 'y', 'w', 'h' + ])); /** @@ -2671,15 +2672,15 @@ KML.ICON_SEQUENCE_ = _ol_xml_.makeStructureNS( * @private */ KML.ICON_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'href': _ol_xml_.makeChildAppender(XSD.writeStringTextNode) - }, _ol_xml_.makeStructureNS( - KML.GX_NAMESPACE_URIS_, { - 'x': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'y': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'w': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'h': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode) - })); + KML.NAMESPACE_URIS_, { + 'href': _ol_xml_.makeChildAppender(XSD.writeStringTextNode) + }, _ol_xml_.makeStructureNS( + KML.GX_NAMESPACE_URIS_, { + 'x': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'y': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'w': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'h': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode) + })); /** @@ -2688,9 +2689,9 @@ KML.ICON_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.ICON_STYLE_SEQUENCE_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, [ - 'scale', 'heading', 'Icon', 'hotSpot' - ]); + KML.NAMESPACE_URIS_, [ + 'scale', 'heading', 'Icon', 'hotSpot' + ]); /** @@ -2699,12 +2700,12 @@ KML.ICON_STYLE_SEQUENCE_ = _ol_xml_.makeStructureNS( * @private */ KML.ICON_STYLE_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'Icon': _ol_xml_.makeChildAppender(KML.writeIcon_), - 'heading': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), - 'hotSpot': _ol_xml_.makeChildAppender(KML.writeVec2_), - 'scale': _ol_xml_.makeChildAppender(KML.writeScaleTextNode_) - }); + KML.NAMESPACE_URIS_, { + 'Icon': _ol_xml_.makeChildAppender(KML.writeIcon_), + 'heading': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode), + 'hotSpot': _ol_xml_.makeChildAppender(KML.writeVec2_), + 'scale': _ol_xml_.makeChildAppender(KML.writeScaleTextNode_) + }); /** @@ -2713,9 +2714,9 @@ KML.ICON_STYLE_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.LABEL_STYLE_SEQUENCE_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, [ - 'color', 'scale' - ]); + KML.NAMESPACE_URIS_, [ + 'color', 'scale' + ]); /** @@ -2724,10 +2725,10 @@ KML.LABEL_STYLE_SEQUENCE_ = _ol_xml_.makeStructureNS( * @private */ KML.LABEL_STYLE_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'color': _ol_xml_.makeChildAppender(KML.writeColorTextNode_), - 'scale': _ol_xml_.makeChildAppender(KML.writeScaleTextNode_) - }); + KML.NAMESPACE_URIS_, { + 'color': _ol_xml_.makeChildAppender(KML.writeColorTextNode_), + 'scale': _ol_xml_.makeChildAppender(KML.writeScaleTextNode_) + }); /** @@ -2736,9 +2737,9 @@ KML.LABEL_STYLE_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.LINE_STYLE_SEQUENCE_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, [ - 'color', 'width' - ]); + KML.NAMESPACE_URIS_, [ + 'color', 'width' + ]); /** @@ -2747,10 +2748,10 @@ KML.LINE_STYLE_SEQUENCE_ = _ol_xml_.makeStructureNS( * @private */ KML.LINE_STYLE_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'color': _ol_xml_.makeChildAppender(KML.writeColorTextNode_), - 'width': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode) - }); + KML.NAMESPACE_URIS_, { + 'color': _ol_xml_.makeChildAppender(KML.writeColorTextNode_), + 'width': _ol_xml_.makeChildAppender(XSD.writeDecimalTextNode) + }); /** @@ -2759,10 +2760,10 @@ KML.LINE_STYLE_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.BOUNDARY_IS_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'LinearRing': _ol_xml_.makeChildAppender( - KML.writePrimitiveGeometry_) - }); + KML.NAMESPACE_URIS_, { + 'LinearRing': _ol_xml_.makeChildAppender( + KML.writePrimitiveGeometry_) + }); /** @@ -2771,15 +2772,15 @@ KML.BOUNDARY_IS_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.MULTI_GEOMETRY_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'LineString': _ol_xml_.makeChildAppender( - KML.writePrimitiveGeometry_), - 'Point': _ol_xml_.makeChildAppender( - KML.writePrimitiveGeometry_), - 'Polygon': _ol_xml_.makeChildAppender(KML.writePolygon_), - 'GeometryCollection': _ol_xml_.makeChildAppender( - KML.writeMultiGeometry_) - }); + KML.NAMESPACE_URIS_, { + 'LineString': _ol_xml_.makeChildAppender( + KML.writePrimitiveGeometry_), + 'Point': _ol_xml_.makeChildAppender( + KML.writePrimitiveGeometry_), + 'Polygon': _ol_xml_.makeChildAppender(KML.writePolygon_), + 'GeometryCollection': _ol_xml_.makeChildAppender( + KML.writeMultiGeometry_) + }); /** @@ -2788,10 +2789,10 @@ KML.MULTI_GEOMETRY_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.PLACEMARK_SEQUENCE_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, [ - 'name', 'open', 'visibility', 'address', 'phoneNumber', 'description', - 'styleUrl', 'Style' - ]); + KML.NAMESPACE_URIS_, [ + 'name', 'open', 'visibility', 'address', 'phoneNumber', 'description', + 'styleUrl', 'Style' + ]); /** @@ -2800,30 +2801,30 @@ KML.PLACEMARK_SEQUENCE_ = _ol_xml_.makeStructureNS( * @private */ KML.PLACEMARK_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'ExtendedData': _ol_xml_.makeChildAppender( - KML.writeExtendedData_), - 'MultiGeometry': _ol_xml_.makeChildAppender( - KML.writeMultiGeometry_), - 'LineString': _ol_xml_.makeChildAppender( - KML.writePrimitiveGeometry_), - 'LinearRing': _ol_xml_.makeChildAppender( - KML.writePrimitiveGeometry_), - 'Point': _ol_xml_.makeChildAppender( - KML.writePrimitiveGeometry_), - 'Polygon': _ol_xml_.makeChildAppender(KML.writePolygon_), - 'Style': _ol_xml_.makeChildAppender(KML.writeStyle_), - 'address': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'description': _ol_xml_.makeChildAppender( - XSD.writeStringTextNode), - 'name': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'open': _ol_xml_.makeChildAppender(XSD.writeBooleanTextNode), - 'phoneNumber': _ol_xml_.makeChildAppender( - XSD.writeStringTextNode), - 'styleUrl': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'visibility': _ol_xml_.makeChildAppender( - XSD.writeBooleanTextNode) - }); + KML.NAMESPACE_URIS_, { + 'ExtendedData': _ol_xml_.makeChildAppender( + KML.writeExtendedData_), + 'MultiGeometry': _ol_xml_.makeChildAppender( + KML.writeMultiGeometry_), + 'LineString': _ol_xml_.makeChildAppender( + KML.writePrimitiveGeometry_), + 'LinearRing': _ol_xml_.makeChildAppender( + KML.writePrimitiveGeometry_), + 'Point': _ol_xml_.makeChildAppender( + KML.writePrimitiveGeometry_), + 'Polygon': _ol_xml_.makeChildAppender(KML.writePolygon_), + 'Style': _ol_xml_.makeChildAppender(KML.writeStyle_), + 'address': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'description': _ol_xml_.makeChildAppender( + XSD.writeStringTextNode), + 'name': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'open': _ol_xml_.makeChildAppender(XSD.writeBooleanTextNode), + 'phoneNumber': _ol_xml_.makeChildAppender( + XSD.writeStringTextNode), + 'styleUrl': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'visibility': _ol_xml_.makeChildAppender( + XSD.writeBooleanTextNode) + }); /** @@ -2832,9 +2833,9 @@ KML.PLACEMARK_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.PRIMITIVE_GEOMETRY_SEQUENCE_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, [ - 'extrude', 'tessellate', 'altitudeMode', 'coordinates' - ]); + KML.NAMESPACE_URIS_, [ + 'extrude', 'tessellate', 'altitudeMode', 'coordinates' + ]); /** @@ -2843,13 +2844,13 @@ KML.PRIMITIVE_GEOMETRY_SEQUENCE_ = _ol_xml_.makeStructureNS( * @private */ KML.PRIMITIVE_GEOMETRY_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'extrude': _ol_xml_.makeChildAppender(XSD.writeBooleanTextNode), - 'tessellate': _ol_xml_.makeChildAppender(XSD.writeBooleanTextNode), - 'altitudeMode': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), - 'coordinates': _ol_xml_.makeChildAppender( - KML.writeCoordinatesTextNode_) - }); + KML.NAMESPACE_URIS_, { + 'extrude': _ol_xml_.makeChildAppender(XSD.writeBooleanTextNode), + 'tessellate': _ol_xml_.makeChildAppender(XSD.writeBooleanTextNode), + 'altitudeMode': _ol_xml_.makeChildAppender(XSD.writeStringTextNode), + 'coordinates': _ol_xml_.makeChildAppender( + KML.writeCoordinatesTextNode_) + }); /** @@ -2858,12 +2859,12 @@ KML.PRIMITIVE_GEOMETRY_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.POLYGON_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'outerBoundaryIs': _ol_xml_.makeChildAppender( - KML.writeBoundaryIs_), - 'innerBoundaryIs': _ol_xml_.makeChildAppender( - KML.writeBoundaryIs_) - }); + KML.NAMESPACE_URIS_, { + 'outerBoundaryIs': _ol_xml_.makeChildAppender( + KML.writeBoundaryIs_), + 'innerBoundaryIs': _ol_xml_.makeChildAppender( + KML.writeBoundaryIs_) + }); /** @@ -2872,9 +2873,9 @@ KML.POLYGON_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.POLY_STYLE_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'color': _ol_xml_.makeChildAppender(KML.writeColorTextNode_) - }); + KML.NAMESPACE_URIS_, { + 'color': _ol_xml_.makeChildAppender(KML.writeColorTextNode_) + }); /** @@ -2883,9 +2884,9 @@ KML.POLY_STYLE_SERIALIZERS_ = _ol_xml_.makeStructureNS( * @private */ KML.STYLE_SEQUENCE_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, [ - 'IconStyle', 'LabelStyle', 'LineStyle', 'PolyStyle' - ]); + KML.NAMESPACE_URIS_, [ + 'IconStyle', 'LabelStyle', 'LineStyle', 'PolyStyle' + ]); /** @@ -2894,12 +2895,12 @@ KML.STYLE_SEQUENCE_ = _ol_xml_.makeStructureNS( * @private */ KML.STYLE_SERIALIZERS_ = _ol_xml_.makeStructureNS( - KML.NAMESPACE_URIS_, { - 'IconStyle': _ol_xml_.makeChildAppender(KML.writeIconStyle_), - 'LabelStyle': _ol_xml_.makeChildAppender(KML.writeLabelStyle_), - 'LineStyle': _ol_xml_.makeChildAppender(KML.writeLineStyle_), - 'PolyStyle': _ol_xml_.makeChildAppender(KML.writePolyStyle_) - }); + KML.NAMESPACE_URIS_, { + 'IconStyle': _ol_xml_.makeChildAppender(KML.writeIconStyle_), + 'LabelStyle': _ol_xml_.makeChildAppender(KML.writeLabelStyle_), + 'LineStyle': _ol_xml_.makeChildAppender(KML.writeLineStyle_), + 'PolyStyle': _ol_xml_.makeChildAppender(KML.writePolyStyle_) + }); /** @@ -2912,7 +2913,7 @@ KML.STYLE_SERIALIZERS_ = _ol_xml_.makeStructureNS( */ KML.GX_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) { return _ol_xml_.createElementNS(KML.GX_NAMESPACE_URIS_[0], - 'gx:' + opt_nodeName); + 'gx:' + opt_nodeName); }; @@ -2925,8 +2926,8 @@ KML.GX_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) { * @private */ KML.DOCUMENT_NODE_FACTORY_ = function(value, objectStack, - opt_nodeName) { - var parentNode = objectStack[objectStack.length - 1].node; + opt_nodeName) { + const parentNode = objectStack[objectStack.length - 1].node; return _ol_xml_.createElementNS(parentNode.namespaceURI, 'Placemark'); }; @@ -2940,11 +2941,11 @@ KML.DOCUMENT_NODE_FACTORY_ = function(value, objectStack, * @private */ KML.GEOMETRY_NODE_FACTORY_ = function(value, objectStack, - opt_nodeName) { + opt_nodeName) { if (value) { - var parentNode = objectStack[objectStack.length - 1].node; + const parentNode = objectStack[objectStack.length - 1].node; return _ol_xml_.createElementNS(parentNode.namespaceURI, - KML.GEOMETRY_TYPE_TO_NODENAME_[/** @type {ol.geom.Geometry} */ (value).getType()]); + KML.GEOMETRY_TYPE_TO_NODENAME_[/** @type {ol.geom.Geometry} */ (value).getType()]); } }; @@ -3063,27 +3064,27 @@ KML.prototype.writeFeatures; */ KML.prototype.writeFeaturesNode = function(features, opt_options) { opt_options = this.adaptOptions(opt_options); - var kml = _ol_xml_.createElementNS(KML.NAMESPACE_URIS_[4], 'kml'); - var xmlnsUri = 'http://www.w3.org/2000/xmlns/'; - var xmlSchemaInstanceUri = 'http://www.w3.org/2001/XMLSchema-instance'; + const kml = _ol_xml_.createElementNS(KML.NAMESPACE_URIS_[4], 'kml'); + const xmlnsUri = 'http://www.w3.org/2000/xmlns/'; + const xmlSchemaInstanceUri = 'http://www.w3.org/2001/XMLSchema-instance'; _ol_xml_.setAttributeNS(kml, xmlnsUri, 'xmlns:gx', - KML.GX_NAMESPACE_URIS_[0]); + KML.GX_NAMESPACE_URIS_[0]); _ol_xml_.setAttributeNS(kml, xmlnsUri, 'xmlns:xsi', xmlSchemaInstanceUri); _ol_xml_.setAttributeNS(kml, xmlSchemaInstanceUri, 'xsi:schemaLocation', - KML.SCHEMA_LOCATION_); + KML.SCHEMA_LOCATION_); - var /** @type {ol.XmlNodeStackItem} */ context = {node: kml}; - var properties = {}; + const /** @type {ol.XmlNodeStackItem} */ context = {node: kml}; + const properties = {}; if (features.length > 1) { properties['Document'] = features; } else if (features.length == 1) { properties['Placemark'] = features[0]; } - var orderedKeys = KML.KML_SEQUENCE_[kml.namespaceURI]; - var values = _ol_xml_.makeSequence(properties, orderedKeys); + const orderedKeys = KML.KML_SEQUENCE_[kml.namespaceURI]; + const values = _ol_xml_.makeSequence(properties, orderedKeys); _ol_xml_.pushSerializeAndPop(context, KML.KML_SERIALIZERS_, - _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, [opt_options], orderedKeys, - this); + _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY, values, [opt_options], orderedKeys, + this); return kml; }; export default KML; diff --git a/src/ol/format/MVT.js b/src/ol/format/MVT.js index 50cc47c91e..13ea01bcd4 100644 --- a/src/ol/format/MVT.js +++ b/src/ol/format/MVT.js @@ -30,11 +30,11 @@ import RenderFeature from '../render/Feature.js'; * @param {olx.format.MVTOptions=} opt_options Options. * @api */ -var MVT = function(opt_options) { +const MVT = function(opt_options) { FeatureFormat.call(this); - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @type {ol.proj.Projection} @@ -89,12 +89,12 @@ inherits(MVT, FeatureFormat); MVT.pbfReaders_ = { layers: function(tag, layers, pbf) { if (tag === 3) { - var layer = { + const layer = { keys: [], values: [], features: [] }; - var end = pbf.readVarint() + pbf.pos; + const end = pbf.readVarint() + pbf.pos; pbf.readFields(MVT.pbfReaders_.layer, layer, end); layer.length = layer.features.length; if (layer.length) { @@ -114,8 +114,8 @@ MVT.pbfReaders_ = { } else if (tag === 3) { layer.keys.push(pbf.readString()); } else if (tag === 4) { - var value = null; - var end = pbf.readVarint() + pbf.pos; + let value = null; + const end = pbf.readVarint() + pbf.pos; while (pbf.pos < end) { tag = pbf.readVarint() >> 3; value = tag === 1 ? pbf.readString() : @@ -133,10 +133,10 @@ MVT.pbfReaders_ = { if (tag == 1) { feature.id = pbf.readVarint(); } else if (tag == 2) { - var end = pbf.readVarint() + pbf.pos; + const end = pbf.readVarint() + pbf.pos; while (pbf.pos < end) { - var key = feature.layer.keys[pbf.readVarint()]; - var value = feature.layer.values[pbf.readVarint()]; + const key = feature.layer.keys[pbf.readVarint()]; + const value = feature.layer.values[pbf.readVarint()]; feature.properties[key] = value; } } else if (tag == 3) { @@ -159,9 +159,9 @@ MVT.pbfReaders_ = { */ MVT.readRawFeature_ = function(pbf, layer, i) { pbf.pos = layer.features[i]; - var end = pbf.readVarint() + pbf.pos; + const end = pbf.readVarint() + pbf.pos; - var feature = { + const feature = { layer: layer, type: 0, properties: {} @@ -184,17 +184,17 @@ MVT.readRawFeature_ = function(pbf, layer, i) { MVT.readRawGeometry_ = function(pbf, feature, flatCoordinates, ends) { pbf.pos = feature.geometry; - var end = pbf.readVarint() + pbf.pos; - var cmd = 1; - var length = 0; - var x = 0; - var y = 0; - var coordsLen = 0; - var currentEnd = 0; + const end = pbf.readVarint() + pbf.pos; + let cmd = 1; + let length = 0; + let x = 0; + let y = 0; + let coordsLen = 0; + let currentEnd = 0; while (pbf.pos < end) { if (!length) { - var cmdLen = pbf.readVarint(); + const cmdLen = pbf.readVarint(); cmd = cmdLen & 0x7; length = cmdLen >> 3; } @@ -220,7 +220,7 @@ MVT.readRawGeometry_ = function(pbf, feature, flatCoordinates, ends) { if (coordsLen > currentEnd) { // close polygon flatCoordinates.push( - flatCoordinates[currentEnd], flatCoordinates[currentEnd + 1]); + flatCoordinates[currentEnd], flatCoordinates[currentEnd + 1]); coordsLen += 2; } @@ -247,7 +247,7 @@ MVT.readRawGeometry_ = function(pbf, feature, flatCoordinates, ends) { */ MVT.getGeometryType_ = function(type, numEnds) { /** @type {ol.geom.GeometryType} */ - var geometryType; + let geometryType; if (type === 1) { geometryType = numEnds === 1 ? GeometryType.POINT : GeometryType.MULTI_POINT; @@ -271,32 +271,32 @@ MVT.getGeometryType_ = function(type, numEnds) { * @return {ol.Feature|ol.render.Feature} Feature. */ MVT.prototype.createFeature_ = function(pbf, rawFeature, opt_options) { - var type = rawFeature.type; + const type = rawFeature.type; if (type === 0) { return null; } - var feature; - var id = rawFeature.id; - var values = rawFeature.properties; + let feature; + const id = rawFeature.id; + const values = rawFeature.properties; values[this.layerName_] = rawFeature.layer.name; - var flatCoordinates = []; - var ends = []; + const flatCoordinates = []; + let ends = []; MVT.readRawGeometry_(pbf, rawFeature, flatCoordinates, ends); - var geometryType = MVT.getGeometryType_(type, ends.length); + const geometryType = MVT.getGeometryType_(type, ends.length); if (this.featureClass_ === RenderFeature) { feature = new this.featureClass_(geometryType, flatCoordinates, ends, values, id); } else { - var geom; + let geom; if (geometryType == GeometryType.POLYGON) { - var endss = []; - var offset = 0; - var prevEndIndex = 0; - for (var i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; + const endss = []; + let offset = 0; + let prevEndIndex = 0; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; if (!_ol_geom_flat_orient_.linearRingIsClockwise(flatCoordinates, offset, end, 2)) { endss.push(ends.slice(prevEndIndex, i)); prevEndIndex = i; @@ -322,7 +322,7 @@ MVT.prototype.createFeature_ = function(pbf, rawFeature, opt_options) { if (this.geometryName_) { feature.setGeometryName(this.geometryName_); } - var geometry = transformWithOptions(geom, false, this.adaptOptions(opt_options)); + const geometry = transformWithOptions(geom, false, this.adaptOptions(opt_options)); feature.setGeometry(geometry); feature.setId(id); feature.setProperties(values); @@ -354,22 +354,21 @@ MVT.prototype.getType = function() { * @api */ MVT.prototype.readFeatures = function(source, opt_options) { - var layers = this.layers_; + const layers = this.layers_; - var pbf = new PBF(/** @type {ArrayBuffer} */ (source)); - var pbfLayers = pbf.readFields(MVT.pbfReaders_.layers, {}); + const pbf = new PBF(/** @type {ArrayBuffer} */ (source)); + const pbfLayers = pbf.readFields(MVT.pbfReaders_.layers, {}); /** @type {Array.} */ - var features = []; - var pbfLayer; - for (var name in pbfLayers) { + const features = []; + let pbfLayer; + for (const name in pbfLayers) { if (layers && layers.indexOf(name) == -1) { continue; } pbfLayer = pbfLayers[name]; - var rawFeature; - for (var i = 0, ii = pbfLayer.length; i < ii; ++i) { - rawFeature = MVT.readRawFeature_(pbf, pbfLayer, i); + for (let i = 0, ii = pbfLayer.length; i < ii; ++i) { + const rawFeature = MVT.readRawFeature_(pbf, pbfLayer, i); features.push(this.createFeature_(pbf, rawFeature)); } this.extent_ = pbfLayer ? [0, 0, pbfLayer.extent, pbfLayer.extent] : null; diff --git a/src/ol/format/OSMXML.js b/src/ol/format/OSMXML.js index 7fc3e17e42..a26536dbf5 100644 --- a/src/ol/format/OSMXML.js +++ b/src/ol/format/OSMXML.js @@ -24,7 +24,7 @@ import _ol_xml_ from '../xml.js'; * @extends {ol.format.XMLFeature} * @api */ -var OSMXML = function() { +const OSMXML = function() { XMLFeature.call(this); /** @@ -42,23 +42,23 @@ inherits(OSMXML, XMLFeature); * @private */ OSMXML.readNode_ = function(node, objectStack) { - var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]); - var state = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var id = node.getAttribute('id'); + const options = /** @type {olx.format.ReadOptions} */ (objectStack[0]); + const state = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const id = node.getAttribute('id'); /** @type {ol.Coordinate} */ - var coordinates = [ + const coordinates = [ parseFloat(node.getAttribute('lon')), parseFloat(node.getAttribute('lat')) ]; state.nodes[id] = coordinates; - var values = _ol_xml_.pushParseAndPop({ + const values = _ol_xml_.pushParseAndPop({ tags: {} }, OSMXML.NODE_PARSERS_, node, objectStack); if (!_ol_obj_.isEmpty(values.tags)) { - var geometry = new Point(coordinates); + const geometry = new Point(coordinates); transformWithOptions(geometry, false, options); - var feature = new Feature(geometry); + const feature = new Feature(geometry); feature.setId(id); feature.setProperties(values.tags); state.features.push(feature); @@ -72,13 +72,13 @@ OSMXML.readNode_ = function(node, objectStack) { * @private */ OSMXML.readWay_ = function(node, objectStack) { - var id = node.getAttribute('id'); - var values = _ol_xml_.pushParseAndPop({ + const id = node.getAttribute('id'); + const values = _ol_xml_.pushParseAndPop({ id: id, ndrefs: [], tags: {} }, OSMXML.WAY_PARSERS_, node, objectStack); - var state = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const state = /** @type {Object} */ (objectStack[objectStack.length - 1]); state.ways.push(values); }; @@ -89,7 +89,7 @@ OSMXML.readWay_ = function(node, objectStack) { * @private */ OSMXML.readNd_ = function(node, objectStack) { - var values = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const values = /** @type {Object} */ (objectStack[objectStack.length - 1]); values.ndrefs.push(node.getAttribute('ref')); }; @@ -100,7 +100,7 @@ OSMXML.readNd_ = function(node, objectStack) { * @private */ OSMXML.readTag_ = function(node, objectStack) { - var values = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const values = /** @type {Object} */ (objectStack[objectStack.length - 1]); values.tags[node.getAttribute('k')] = node.getAttribute('v'); }; @@ -121,10 +121,10 @@ OSMXML.NAMESPACE_URIS_ = [ * @private */ OSMXML.WAY_PARSERS_ = _ol_xml_.makeStructureNS( - OSMXML.NAMESPACE_URIS_, { - 'nd': OSMXML.readNd_, - 'tag': OSMXML.readTag_ - }); + OSMXML.NAMESPACE_URIS_, { + 'nd': OSMXML.readNd_, + 'tag': OSMXML.readTag_ + }); /** @@ -133,10 +133,10 @@ OSMXML.WAY_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OSMXML.PARSERS_ = _ol_xml_.makeStructureNS( - OSMXML.NAMESPACE_URIS_, { - 'node': OSMXML.readNode_, - 'way': OSMXML.readWay_ - }); + OSMXML.NAMESPACE_URIS_, { + 'node': OSMXML.readNode_, + 'way': OSMXML.readWay_ + }); /** @@ -145,9 +145,9 @@ OSMXML.PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OSMXML.NODE_PARSERS_ = _ol_xml_.makeStructureNS( - OSMXML.NAMESPACE_URIS_, { - 'tag': OSMXML.readTag_ - }); + OSMXML.NAMESPACE_URIS_, { + 'tag': OSMXML.readTag_ + }); /** @@ -166,34 +166,34 @@ OSMXML.prototype.readFeatures; * @inheritDoc */ OSMXML.prototype.readFeaturesFromNode = function(node, opt_options) { - var options = this.getReadOptions(node, opt_options); + const options = this.getReadOptions(node, opt_options); if (node.localName == 'osm') { - var state = _ol_xml_.pushParseAndPop({ + const state = _ol_xml_.pushParseAndPop({ nodes: {}, ways: [], features: [] }, OSMXML.PARSERS_, node, [options]); // parse nodes in ways - for (var j = 0; j < state.ways.length; j++) { - var values = /** @type {Object} */ (state.ways[j]); + for (let j = 0; j < state.ways.length; j++) { + const values = /** @type {Object} */ (state.ways[j]); /** @type {Array.} */ - var flatCoordinates = []; - for (var i = 0, ii = values.ndrefs.length; i < ii; i++) { - var point = state.nodes[values.ndrefs[i]]; + const flatCoordinates = []; + for (let i = 0, ii = values.ndrefs.length; i < ii; i++) { + const point = state.nodes[values.ndrefs[i]]; extend(flatCoordinates, point); } - var geometry; + let geometry; if (values.ndrefs[0] == values.ndrefs[values.ndrefs.length - 1]) { // closed way geometry = new Polygon(null); geometry.setFlatCoordinates(GeometryLayout.XY, flatCoordinates, - [flatCoordinates.length]); + [flatCoordinates.length]); } else { geometry = new LineString(null); geometry.setFlatCoordinates(GeometryLayout.XY, flatCoordinates); } transformWithOptions(geometry, false, options); - var feature = new Feature(geometry); + const feature = new Feature(geometry); feature.setId(values.id); feature.setProperties(values.tags); state.features.push(feature); diff --git a/src/ol/format/OWS.js b/src/ol/format/OWS.js index ae46fd59d4..9e2962b375 100644 --- a/src/ol/format/OWS.js +++ b/src/ol/format/OWS.js @@ -11,7 +11,7 @@ import _ol_xml_ from '../xml.js'; * @constructor * @extends {ol.format.XML} */ -var OWS = function() { +const OWS = function() { XML.call(this); }; @@ -22,7 +22,7 @@ inherits(OWS, XML); * @inheritDoc */ OWS.prototype.readFromDocument = function(doc) { - for (var n = doc.firstChild; n; n = n.nextSibling) { + for (let n = doc.firstChild; n; n = n.nextSibling) { if (n.nodeType == Node.ELEMENT_NODE) { return this.readFromNode(n); } @@ -35,8 +35,8 @@ OWS.prototype.readFromDocument = function(doc) { * @inheritDoc */ OWS.prototype.readFromNode = function(node) { - var owsObject = _ol_xml_.pushParseAndPop({}, - OWS.PARSERS_, node, []); + const owsObject = _ol_xml_.pushParseAndPop({}, + OWS.PARSERS_, node, []); return owsObject ? owsObject : null; }; @@ -49,7 +49,7 @@ OWS.prototype.readFromNode = function(node) { */ OWS.readAddress_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - OWS.ADDRESS_PARSERS_, node, objectStack); + OWS.ADDRESS_PARSERS_, node, objectStack); }; @@ -61,7 +61,7 @@ OWS.readAddress_ = function(node, objectStack) { */ OWS.readAllowedValues_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - OWS.ALLOWED_VALUES_PARSERS_, node, objectStack); + OWS.ALLOWED_VALUES_PARSERS_, node, objectStack); }; @@ -72,13 +72,13 @@ OWS.readAllowedValues_ = function(node, objectStack) { * @return {Object|undefined} The constraint. */ OWS.readConstraint_ = function(node, objectStack) { - var name = node.getAttribute('name'); + const name = node.getAttribute('name'); if (!name) { return undefined; } return _ol_xml_.pushParseAndPop({'name': name}, - OWS.CONSTRAINT_PARSERS_, node, - objectStack); + OWS.CONSTRAINT_PARSERS_, node, + objectStack); }; @@ -90,7 +90,7 @@ OWS.readConstraint_ = function(node, objectStack) { */ OWS.readContactInfo_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - OWS.CONTACT_INFO_PARSERS_, node, objectStack); + OWS.CONTACT_INFO_PARSERS_, node, objectStack); }; @@ -102,7 +102,7 @@ OWS.readContactInfo_ = function(node, objectStack) { */ OWS.readDcp_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - OWS.DCP_PARSERS_, node, objectStack); + OWS.DCP_PARSERS_, node, objectStack); }; @@ -113,12 +113,12 @@ OWS.readDcp_ = function(node, objectStack) { * @return {Object|undefined} The GET object. */ OWS.readGet_ = function(node, objectStack) { - var href = XLink.readHref(node); + const href = XLink.readHref(node); if (!href) { return undefined; } return _ol_xml_.pushParseAndPop({'href': href}, - OWS.REQUEST_METHOD_PARSERS_, node, objectStack); + OWS.REQUEST_METHOD_PARSERS_, node, objectStack); }; @@ -130,7 +130,7 @@ OWS.readGet_ = function(node, objectStack) { */ OWS.readHttp_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, OWS.HTTP_PARSERS_, - node, objectStack); + node, objectStack); }; @@ -141,13 +141,13 @@ OWS.readHttp_ = function(node, objectStack) { * @return {Object|undefined} The operation. */ OWS.readOperation_ = function(node, objectStack) { - var name = node.getAttribute('name'); - var value = _ol_xml_.pushParseAndPop({}, - OWS.OPERATION_PARSERS_, node, objectStack); + const name = node.getAttribute('name'); + const value = _ol_xml_.pushParseAndPop({}, + OWS.OPERATION_PARSERS_, node, objectStack); if (!value) { return undefined; } - var object = /** @type {Object} */ + const object = /** @type {Object} */ (objectStack[objectStack.length - 1]); object[name] = value; }; @@ -160,10 +160,10 @@ OWS.readOperation_ = function(node, objectStack) { * @return {Object|undefined} The operations metadata. */ OWS.readOperationsMetadata_ = function(node, - objectStack) { + objectStack) { return _ol_xml_.pushParseAndPop({}, - OWS.OPERATIONS_METADATA_PARSERS_, node, - objectStack); + OWS.OPERATIONS_METADATA_PARSERS_, node, + objectStack); }; @@ -175,7 +175,7 @@ OWS.readOperationsMetadata_ = function(node, */ OWS.readPhone_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - OWS.PHONE_PARSERS_, node, objectStack); + OWS.PHONE_PARSERS_, node, objectStack); }; @@ -186,10 +186,10 @@ OWS.readPhone_ = function(node, objectStack) { * @return {Object|undefined} The service identification. */ OWS.readServiceIdentification_ = function(node, - objectStack) { + objectStack) { return _ol_xml_.pushParseAndPop( - {}, OWS.SERVICE_IDENTIFICATION_PARSERS_, node, - objectStack); + {}, OWS.SERVICE_IDENTIFICATION_PARSERS_, node, + objectStack); }; @@ -201,8 +201,8 @@ OWS.readServiceIdentification_ = function(node, */ OWS.readServiceContact_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, OWS.SERVICE_CONTACT_PARSERS_, node, - objectStack); + {}, OWS.SERVICE_CONTACT_PARSERS_, node, + objectStack); }; @@ -214,8 +214,8 @@ OWS.readServiceContact_ = function(node, objectStack) { */ OWS.readServiceProvider_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, OWS.SERVICE_PROVIDER_PARSERS_, node, - objectStack); + {}, OWS.SERVICE_PROVIDER_PARSERS_, node, + objectStack); }; @@ -247,14 +247,14 @@ OWS.NAMESPACE_URIS_ = [ * @private */ OWS.PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'ServiceIdentification': _ol_xml_.makeObjectPropertySetter( - OWS.readServiceIdentification_), - 'ServiceProvider': _ol_xml_.makeObjectPropertySetter( - OWS.readServiceProvider_), - 'OperationsMetadata': _ol_xml_.makeObjectPropertySetter( - OWS.readOperationsMetadata_) - }); + OWS.NAMESPACE_URIS_, { + 'ServiceIdentification': _ol_xml_.makeObjectPropertySetter( + OWS.readServiceIdentification_), + 'ServiceProvider': _ol_xml_.makeObjectPropertySetter( + OWS.readServiceProvider_), + 'OperationsMetadata': _ol_xml_.makeObjectPropertySetter( + OWS.readOperationsMetadata_) + }); /** @@ -263,17 +263,17 @@ OWS.PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OWS.ADDRESS_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'DeliveryPoint': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'City': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'AdministrativeArea': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'PostalCode': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Country': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'ElectronicMailAddress': _ol_xml_.makeObjectPropertySetter( - XSD.readString) - }); + OWS.NAMESPACE_URIS_, { + 'DeliveryPoint': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'City': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'AdministrativeArea': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'PostalCode': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Country': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'ElectronicMailAddress': _ol_xml_.makeObjectPropertySetter( + XSD.readString) + }); /** @@ -282,9 +282,9 @@ OWS.ADDRESS_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OWS.ALLOWED_VALUES_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'Value': _ol_xml_.makeObjectPropertyPusher(OWS.readValue_) - }); + OWS.NAMESPACE_URIS_, { + 'Value': _ol_xml_.makeObjectPropertyPusher(OWS.readValue_) + }); /** @@ -293,10 +293,10 @@ OWS.ALLOWED_VALUES_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OWS.CONSTRAINT_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'AllowedValues': _ol_xml_.makeObjectPropertySetter( - OWS.readAllowedValues_) - }); + OWS.NAMESPACE_URIS_, { + 'AllowedValues': _ol_xml_.makeObjectPropertySetter( + OWS.readAllowedValues_) + }); /** @@ -305,10 +305,10 @@ OWS.CONSTRAINT_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OWS.CONTACT_INFO_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'Phone': _ol_xml_.makeObjectPropertySetter(OWS.readPhone_), - 'Address': _ol_xml_.makeObjectPropertySetter(OWS.readAddress_) - }); + OWS.NAMESPACE_URIS_, { + 'Phone': _ol_xml_.makeObjectPropertySetter(OWS.readPhone_), + 'Address': _ol_xml_.makeObjectPropertySetter(OWS.readAddress_) + }); /** @@ -317,9 +317,9 @@ OWS.CONTACT_INFO_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OWS.DCP_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'HTTP': _ol_xml_.makeObjectPropertySetter(OWS.readHttp_) - }); + OWS.NAMESPACE_URIS_, { + 'HTTP': _ol_xml_.makeObjectPropertySetter(OWS.readHttp_) + }); /** @@ -328,10 +328,10 @@ OWS.DCP_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OWS.HTTP_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'Get': _ol_xml_.makeObjectPropertyPusher(OWS.readGet_), - 'Post': undefined // TODO - }); + OWS.NAMESPACE_URIS_, { + 'Get': _ol_xml_.makeObjectPropertyPusher(OWS.readGet_), + 'Post': undefined // TODO + }); /** @@ -340,9 +340,9 @@ OWS.HTTP_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OWS.OPERATION_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'DCP': _ol_xml_.makeObjectPropertySetter(OWS.readDcp_) - }); + OWS.NAMESPACE_URIS_, { + 'DCP': _ol_xml_.makeObjectPropertySetter(OWS.readDcp_) + }); /** @@ -351,9 +351,9 @@ OWS.OPERATION_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OWS.OPERATIONS_METADATA_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'Operation': OWS.readOperation_ - }); + OWS.NAMESPACE_URIS_, { + 'Operation': OWS.readOperation_ + }); /** @@ -362,10 +362,10 @@ OWS.OPERATIONS_METADATA_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OWS.PHONE_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'Voice': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Facsimile': _ol_xml_.makeObjectPropertySetter(XSD.readString) - }); + OWS.NAMESPACE_URIS_, { + 'Voice': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Facsimile': _ol_xml_.makeObjectPropertySetter(XSD.readString) + }); /** @@ -374,10 +374,10 @@ OWS.PHONE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ OWS.REQUEST_METHOD_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'Constraint': _ol_xml_.makeObjectPropertyPusher( - OWS.readConstraint_) - }); + OWS.NAMESPACE_URIS_, { + 'Constraint': _ol_xml_.makeObjectPropertyPusher( + OWS.readConstraint_) + }); /** @@ -387,13 +387,13 @@ OWS.REQUEST_METHOD_PARSERS_ = _ol_xml_.makeStructureNS( */ OWS.SERVICE_CONTACT_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'IndividualName': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'PositionName': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'ContactInfo': _ol_xml_.makeObjectPropertySetter( - OWS.readContactInfo_) - }); + OWS.NAMESPACE_URIS_, { + 'IndividualName': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'PositionName': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'ContactInfo': _ol_xml_.makeObjectPropertySetter( + OWS.readContactInfo_) + }); /** @@ -403,15 +403,15 @@ OWS.SERVICE_CONTACT_PARSERS_ = */ OWS.SERVICE_IDENTIFICATION_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'Abstract': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'AccessConstraints': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Fees': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Title': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'ServiceTypeVersion': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'ServiceType': _ol_xml_.makeObjectPropertySetter(XSD.readString) - }); + OWS.NAMESPACE_URIS_, { + 'Abstract': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'AccessConstraints': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Fees': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Title': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'ServiceTypeVersion': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'ServiceType': _ol_xml_.makeObjectPropertySetter(XSD.readString) + }); /** @@ -421,10 +421,10 @@ OWS.SERVICE_IDENTIFICATION_PARSERS_ = */ OWS.SERVICE_PROVIDER_PARSERS_ = _ol_xml_.makeStructureNS( - OWS.NAMESPACE_URIS_, { - 'ProviderName': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'ProviderSite': _ol_xml_.makeObjectPropertySetter(XLink.readHref), - 'ServiceContact': _ol_xml_.makeObjectPropertySetter( - OWS.readServiceContact_) - }); + OWS.NAMESPACE_URIS_, { + 'ProviderName': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'ProviderSite': _ol_xml_.makeObjectPropertySetter(XLink.readHref), + 'ServiceContact': _ol_xml_.makeObjectPropertySetter( + OWS.readServiceContact_) + }); export default OWS; diff --git a/src/ol/format/Polyline.js b/src/ol/format/Polyline.js index 253a8c2275..8907f773e9 100644 --- a/src/ol/format/Polyline.js +++ b/src/ol/format/Polyline.js @@ -24,9 +24,9 @@ import {get as getProjection} from '../proj.js'; * Optional configuration object. * @api */ -var Polyline = function(opt_options) { +const Polyline = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; TextFeature.call(this); @@ -66,19 +66,19 @@ inherits(Polyline, TextFeature); * @api */ export function encodeDeltas(numbers, stride, opt_factor) { - var factor = opt_factor ? opt_factor : 1e5; - var d; + const factor = opt_factor ? opt_factor : 1e5; + let d; - var lastNumbers = new Array(stride); + const lastNumbers = new Array(stride); for (d = 0; d < stride; ++d) { lastNumbers[d] = 0; } - var i, ii; + let i, ii; for (i = 0, ii = numbers.length; i < ii;) { for (d = 0; d < stride; ++d, ++i) { - var num = numbers[i]; - var delta = num - lastNumbers[d]; + const num = numbers[i]; + const delta = num - lastNumbers[d]; lastNumbers[d] = num; numbers[i] = delta; @@ -101,18 +101,18 @@ export function encodeDeltas(numbers, stride, opt_factor) { * @api */ export function decodeDeltas(encoded, stride, opt_factor) { - var factor = opt_factor ? opt_factor : 1e5; - var d; + const factor = opt_factor ? opt_factor : 1e5; + let d; /** @type {Array.} */ - var lastNumbers = new Array(stride); + const lastNumbers = new Array(stride); for (d = 0; d < stride; ++d) { lastNumbers[d] = 0; } - var numbers = decodeFloats(encoded, factor); + const numbers = decodeFloats(encoded, factor); - var i, ii; + let i, ii; for (i = 0, ii = numbers.length; i < ii;) { for (d = 0; d < stride; ++d, ++i) { lastNumbers[d] += numbers[i]; @@ -138,8 +138,8 @@ export function decodeDeltas(encoded, stride, opt_factor) { * @api */ export function encodeFloats(numbers, opt_factor) { - var factor = opt_factor ? opt_factor : 1e5; - var i, ii; + const factor = opt_factor ? opt_factor : 1e5; + let i, ii; for (i = 0, ii = numbers.length; i < ii; ++i) { numbers[i] = Math.round(numbers[i] * factor); } @@ -158,9 +158,9 @@ export function encodeFloats(numbers, opt_factor) { * @api */ export function decodeFloats(encoded, opt_factor) { - var factor = opt_factor ? opt_factor : 1e5; - var numbers = decodeSignedIntegers(encoded); - var i, ii; + const factor = opt_factor ? opt_factor : 1e5; + const numbers = decodeSignedIntegers(encoded); + let i, ii; for (i = 0, ii = numbers.length; i < ii; ++i) { numbers[i] /= factor; } @@ -177,9 +177,9 @@ export function decodeFloats(encoded, opt_factor) { * @return {string} The encoded string. */ export function encodeSignedIntegers(numbers) { - var i, ii; + let i, ii; for (i = 0, ii = numbers.length; i < ii; ++i) { - var num = numbers[i]; + const num = numbers[i]; numbers[i] = (num < 0) ? ~(num << 1) : (num << 1); } return encodeUnsignedIntegers(numbers); @@ -193,10 +193,10 @@ export function encodeSignedIntegers(numbers) { * @return {Array.} A list of signed integers. */ export function decodeSignedIntegers(encoded) { - var numbers = decodeUnsignedIntegers(encoded); - var i, ii; + const numbers = decodeUnsignedIntegers(encoded); + let i, ii; for (i = 0, ii = numbers.length; i < ii; ++i) { - var num = numbers[i]; + const num = numbers[i]; numbers[i] = (num & 1) ? ~(num >> 1) : (num >> 1); } return numbers; @@ -210,8 +210,8 @@ export function decodeSignedIntegers(encoded) { * @return {string} The encoded string. */ export function encodeUnsignedIntegers(numbers) { - var encoded = ''; - var i, ii; + let encoded = ''; + let i, ii; for (i = 0, ii = numbers.length; i < ii; ++i) { encoded += encodeUnsignedInteger(numbers[i]); } @@ -226,12 +226,12 @@ export function encodeUnsignedIntegers(numbers) { * @return {Array.} A list of unsigned integers. */ export function decodeUnsignedIntegers(encoded) { - var numbers = []; - var current = 0; - var shift = 0; - var i, ii; + const numbers = []; + let current = 0; + let shift = 0; + let i, ii; for (i = 0, ii = encoded.length; i < ii; ++i) { - var b = encoded.charCodeAt(i) - 63; + const b = encoded.charCodeAt(i) - 63; current |= (b & 0x1f) << shift; if (b < 0x20) { numbers.push(current); @@ -252,7 +252,7 @@ export function decodeUnsignedIntegers(encoded) { * @return {string} The encoded string. */ export function encodeUnsignedInteger(num) { - var value, encoded = ''; + let value, encoded = ''; while (num >= 0x20) { value = (0x20 | (num & 0x1f)) + 63; encoded += String.fromCharCode(value); @@ -281,7 +281,7 @@ Polyline.prototype.readFeature; * @inheritDoc */ Polyline.prototype.readFeatureFromText = function(text, opt_options) { - var geometry = this.readGeometryFromText(text, opt_options); + const geometry = this.readGeometryFromText(text, opt_options); return new Feature(geometry); }; @@ -303,7 +303,7 @@ Polyline.prototype.readFeatures; * @inheritDoc */ Polyline.prototype.readFeaturesFromText = function(text, opt_options) { - var feature = this.readFeatureFromText(text, opt_options); + const feature = this.readFeatureFromText(text, opt_options); return [feature]; }; @@ -324,17 +324,17 @@ Polyline.prototype.readGeometry; * @inheritDoc */ Polyline.prototype.readGeometryFromText = function(text, opt_options) { - var stride = getStrideForLayout(this.geometryLayout_); - var flatCoordinates = decodeDeltas(text, stride, this.factor_); + const stride = getStrideForLayout(this.geometryLayout_); + const flatCoordinates = decodeDeltas(text, stride, this.factor_); _ol_geom_flat_flip_.flipXY( - flatCoordinates, 0, flatCoordinates.length, stride, flatCoordinates); - var coordinates = _ol_geom_flat_inflate_.coordinates( - flatCoordinates, 0, flatCoordinates.length, stride); + flatCoordinates, 0, flatCoordinates.length, stride, flatCoordinates); + const coordinates = _ol_geom_flat_inflate_.coordinates( + flatCoordinates, 0, flatCoordinates.length, stride); return ( /** @type {ol.geom.Geometry} */ transformWithOptions( - new LineString(coordinates, this.geometryLayout_), false, - this.adaptOptions(opt_options)) + new LineString(coordinates, this.geometryLayout_), false, + this.adaptOptions(opt_options)) ); }; @@ -354,7 +354,7 @@ Polyline.prototype.readProjection; * @inheritDoc */ Polyline.prototype.writeFeatureText = function(feature, opt_options) { - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); if (geometry) { return this.writeGeometryText(geometry, opt_options); } else { @@ -390,10 +390,10 @@ Polyline.prototype.writeGeometry; Polyline.prototype.writeGeometryText = function(geometry, opt_options) { geometry = /** @type {ol.geom.LineString} */ (transformWithOptions(geometry, true, this.adaptOptions(opt_options))); - var flatCoordinates = geometry.getFlatCoordinates(); - var stride = geometry.getStride(); + const flatCoordinates = geometry.getFlatCoordinates(); + const stride = geometry.getStride(); _ol_geom_flat_flip_.flipXY( - flatCoordinates, 0, flatCoordinates.length, stride, flatCoordinates); + flatCoordinates, 0, flatCoordinates.length, stride, flatCoordinates); return encodeDeltas(flatCoordinates, stride, this.factor_); }; export default Polyline; diff --git a/src/ol/format/TextFeature.js b/src/ol/format/TextFeature.js index db033be3af..d2fdbe117d 100644 --- a/src/ol/format/TextFeature.js +++ b/src/ol/format/TextFeature.js @@ -15,7 +15,7 @@ import FormatType from '../format/FormatType.js'; * @abstract * @extends {ol.format.Feature} */ -var TextFeature = function() { +const TextFeature = function() { FeatureFormat.call(this); }; diff --git a/src/ol/format/TopoJSON.js b/src/ol/format/TopoJSON.js index ffdf8f6713..5e07f9e591 100644 --- a/src/ol/format/TopoJSON.js +++ b/src/ol/format/TopoJSON.js @@ -22,9 +22,9 @@ import {get as getProjection} from '../proj.js'; * @param {olx.format.TopoJSONOptions=} opt_options Options. * @api */ -var TopoJSON = function(opt_options) { +const TopoJSON = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; JSONFeature.call(this); @@ -44,8 +44,8 @@ var TopoJSON = function(opt_options) { * @inheritDoc */ this.defaultDataProjection = getProjection( - options.defaultDataProjection ? - options.defaultDataProjection : 'EPSG:4326'); + options.defaultDataProjection ? + options.defaultDataProjection : 'EPSG:4326'); }; @@ -56,7 +56,7 @@ inherits(TopoJSON, JSONFeature); * @const * @type {Object.} */ -var GEOMETRY_READERS = { +const GEOMETRY_READERS = { 'Point': readPointGeometry, 'LineString': readLineStringGeometry, 'Polygon': readPolygonGeometry, @@ -76,10 +76,10 @@ var GEOMETRY_READERS = { */ function concatenateArcs(indices, arcs) { /** @type {Array.} */ - var coordinates = []; - var index, arc; - var i, ii; - var j, jj; + const coordinates = []; + let index, arc; + let i, ii; + let j, jj; for (i = 0, ii = indices.length; i < ii; ++i) { index = indices[i]; if (i > 0) { @@ -112,7 +112,7 @@ function concatenateArcs(indices, arcs) { * @return {ol.geom.Point} Geometry. */ function readPointGeometry(object, scale, translate) { - var coordinates = object.coordinates; + const coordinates = object.coordinates; if (scale && translate) { transformVertex(coordinates, scale, translate); } @@ -129,8 +129,8 @@ function readPointGeometry(object, scale, translate) { * @return {ol.geom.MultiPoint} Geometry. */ function readMultiPointGeometry(object, scale, translate) { - var coordinates = object.coordinates; - var i, ii; + const coordinates = object.coordinates; + let i, ii; if (scale && translate) { for (i = 0, ii = coordinates.length; i < ii; ++i) { transformVertex(coordinates[i], scale, translate); @@ -148,7 +148,7 @@ function readMultiPointGeometry(object, scale, translate) { * @return {ol.geom.LineString} Geometry. */ function readLineStringGeometry(object, arcs) { - var coordinates = concatenateArcs(object.arcs, arcs); + const coordinates = concatenateArcs(object.arcs, arcs); return new LineString(coordinates); } @@ -161,8 +161,8 @@ function readLineStringGeometry(object, arcs) { * @return {ol.geom.MultiLineString} Geometry. */ function readMultiLineStringGeometry(object, arcs) { - var coordinates = []; - var i, ii; + const coordinates = []; + let i, ii; for (i = 0, ii = object.arcs.length; i < ii; ++i) { coordinates[i] = concatenateArcs(object.arcs[i], arcs); } @@ -178,8 +178,8 @@ function readMultiLineStringGeometry(object, arcs) { * @return {ol.geom.Polygon} Geometry. */ function readPolygonGeometry(object, arcs) { - var coordinates = []; - var i, ii; + const coordinates = []; + let i, ii; for (i = 0, ii = object.arcs.length; i < ii; ++i) { coordinates[i] = concatenateArcs(object.arcs[i], arcs); } @@ -195,9 +195,9 @@ function readPolygonGeometry(object, arcs) { * @return {ol.geom.MultiPolygon} Geometry. */ function readMultiPolygonGeometry(object, arcs) { - var coordinates = []; - var polyArray, ringCoords, j, jj; - var i, ii; + const coordinates = []; + let polyArray, ringCoords, j, jj; + let i, ii; for (i = 0, ii = object.arcs.length; i < ii; ++i) { // for each polygon polyArray = object.arcs[i]; @@ -227,12 +227,12 @@ function readMultiPolygonGeometry(object, arcs) { * @return {Array.} Array of features. */ function readFeaturesFromGeometryCollection(collection, arcs, scale, translate, property, name, opt_options) { - var geometries = collection.geometries; - var features = []; - var i, ii; + const geometries = collection.geometries; + const features = []; + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { features[i] = readFeatureFromGeometry( - geometries[i], arcs, scale, translate, property, name, opt_options); + geometries[i], arcs, scale, translate, property, name, opt_options); } return features; } @@ -252,21 +252,21 @@ function readFeaturesFromGeometryCollection(collection, arcs, scale, translate, * @return {ol.Feature} Feature. */ function readFeatureFromGeometry(object, arcs, scale, translate, property, name, opt_options) { - var geometry; - var type = object.type; - var geometryReader = GEOMETRY_READERS[type]; + let geometry; + const type = object.type; + const geometryReader = GEOMETRY_READERS[type]; if ((type === 'Point') || (type === 'MultiPoint')) { geometry = geometryReader(object, scale, translate); } else { geometry = geometryReader(object, arcs); } - var feature = new Feature(); + const feature = new Feature(); feature.setGeometry(/** @type {ol.geom.Geometry} */ ( transformWithOptions(geometry, false, opt_options))); if (object.id !== undefined) { feature.setId(object.id); } - var properties = object.properties; + let properties = object.properties; if (property) { if (!properties) { properties = {}; @@ -295,24 +295,24 @@ TopoJSON.prototype.readFeatures; * @inheritDoc */ TopoJSON.prototype.readFeaturesFromObject = function( - object, opt_options) { + object, opt_options) { if (object.type == 'Topology') { - var topoJSONTopology = /** @type {TopoJSONTopology} */ (object); - var transform, scale = null, translate = null; + const topoJSONTopology = /** @type {TopoJSONTopology} */ (object); + let transform, scale = null, translate = null; if (topoJSONTopology.transform) { transform = topoJSONTopology.transform; scale = transform.scale; translate = transform.translate; } - var arcs = topoJSONTopology.arcs; + const arcs = topoJSONTopology.arcs; if (transform) { transformArcs(arcs, scale, translate); } /** @type {Array.} */ - var features = []; - var topoJSONFeatures = topoJSONTopology.objects; - var property = this.layerName_; - var objectName, feature; + const features = []; + const topoJSONFeatures = topoJSONTopology.objects; + const property = this.layerName_; + let objectName, feature; for (objectName in topoJSONFeatures) { if (this.layers_ && this.layers_.indexOf(objectName) == -1) { continue; @@ -320,11 +320,11 @@ TopoJSON.prototype.readFeaturesFromObject = function( if (topoJSONFeatures[objectName].type === 'GeometryCollection') { feature = /** @type {TopoJSONGeometryCollection} */ (topoJSONFeatures[objectName]); features.push.apply(features, readFeaturesFromGeometryCollection( - feature, arcs, scale, translate, property, objectName, opt_options)); + feature, arcs, scale, translate, property, objectName, opt_options)); } else { feature = /** @type {TopoJSONGeometry} */ (topoJSONFeatures[objectName]); features.push(readFeatureFromGeometry( - feature, arcs, scale, translate, property, objectName, opt_options)); + feature, arcs, scale, translate, property, objectName, opt_options)); } } return features; @@ -343,7 +343,7 @@ TopoJSON.prototype.readFeaturesFromObject = function( * @param {Array.} translate Translation for each dimension. */ function transformArcs(arcs, scale, translate) { - var i, ii; + let i, ii; for (i = 0, ii = arcs.length; i < ii; ++i) { transformArc(arcs[i], scale, translate); } @@ -358,10 +358,10 @@ function transformArcs(arcs, scale, translate) { * @param {Array.} translate Translation for each dimension. */ function transformArc(arc, scale, translate) { - var x = 0; - var y = 0; - var vertex; - var i, ii; + let x = 0; + let y = 0; + let vertex; + let i, ii; for (i = 0, ii = arc.length; i < ii; ++i) { vertex = arc[i]; x += vertex[0]; diff --git a/src/ol/format/WFS.js b/src/ol/format/WFS.js index 1db5e78776..724a51917d 100644 --- a/src/ol/format/WFS.js +++ b/src/ol/format/WFS.js @@ -27,8 +27,8 @@ import _ol_xml_ from '../xml.js'; * @extends {ol.format.XMLFeature} * @api */ -var WFS = function(opt_options) { - var options = opt_options ? opt_options : {}; +const WFS = function(opt_options) { + const options = opt_options ? opt_options : {}; /** * @private @@ -149,19 +149,19 @@ WFS.prototype.readFeatures; * @inheritDoc */ WFS.prototype.readFeaturesFromNode = function(node, opt_options) { - var context = /** @type {ol.XmlNodeStackItem} */ ({ + const context = /** @type {ol.XmlNodeStackItem} */ ({ 'featureType': this.featureType_, 'featureNS': this.featureNS_ }); _ol_obj_.assign(context, this.getReadOptions(node, - opt_options ? opt_options : {})); - var objectStack = [context]; + opt_options ? opt_options : {})); + const objectStack = [context]; this.gmlFormat_.FEATURE_COLLECTION_PARSERS[GMLBase.GMLNS][ - 'featureMember'] = + 'featureMember'] = _ol_xml_.makeArrayPusher(GMLBase.prototype.readFeaturesInternal); - var features = _ol_xml_.pushParseAndPop([], - this.gmlFormat_.FEATURE_COLLECTION_PARSERS, node, - objectStack, this.gmlFormat_); + let features = _ol_xml_.pushParseAndPop([], + this.gmlFormat_.FEATURE_COLLECTION_PARSERS, node, + objectStack, this.gmlFormat_); if (!features) { features = []; } @@ -179,11 +179,11 @@ WFS.prototype.readFeaturesFromNode = function(node, opt_options) { WFS.prototype.readTransactionResponse = function(source) { if (_ol_xml_.isDocument(source)) { return this.readTransactionResponseFromDocument( - /** @type {Document} */ (source)); + /** @type {Document} */ (source)); } else if (_ol_xml_.isNode(source)) { return this.readTransactionResponseFromNode(/** @type {Node} */ (source)); } else if (typeof source === 'string') { - var doc = _ol_xml_.parse(source); + const doc = _ol_xml_.parse(source); return this.readTransactionResponseFromDocument(doc); } else { return undefined; @@ -202,12 +202,12 @@ WFS.prototype.readTransactionResponse = function(source) { WFS.prototype.readFeatureCollectionMetadata = function(source) { if (_ol_xml_.isDocument(source)) { return this.readFeatureCollectionMetadataFromDocument( - /** @type {Document} */ (source)); + /** @type {Document} */ (source)); } else if (_ol_xml_.isNode(source)) { return this.readFeatureCollectionMetadataFromNode( - /** @type {Node} */ (source)); + /** @type {Node} */ (source)); } else if (typeof source === 'string') { - var doc = _ol_xml_.parse(source); + const doc = _ol_xml_.parse(source); return this.readFeatureCollectionMetadataFromDocument(doc); } else { return undefined; @@ -221,7 +221,7 @@ WFS.prototype.readFeatureCollectionMetadata = function(source) { * FeatureCollection metadata. */ WFS.prototype.readFeatureCollectionMetadataFromDocument = function(doc) { - for (var n = doc.firstChild; n; n = n.nextSibling) { + for (let n = doc.firstChild; n; n = n.nextSibling) { if (n.nodeType == Node.ELEMENT_NODE) { return this.readFeatureCollectionMetadataFromNode(n); } @@ -238,7 +238,7 @@ WFS.prototype.readFeatureCollectionMetadataFromDocument = function(doc) { WFS.FEATURE_COLLECTION_PARSERS_ = { 'http://www.opengis.net/gml': { 'boundedBy': _ol_xml_.makeObjectPropertySetter( - GMLBase.prototype.readGeometryElement, 'bounds') + GMLBase.prototype.readGeometryElement, 'bounds') } }; @@ -249,13 +249,13 @@ WFS.FEATURE_COLLECTION_PARSERS_ = { * FeatureCollection metadata. */ WFS.prototype.readFeatureCollectionMetadataFromNode = function(node) { - var result = {}; - var value = XSD.readNonNegativeIntegerString( - node.getAttribute('numberOfFeatures')); + const result = {}; + const value = XSD.readNonNegativeIntegerString( + node.getAttribute('numberOfFeatures')); result['numberOfFeatures'] = value; return _ol_xml_.pushParseAndPop( - /** @type {ol.WFSFeatureCollectionMetadata} */ (result), - WFS.FEATURE_COLLECTION_PARSERS_, node, [], this.gmlFormat_); + /** @type {ol.WFSFeatureCollectionMetadata} */ (result), + WFS.FEATURE_COLLECTION_PARSERS_, node, [], this.gmlFormat_); }; @@ -267,11 +267,11 @@ WFS.prototype.readFeatureCollectionMetadataFromNode = function(node) { WFS.TRANSACTION_SUMMARY_PARSERS_ = { 'http://www.opengis.net/wfs': { 'totalInserted': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger), + XSD.readNonNegativeInteger), 'totalUpdated': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger), + XSD.readNonNegativeInteger), 'totalDeleted': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger) + XSD.readNonNegativeInteger) } }; @@ -284,7 +284,7 @@ WFS.TRANSACTION_SUMMARY_PARSERS_ = { */ WFS.readTransactionSummary_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WFS.TRANSACTION_SUMMARY_PARSERS_, node, objectStack); + {}, WFS.TRANSACTION_SUMMARY_PARSERS_, node, objectStack); }; @@ -332,7 +332,7 @@ WFS.INSERT_RESULTS_PARSERS_ = { */ WFS.readInsertResults_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - [], WFS.INSERT_RESULTS_PARSERS_, node, objectStack); + [], WFS.INSERT_RESULTS_PARSERS_, node, objectStack); }; @@ -344,9 +344,9 @@ WFS.readInsertResults_ = function(node, objectStack) { WFS.TRANSACTION_RESPONSE_PARSERS_ = { 'http://www.opengis.net/wfs': { 'TransactionSummary': _ol_xml_.makeObjectPropertySetter( - WFS.readTransactionSummary_, 'transactionSummary'), + WFS.readTransactionSummary_, 'transactionSummary'), 'InsertResults': _ol_xml_.makeObjectPropertySetter( - WFS.readInsertResults_, 'insertIds') + WFS.readInsertResults_, 'insertIds') } }; @@ -356,7 +356,7 @@ WFS.TRANSACTION_RESPONSE_PARSERS_ = { * @return {ol.WFSTransactionResponse|undefined} Transaction response. */ WFS.prototype.readTransactionResponseFromDocument = function(doc) { - for (var n = doc.firstChild; n; n = n.nextSibling) { + for (let n = doc.firstChild; n; n = n.nextSibling) { if (n.nodeType == Node.ELEMENT_NODE) { return this.readTransactionResponseFromNode(n); } @@ -371,8 +371,8 @@ WFS.prototype.readTransactionResponseFromDocument = function(doc) { */ WFS.prototype.readTransactionResponseFromNode = function(node) { return _ol_xml_.pushParseAndPop( - /** @type {ol.WFSTransactionResponse} */({}), - WFS.TRANSACTION_RESPONSE_PARSERS_, node, []); + /** @type {ol.WFSTransactionResponse} */({}), + WFS.TRANSACTION_RESPONSE_PARSERS_, node, []); }; @@ -394,11 +394,11 @@ WFS.QUERY_SERIALIZERS_ = { * @private */ WFS.writeFeature_ = function(node, feature, objectStack) { - var context = objectStack[objectStack.length - 1]; - var featureType = context['featureType']; - var featureNS = context['featureNS']; - var gmlVersion = context['gmlVersion']; - var child = _ol_xml_.createElementNS(featureNS, featureType); + const context = objectStack[objectStack.length - 1]; + const featureType = context['featureType']; + const featureNS = context['featureNS']; + const gmlVersion = context['gmlVersion']; + const child = _ol_xml_.createElementNS(featureNS, featureType); node.appendChild(child); if (gmlVersion === 2) { GML2.prototype.writeFeatureElement(child, feature, objectStack); @@ -415,8 +415,8 @@ WFS.writeFeature_ = function(node, feature, objectStack) { * @private */ WFS.writeOgcFidFilter_ = function(node, fid, objectStack) { - var filter = _ol_xml_.createElementNS(WFS.OGCNS, 'Filter'); - var child = _ol_xml_.createElementNS(WFS.OGCNS, 'FeatureId'); + const filter = _ol_xml_.createElementNS(WFS.OGCNS, 'Filter'); + const child = _ol_xml_.createElementNS(WFS.OGCNS, 'FeatureId'); filter.appendChild(child); child.setAttribute('fid', fid); node.appendChild(filter); @@ -432,7 +432,7 @@ WFS.writeOgcFidFilter_ = function(node, fid, objectStack) { WFS.getTypeName_ = function(featurePrefix, featureType) { featurePrefix = featurePrefix ? featurePrefix : WFS.FEATURE_PREFIX; - var prefix = featurePrefix + ':'; + const prefix = featurePrefix + ':'; // The featureType already contains the prefix. if (featureType.indexOf(prefix) === 0) { return featureType; @@ -449,16 +449,16 @@ WFS.getTypeName_ = function(featurePrefix, featureType) { * @private */ WFS.writeDelete_ = function(node, feature, objectStack) { - var context = objectStack[objectStack.length - 1]; + const context = objectStack[objectStack.length - 1]; assert(feature.getId() !== undefined, 26); // Features must have an id set - var featureType = context['featureType']; - var featurePrefix = context['featurePrefix']; - var featureNS = context['featureNS']; - var typeName = WFS.getTypeName_(featurePrefix, featureType); + const featureType = context['featureType']; + const featurePrefix = context['featurePrefix']; + const featureNS = context['featureNS']; + const typeName = WFS.getTypeName_(featurePrefix, featureType); node.setAttribute('typeName', typeName); _ol_xml_.setAttributeNS(node, WFS.XMLNS, 'xmlns:' + featurePrefix, - featureNS); - var fid = feature.getId(); + featureNS); + const fid = feature.getId(); if (fid !== undefined) { WFS.writeOgcFidFilter_(node, fid, objectStack); } @@ -472,24 +472,24 @@ WFS.writeDelete_ = function(node, feature, objectStack) { * @private */ WFS.writeUpdate_ = function(node, feature, objectStack) { - var context = objectStack[objectStack.length - 1]; + const context = objectStack[objectStack.length - 1]; assert(feature.getId() !== undefined, 27); // Features must have an id set - var featureType = context['featureType']; - var featurePrefix = context['featurePrefix']; - var featureNS = context['featureNS']; - var typeName = WFS.getTypeName_(featurePrefix, featureType); - var geometryName = feature.getGeometryName(); + const featureType = context['featureType']; + const featurePrefix = context['featurePrefix']; + const featureNS = context['featureNS']; + const typeName = WFS.getTypeName_(featurePrefix, featureType); + const geometryName = feature.getGeometryName(); node.setAttribute('typeName', typeName); _ol_xml_.setAttributeNS(node, WFS.XMLNS, 'xmlns:' + featurePrefix, - featureNS); - var fid = feature.getId(); + featureNS); + const fid = feature.getId(); if (fid !== undefined) { - var keys = feature.getKeys(); - var values = []; - for (var i = 0, ii = keys.length; i < ii; i++) { - var value = feature.get(keys[i]); + const keys = feature.getKeys(); + const values = []; + for (let i = 0, ii = keys.length; i < ii; i++) { + const value = feature.get(keys[i]); if (value !== undefined) { - var name = keys[i]; + let name = keys[i]; if (value instanceof Geometry) { name = geometryName; } @@ -514,21 +514,21 @@ WFS.writeUpdate_ = function(node, feature, objectStack) { * @private */ WFS.writeProperty_ = function(node, pair, objectStack) { - var name = _ol_xml_.createElementNS(WFS.WFSNS, 'Name'); - var context = objectStack[objectStack.length - 1]; - var gmlVersion = context['gmlVersion']; + const name = _ol_xml_.createElementNS(WFS.WFSNS, 'Name'); + const context = objectStack[objectStack.length - 1]; + const gmlVersion = context['gmlVersion']; node.appendChild(name); XSD.writeStringTextNode(name, pair.name); if (pair.value !== undefined && pair.value !== null) { - var value = _ol_xml_.createElementNS(WFS.WFSNS, 'Value'); + const value = _ol_xml_.createElementNS(WFS.WFSNS, 'Value'); node.appendChild(value); if (pair.value instanceof Geometry) { if (gmlVersion === 2) { GML2.prototype.writeGeometryElement(value, - pair.value, objectStack); + pair.value, objectStack); } else { GML3.prototype.writeGeometryElement(value, - pair.value, objectStack); + pair.value, objectStack); } } else { XSD.writeStringTextNode(value, pair.value); @@ -579,12 +579,12 @@ WFS.TRANSACTION_SERIALIZERS_ = { * @private */ WFS.writeQuery_ = function(node, featureType, objectStack) { - var context = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var featurePrefix = context['featurePrefix']; - var featureNS = context['featureNS']; - var propertyNames = context['propertyNames']; - var srsName = context['srsName']; - var typeName; + const context = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const featurePrefix = context['featurePrefix']; + const featureNS = context['featureNS']; + const propertyNames = context['propertyNames']; + const srsName = context['srsName']; + let typeName; // If feature prefix is not defined, we must not use the default prefix. if (featurePrefix) { typeName = WFS.getTypeName_(featurePrefix, featureType); @@ -597,17 +597,17 @@ WFS.writeQuery_ = function(node, featureType, objectStack) { } if (featureNS) { _ol_xml_.setAttributeNS(node, WFS.XMLNS, 'xmlns:' + featurePrefix, - featureNS); + featureNS); } - var item = /** @type {ol.XmlNodeStackItem} */ (_ol_obj_.assign({}, context)); + const item = /** @type {ol.XmlNodeStackItem} */ (_ol_obj_.assign({}, context)); item.node = node; _ol_xml_.pushSerializeAndPop(item, - WFS.QUERY_SERIALIZERS_, - _ol_xml_.makeSimpleNodeFactory('PropertyName'), propertyNames, - objectStack); - var filter = context['filter']; + WFS.QUERY_SERIALIZERS_, + _ol_xml_.makeSimpleNodeFactory('PropertyName'), propertyNames, + objectStack); + const filter = context['filter']; if (filter) { - var child = _ol_xml_.createElementNS(WFS.OGCNS, 'Filter'); + const child = _ol_xml_.createElementNS(WFS.OGCNS, 'Filter'); node.appendChild(child); WFS.writeFilterCondition_(child, filter, objectStack); } @@ -622,11 +622,11 @@ WFS.writeQuery_ = function(node, featureType, objectStack) { */ WFS.writeFilterCondition_ = function(node, filter, objectStack) { /** @type {ol.XmlNodeStackItem} */ - var item = {node: node}; + const item = {node: node}; _ol_xml_.pushSerializeAndPop(item, - WFS.GETFEATURE_SERIALIZERS_, - _ol_xml_.makeSimpleNodeFactory(filter.getTagName()), - [filter], objectStack); + WFS.GETFEATURE_SERIALIZERS_, + _ol_xml_.makeSimpleNodeFactory(filter.getTagName()), + [filter], objectStack); }; @@ -637,7 +637,7 @@ WFS.writeFilterCondition_ = function(node, filter, objectStack) { * @private */ WFS.writeBboxFilter_ = function(node, filter, objectStack) { - var context = objectStack[objectStack.length - 1]; + const context = objectStack[objectStack.length - 1]; context['srsName'] = filter.srsName; WFS.writeOgcPropertyName_(node, filter.geometryName); @@ -652,7 +652,7 @@ WFS.writeBboxFilter_ = function(node, filter, objectStack) { * @private */ WFS.writeContainsFilter_ = function(node, filter, objectStack) { - var context = objectStack[objectStack.length - 1]; + const context = objectStack[objectStack.length - 1]; context['srsName'] = filter.srsName; WFS.writeOgcPropertyName_(node, filter.geometryName); @@ -667,7 +667,7 @@ WFS.writeContainsFilter_ = function(node, filter, objectStack) { * @private */ WFS.writeIntersectsFilter_ = function(node, filter, objectStack) { - var context = objectStack[objectStack.length - 1]; + const context = objectStack[objectStack.length - 1]; context['srsName'] = filter.srsName; WFS.writeOgcPropertyName_(node, filter.geometryName); @@ -682,7 +682,7 @@ WFS.writeIntersectsFilter_ = function(node, filter, objectStack) { * @private */ WFS.writeWithinFilter_ = function(node, filter, objectStack) { - var context = objectStack[objectStack.length - 1]; + const context = objectStack[objectStack.length - 1]; context['srsName'] = filter.srsName; WFS.writeOgcPropertyName_(node, filter.geometryName); @@ -698,19 +698,19 @@ WFS.writeWithinFilter_ = function(node, filter, objectStack) { */ WFS.writeDuringFilter_ = function(node, filter, objectStack) { - var valueReference = _ol_xml_.createElementNS(WFS.FESNS, 'ValueReference'); + const valueReference = _ol_xml_.createElementNS(WFS.FESNS, 'ValueReference'); XSD.writeStringTextNode(valueReference, filter.propertyName); node.appendChild(valueReference); - var timePeriod = _ol_xml_.createElementNS(GMLBase.GMLNS, 'TimePeriod'); + const timePeriod = _ol_xml_.createElementNS(GMLBase.GMLNS, 'TimePeriod'); node.appendChild(timePeriod); - var begin = _ol_xml_.createElementNS(GMLBase.GMLNS, 'begin'); + const begin = _ol_xml_.createElementNS(GMLBase.GMLNS, 'begin'); timePeriod.appendChild(begin); WFS.writeTimeInstant_(begin, filter.begin); - var end = _ol_xml_.createElementNS(GMLBase.GMLNS, 'end'); + const end = _ol_xml_.createElementNS(GMLBase.GMLNS, 'end'); timePeriod.appendChild(end); WFS.writeTimeInstant_(end, filter.end); }; @@ -724,14 +724,14 @@ WFS.writeDuringFilter_ = function(node, filter, objectStack) { */ WFS.writeLogicalFilter_ = function(node, filter, objectStack) { /** @type {ol.XmlNodeStackItem} */ - var item = {node: node}; - var conditions = filter.conditions; - for (var i = 0, ii = conditions.length; i < ii; ++i) { - var condition = conditions[i]; + const item = {node: node}; + const conditions = filter.conditions; + for (let i = 0, ii = conditions.length; i < ii; ++i) { + const condition = conditions[i]; _ol_xml_.pushSerializeAndPop(item, - WFS.GETFEATURE_SERIALIZERS_, - _ol_xml_.makeSimpleNodeFactory(condition.getTagName()), - [condition], objectStack); + WFS.GETFEATURE_SERIALIZERS_, + _ol_xml_.makeSimpleNodeFactory(condition.getTagName()), + [condition], objectStack); } }; @@ -744,12 +744,12 @@ WFS.writeLogicalFilter_ = function(node, filter, objectStack) { */ WFS.writeNotFilter_ = function(node, filter, objectStack) { /** @type {ol.XmlNodeStackItem} */ - var item = {node: node}; - var condition = filter.condition; + const item = {node: node}; + const condition = filter.condition; _ol_xml_.pushSerializeAndPop(item, - WFS.GETFEATURE_SERIALIZERS_, - _ol_xml_.makeSimpleNodeFactory(condition.getTagName()), - [condition], objectStack); + WFS.GETFEATURE_SERIALIZERS_, + _ol_xml_.makeSimpleNodeFactory(condition.getTagName()), + [condition], objectStack); }; @@ -788,11 +788,11 @@ WFS.writeIsNullFilter_ = function(node, filter, objectStack) { WFS.writeIsBetweenFilter_ = function(node, filter, objectStack) { WFS.writeOgcPropertyName_(node, filter.propertyName); - var lowerBoundary = _ol_xml_.createElementNS(WFS.OGCNS, 'LowerBoundary'); + const lowerBoundary = _ol_xml_.createElementNS(WFS.OGCNS, 'LowerBoundary'); node.appendChild(lowerBoundary); WFS.writeOgcLiteral_(lowerBoundary, '' + filter.lowerBoundary); - var upperBoundary = _ol_xml_.createElementNS(WFS.OGCNS, 'UpperBoundary'); + const upperBoundary = _ol_xml_.createElementNS(WFS.OGCNS, 'UpperBoundary'); node.appendChild(upperBoundary); WFS.writeOgcLiteral_(upperBoundary, '' + filter.upperBoundary); }; @@ -823,7 +823,7 @@ WFS.writeIsLikeFilter_ = function(node, filter, objectStack) { * @private */ WFS.writeOgcExpression_ = function(tagName, node, value) { - var property = _ol_xml_.createElementNS(WFS.OGCNS, tagName); + const property = _ol_xml_.createElementNS(WFS.OGCNS, tagName); XSD.writeStringTextNode(property, value); node.appendChild(property); }; @@ -855,10 +855,10 @@ WFS.writeOgcLiteral_ = function(node, value) { * @private */ WFS.writeTimeInstant_ = function(node, time) { - var timeInstant = _ol_xml_.createElementNS(GMLBase.GMLNS, 'TimeInstant'); + const timeInstant = _ol_xml_.createElementNS(GMLBase.GMLNS, 'TimeInstant'); node.appendChild(timeInstant); - var timePosition = _ol_xml_.createElementNS(GMLBase.GMLNS, 'timePosition'); + const timePosition = _ol_xml_.createElementNS(GMLBase.GMLNS, 'timePosition'); timeInstant.appendChild(timePosition); XSD.writeStringTextNode(timePosition, time); }; @@ -902,7 +902,7 @@ WFS.GETFEATURE_SERIALIZERS_ = { * @api */ WFS.writeFilter = function(filter) { - var child = _ol_xml_.createElementNS(WFS.OGCNS, 'Filter'); + const child = _ol_xml_.createElementNS(WFS.OGCNS, 'Filter'); WFS.writeFilterCondition_(child, filter, []); return child; }; @@ -915,13 +915,13 @@ WFS.writeFilter = function(filter) { * @private */ WFS.writeGetFeature_ = function(node, featureTypes, objectStack) { - var context = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var item = /** @type {ol.XmlNodeStackItem} */ (_ol_obj_.assign({}, context)); + const context = /** @type {Object} */ (objectStack[objectStack.length - 1]); + const item = /** @type {ol.XmlNodeStackItem} */ (_ol_obj_.assign({}, context)); item.node = node; _ol_xml_.pushSerializeAndPop(item, - WFS.GETFEATURE_SERIALIZERS_, - _ol_xml_.makeSimpleNodeFactory('Query'), featureTypes, - objectStack); + WFS.GETFEATURE_SERIALIZERS_, + _ol_xml_.makeSimpleNodeFactory('Query'), featureTypes, + objectStack); }; @@ -933,10 +933,10 @@ WFS.writeGetFeature_ = function(node, featureTypes, objectStack) { * @api */ WFS.prototype.writeGetFeature = function(options) { - var node = _ol_xml_.createElementNS(WFS.WFSNS, 'GetFeature'); + const node = _ol_xml_.createElementNS(WFS.WFSNS, 'GetFeature'); node.setAttribute('service', 'WFS'); node.setAttribute('version', '1.1.0'); - var filter; + let filter; if (options) { if (options.handle) { node.setAttribute('handle', options.handle); @@ -959,9 +959,9 @@ WFS.prototype.writeGetFeature = function(options) { filter = options.filter; if (options.bbox) { assert(options.geometryName, - 12); // `options.geometryName` must also be provided when `options.bbox` is set - var bbox = _ol_format_filter_.bbox( - /** @type {string} */ (options.geometryName), options.bbox, options.srsName); + 12); // `options.geometryName` must also be provided when `options.bbox` is set + const bbox = _ol_format_filter_.bbox( + /** @type {string} */ (options.geometryName), options.bbox, options.srsName); if (filter) { // if bbox and filter are both set, combine the two into a single filter filter = _ol_format_filter_.and(filter, bbox); @@ -971,9 +971,9 @@ WFS.prototype.writeGetFeature = function(options) { } } _ol_xml_.setAttributeNS(node, 'http://www.w3.org/2001/XMLSchema-instance', - 'xsi:schemaLocation', this.schemaLocation_); + 'xsi:schemaLocation', this.schemaLocation_); /** @type {ol.XmlNodeStackItem} */ - var context = { + const context = { node: node, 'srsName': options.srsName, 'featureNS': options.featureNS ? options.featureNS : this.featureNS_, @@ -983,7 +983,7 @@ WFS.prototype.writeGetFeature = function(options) { 'propertyNames': options.propertyNames ? options.propertyNames : [] }; assert(Array.isArray(options.featureTypes), - 11); // `options.featureTypes` should be an Array + 11); // `options.featureTypes` should be an Array WFS.writeGetFeature_(node, /** @type {!Array.} */ (options.featureTypes), [context]); return node; }; @@ -1000,36 +1000,36 @@ WFS.prototype.writeGetFeature = function(options) { * @api */ WFS.prototype.writeTransaction = function(inserts, updates, deletes, - options) { - var objectStack = []; - var node = _ol_xml_.createElementNS(WFS.WFSNS, 'Transaction'); - var version = options.version ? + options) { + const objectStack = []; + const node = _ol_xml_.createElementNS(WFS.WFSNS, 'Transaction'); + const version = options.version ? options.version : WFS.DEFAULT_VERSION; - var gmlVersion = version === '1.0.0' ? 2 : 3; + const gmlVersion = version === '1.0.0' ? 2 : 3; node.setAttribute('service', 'WFS'); node.setAttribute('version', version); - var baseObj; + let baseObj; /** @type {ol.XmlNodeStackItem} */ - var obj; + let obj; if (options) { baseObj = options.gmlOptions ? options.gmlOptions : {}; if (options.handle) { node.setAttribute('handle', options.handle); } } - var schemaLocation = WFS.SCHEMA_LOCATIONS[version]; + const schemaLocation = WFS.SCHEMA_LOCATIONS[version]; _ol_xml_.setAttributeNS(node, 'http://www.w3.org/2001/XMLSchema-instance', - 'xsi:schemaLocation', schemaLocation); - var featurePrefix = options.featurePrefix ? options.featurePrefix : WFS.FEATURE_PREFIX; + 'xsi:schemaLocation', schemaLocation); + const featurePrefix = options.featurePrefix ? options.featurePrefix : WFS.FEATURE_PREFIX; if (inserts) { obj = {node: node, 'featureNS': options.featureNS, 'featureType': options.featureType, 'featurePrefix': featurePrefix, 'gmlVersion': gmlVersion, 'hasZ': options.hasZ, 'srsName': options.srsName}; _ol_obj_.assign(obj, baseObj); _ol_xml_.pushSerializeAndPop(obj, - WFS.TRANSACTION_SERIALIZERS_, - _ol_xml_.makeSimpleNodeFactory('Insert'), inserts, - objectStack); + WFS.TRANSACTION_SERIALIZERS_, + _ol_xml_.makeSimpleNodeFactory('Insert'), inserts, + objectStack); } if (updates) { obj = {node: node, 'featureNS': options.featureNS, @@ -1037,9 +1037,9 @@ WFS.prototype.writeTransaction = function(inserts, updates, deletes, 'gmlVersion': gmlVersion, 'hasZ': options.hasZ, 'srsName': options.srsName}; _ol_obj_.assign(obj, baseObj); _ol_xml_.pushSerializeAndPop(obj, - WFS.TRANSACTION_SERIALIZERS_, - _ol_xml_.makeSimpleNodeFactory('Update'), updates, - objectStack); + WFS.TRANSACTION_SERIALIZERS_, + _ol_xml_.makeSimpleNodeFactory('Update'), updates, + objectStack); } if (deletes) { _ol_xml_.pushSerializeAndPop({node: node, 'featureNS': options.featureNS, @@ -1076,7 +1076,7 @@ WFS.prototype.readProjection; * @inheritDoc */ WFS.prototype.readProjectionFromDocument = function(doc) { - for (var n = doc.firstChild; n; n = n.nextSibling) { + for (let n = doc.firstChild; n; n = n.nextSibling) { if (n.nodeType == Node.ELEMENT_NODE) { return this.readProjectionFromNode(n); } @@ -1092,11 +1092,11 @@ WFS.prototype.readProjectionFromNode = function(node) { if (node.firstElementChild && node.firstElementChild.firstElementChild) { node = node.firstElementChild.firstElementChild; - for (var n = node.firstElementChild; n; n = n.nextElementSibling) { + for (let n = node.firstElementChild; n; n = n.nextElementSibling) { if (!(n.childNodes.length === 0 || (n.childNodes.length === 1 && n.firstChild.nodeType === 3))) { - var objectStack = [{}]; + const objectStack = [{}]; this.gmlFormat_.readGeometryElement(n, objectStack); return getProjection(objectStack.pop().srsName); } diff --git a/src/ol/format/WKT.js b/src/ol/format/WKT.js index 9b91c7f12d..504e9451d2 100644 --- a/src/ol/format/WKT.js +++ b/src/ol/format/WKT.js @@ -26,9 +26,9 @@ import SimpleGeometry from '../geom/SimpleGeometry.js'; * @param {olx.format.WKTOptions=} opt_options Options. * @api */ -var WKT = function(opt_options) { +const WKT = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; TextFeature.call(this); @@ -79,7 +79,7 @@ WKT.ZM = 'ZM'; * @private */ WKT.encodePointGeometry_ = function(geom) { - var coordinates = geom.getCoordinates(); + const coordinates = geom.getCoordinates(); if (coordinates.length === 0) { return ''; } @@ -93,9 +93,9 @@ WKT.encodePointGeometry_ = function(geom) { * @private */ WKT.encodeMultiPointGeometry_ = function(geom) { - var array = []; - var components = geom.getPoints(); - for (var i = 0, ii = components.length; i < ii; ++i) { + const array = []; + const components = geom.getPoints(); + for (let i = 0, ii = components.length; i < ii; ++i) { array.push('(' + WKT.encodePointGeometry_(components[i]) + ')'); } return array.join(','); @@ -108,9 +108,9 @@ WKT.encodeMultiPointGeometry_ = function(geom) { * @private */ WKT.encodeGeometryCollectionGeometry_ = function(geom) { - var array = []; - var geoms = geom.getGeometries(); - for (var i = 0, ii = geoms.length; i < ii; ++i) { + const array = []; + const geoms = geom.getGeometries(); + for (let i = 0, ii = geoms.length; i < ii; ++i) { array.push(WKT.encode_(geoms[i])); } return array.join(','); @@ -123,9 +123,9 @@ WKT.encodeGeometryCollectionGeometry_ = function(geom) { * @private */ WKT.encodeLineStringGeometry_ = function(geom) { - var coordinates = geom.getCoordinates(); - var array = []; - for (var i = 0, ii = coordinates.length; i < ii; ++i) { + const coordinates = geom.getCoordinates(); + const array = []; + for (let i = 0, ii = coordinates.length; i < ii; ++i) { array.push(coordinates[i].join(' ')); } return array.join(','); @@ -138,11 +138,11 @@ WKT.encodeLineStringGeometry_ = function(geom) { * @private */ WKT.encodeMultiLineStringGeometry_ = function(geom) { - var array = []; - var components = geom.getLineStrings(); - for (var i = 0, ii = components.length; i < ii; ++i) { + const array = []; + const components = geom.getLineStrings(); + for (let i = 0, ii = components.length; i < ii; ++i) { array.push('(' + WKT.encodeLineStringGeometry_( - components[i]) + ')'); + components[i]) + ')'); } return array.join(','); }; @@ -154,11 +154,11 @@ WKT.encodeMultiLineStringGeometry_ = function(geom) { * @private */ WKT.encodePolygonGeometry_ = function(geom) { - var array = []; - var rings = geom.getLinearRings(); - for (var i = 0, ii = rings.length; i < ii; ++i) { + const array = []; + const rings = geom.getLinearRings(); + for (let i = 0, ii = rings.length; i < ii; ++i) { array.push('(' + WKT.encodeLineStringGeometry_( - rings[i]) + ')'); + rings[i]) + ')'); } return array.join(','); }; @@ -170,11 +170,11 @@ WKT.encodePolygonGeometry_ = function(geom) { * @private */ WKT.encodeMultiPolygonGeometry_ = function(geom) { - var array = []; - var components = geom.getPolygons(); - for (var i = 0, ii = components.length; i < ii; ++i) { + const array = []; + const components = geom.getPolygons(); + for (let i = 0, ii = components.length; i < ii; ++i) { array.push('(' + WKT.encodePolygonGeometry_( - components[i]) + ')'); + components[i]) + ')'); } return array.join(','); }; @@ -185,8 +185,8 @@ WKT.encodeMultiPolygonGeometry_ = function(geom) { * @private */ WKT.encodeGeometryLayout_ = function(geom) { - var layout = geom.getLayout(); - var dimInfo = ''; + const layout = geom.getLayout(); + let dimInfo = ''; if (layout === GeometryLayout.XYZ || layout === GeometryLayout.XYZM) { dimInfo += WKT.Z; } @@ -204,12 +204,12 @@ WKT.encodeGeometryLayout_ = function(geom) { * @private */ WKT.encode_ = function(geom) { - var type = geom.getType(); - var geometryEncoder = WKT.GeometryEncoder_[type]; - var enc = geometryEncoder(geom); + let type = geom.getType(); + const geometryEncoder = WKT.GeometryEncoder_[type]; + const enc = geometryEncoder(geom); type = type.toUpperCase(); if (geom instanceof SimpleGeometry) { - var dimInfo = WKT.encodeGeometryLayout_(geom); + const dimInfo = WKT.encodeGeometryLayout_(geom); if (dimInfo.length > 0) { type += ' ' + dimInfo; } @@ -245,8 +245,8 @@ WKT.GeometryEncoder_ = { * @private */ WKT.prototype.parse_ = function(wkt) { - var lexer = new WKT.Lexer(wkt); - var parser = new WKT.Parser(lexer); + const lexer = new WKT.Lexer(wkt); + const parser = new WKT.Parser(lexer); return parser.parse(); }; @@ -267,9 +267,9 @@ WKT.prototype.readFeature; * @inheritDoc */ WKT.prototype.readFeatureFromText = function(text, opt_options) { - var geom = this.readGeometryFromText(text, opt_options); + const geom = this.readGeometryFromText(text, opt_options); if (geom) { - var feature = new Feature(); + const feature = new Feature(); feature.setGeometry(geom); return feature; } @@ -293,17 +293,18 @@ WKT.prototype.readFeatures; * @inheritDoc */ WKT.prototype.readFeaturesFromText = function(text, opt_options) { - var geometries = []; - var geometry = this.readGeometryFromText(text, opt_options); + let geometries = []; + const geometry = this.readGeometryFromText(text, opt_options); if (this.splitCollection_ && geometry.getType() == GeometryType.GEOMETRY_COLLECTION) { geometries = (/** @type {ol.geom.GeometryCollection} */ (geometry)) - .getGeometriesArray(); + .getGeometriesArray(); } else { geometries = [geometry]; } - var feature, features = []; - for (var i = 0, ii = geometries.length; i < ii; ++i) { + const features = []; + let feature; + for (let i = 0, ii = geometries.length; i < ii; ++i) { feature = new Feature(); feature.setGeometry(geometries[i]); features.push(feature); @@ -328,7 +329,7 @@ WKT.prototype.readGeometry; * @inheritDoc */ WKT.prototype.readGeometryFromText = function(text, opt_options) { - var geometry = this.parse_(text); + const geometry = this.parse_(text); if (geometry) { return ( /** @type {ol.geom.Geometry} */ transformWithOptions(geometry, false, opt_options) @@ -355,7 +356,7 @@ WKT.prototype.writeFeature; * @inheritDoc */ WKT.prototype.writeFeatureText = function(feature, opt_options) { - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); if (geometry) { return this.writeGeometryText(geometry, opt_options); } @@ -382,11 +383,11 @@ WKT.prototype.writeFeaturesText = function(features, opt_options) { if (features.length == 1) { return this.writeFeatureText(features[0], opt_options); } - var geometries = []; - for (var i = 0, ii = features.length; i < ii; ++i) { + const geometries = []; + for (let i = 0, ii = features.length; i < ii; ++i) { geometries.push(features[i].getGeometry()); } - var collection = new GeometryCollection(geometries); + const collection = new GeometryCollection(geometries); return this.writeGeometryText(collection, opt_options); }; @@ -466,7 +467,7 @@ WKT.Lexer.prototype.isAlpha_ = function(c) { * @private */ WKT.Lexer.prototype.isNumeric_ = function(c, opt_decimal) { - var decimal = opt_decimal !== undefined ? opt_decimal : false; + const decimal = opt_decimal !== undefined ? opt_decimal : false; return c >= '0' && c <= '9' || c == '.' && !decimal; }; @@ -495,8 +496,8 @@ WKT.Lexer.prototype.nextChar_ = function() { * @return {!ol.WKTToken} Next string token. */ WKT.Lexer.prototype.nextToken = function() { - var c = this.nextChar_(); - var token = {position: this.index_, value: c}; + const c = this.nextChar_(); + const token = {position: this.index_, value: c}; if (c == '(') { token.type = WKT.TokenType_.LEFT_PAREN; @@ -527,9 +528,10 @@ WKT.Lexer.prototype.nextToken = function() { * @private */ WKT.Lexer.prototype.readNumber_ = function() { - var c, index = this.index_; - var decimal = false; - var scientificNotation = false; + let c; + const index = this.index_; + let decimal = false; + let scientificNotation = false; do { if (c == '.') { decimal = true; @@ -555,7 +557,8 @@ WKT.Lexer.prototype.readNumber_ = function() { * @private */ WKT.Lexer.prototype.readText_ = function() { - var c, index = this.index_; + let c; + const index = this.index_; do { c = this.nextChar_(); } while (this.isAlpha_(c)); @@ -605,7 +608,7 @@ WKT.Parser.prototype.consume_ = function() { * @return {boolean} Whether the token matches the given type. */ WKT.Parser.prototype.isTokenType = function(type) { - var isMatch = this.token_.type == type; + const isMatch = this.token_.type == type; return isMatch; }; @@ -616,7 +619,7 @@ WKT.Parser.prototype.isTokenType = function(type) { * @return {boolean} Whether the token matches the given type. */ WKT.Parser.prototype.match = function(type) { - var isMatch = this.isTokenType(type); + const isMatch = this.isTokenType(type); if (isMatch) { this.consume_(); } @@ -630,7 +633,7 @@ WKT.Parser.prototype.match = function(type) { */ WKT.Parser.prototype.parse = function() { this.consume_(); - var geometry = this.parseGeometry_(); + const geometry = this.parseGeometry_(); return geometry; }; @@ -641,10 +644,10 @@ WKT.Parser.prototype.parse = function() { * @private */ WKT.Parser.prototype.parseGeometryLayout_ = function() { - var layout = GeometryLayout.XY; - var dimToken = this.token_; + let layout = GeometryLayout.XY; + const dimToken = this.token_; if (this.isTokenType(WKT.TokenType_.TEXT)) { - var dimInfo = dimToken.value; + const dimInfo = dimToken.value; if (dimInfo === WKT.Z) { layout = GeometryLayout.XYZ; } else if (dimInfo === WKT.M) { @@ -665,20 +668,20 @@ WKT.Parser.prototype.parseGeometryLayout_ = function() { * @private */ WKT.Parser.prototype.parseGeometry_ = function() { - var token = this.token_; + const token = this.token_; if (this.match(WKT.TokenType_.TEXT)) { - var geomType = token.value; + const geomType = token.value; this.layout_ = this.parseGeometryLayout_(); if (geomType == GeometryType.GEOMETRY_COLLECTION.toUpperCase()) { - var geometries = this.parseGeometryCollectionText_(); + const geometries = this.parseGeometryCollectionText_(); return new GeometryCollection(geometries); } else { - var parser = WKT.Parser.GeometryParser_[geomType]; - var ctor = WKT.Parser.GeometryConstructor_[geomType]; + const parser = WKT.Parser.GeometryParser_[geomType]; + const ctor = WKT.Parser.GeometryConstructor_[geomType]; if (!parser || !ctor) { throw new Error('Invalid geometry type: ' + geomType); } - var coordinates = parser.call(this); + const coordinates = parser.call(this); return new ctor(coordinates, this.layout_); } } @@ -692,7 +695,7 @@ WKT.Parser.prototype.parseGeometry_ = function() { */ WKT.Parser.prototype.parseGeometryCollectionText_ = function() { if (this.match(WKT.TokenType_.LEFT_PAREN)) { - var geometries = []; + const geometries = []; do { geometries.push(this.parseGeometry_()); } while (this.match(WKT.TokenType_.COMMA)); @@ -712,7 +715,7 @@ WKT.Parser.prototype.parseGeometryCollectionText_ = function() { */ WKT.Parser.prototype.parsePointText_ = function() { if (this.match(WKT.TokenType_.LEFT_PAREN)) { - var coordinates = this.parsePoint_(); + const coordinates = this.parsePoint_(); if (this.match(WKT.TokenType_.RIGHT_PAREN)) { return coordinates; } @@ -729,7 +732,7 @@ WKT.Parser.prototype.parsePointText_ = function() { */ WKT.Parser.prototype.parseLineStringText_ = function() { if (this.match(WKT.TokenType_.LEFT_PAREN)) { - var coordinates = this.parsePointList_(); + const coordinates = this.parsePointList_(); if (this.match(WKT.TokenType_.RIGHT_PAREN)) { return coordinates; } @@ -746,7 +749,7 @@ WKT.Parser.prototype.parseLineStringText_ = function() { */ WKT.Parser.prototype.parsePolygonText_ = function() { if (this.match(WKT.TokenType_.LEFT_PAREN)) { - var coordinates = this.parseLineStringTextList_(); + const coordinates = this.parseLineStringTextList_(); if (this.match(WKT.TokenType_.RIGHT_PAREN)) { return coordinates; } @@ -763,7 +766,7 @@ WKT.Parser.prototype.parsePolygonText_ = function() { */ WKT.Parser.prototype.parseMultiPointText_ = function() { if (this.match(WKT.TokenType_.LEFT_PAREN)) { - var coordinates; + let coordinates; if (this.token_.type == WKT.TokenType_.LEFT_PAREN) { coordinates = this.parsePointTextList_(); } else { @@ -786,7 +789,7 @@ WKT.Parser.prototype.parseMultiPointText_ = function() { */ WKT.Parser.prototype.parseMultiLineStringText_ = function() { if (this.match(WKT.TokenType_.LEFT_PAREN)) { - var coordinates = this.parseLineStringTextList_(); + const coordinates = this.parseLineStringTextList_(); if (this.match(WKT.TokenType_.RIGHT_PAREN)) { return coordinates; } @@ -803,7 +806,7 @@ WKT.Parser.prototype.parseMultiLineStringText_ = function() { */ WKT.Parser.prototype.parseMultiPolygonText_ = function() { if (this.match(WKT.TokenType_.LEFT_PAREN)) { - var coordinates = this.parsePolygonTextList_(); + const coordinates = this.parsePolygonTextList_(); if (this.match(WKT.TokenType_.RIGHT_PAREN)) { return coordinates; } @@ -819,10 +822,10 @@ WKT.Parser.prototype.parseMultiPolygonText_ = function() { * @private */ WKT.Parser.prototype.parsePoint_ = function() { - var coordinates = []; - var dimensions = this.layout_.length; - for (var i = 0; i < dimensions; ++i) { - var token = this.token_; + const coordinates = []; + const dimensions = this.layout_.length; + for (let i = 0; i < dimensions; ++i) { + const token = this.token_; if (this.match(WKT.TokenType_.NUMBER)) { coordinates.push(token.value); } else { @@ -841,7 +844,7 @@ WKT.Parser.prototype.parsePoint_ = function() { * @private */ WKT.Parser.prototype.parsePointList_ = function() { - var coordinates = [this.parsePoint_()]; + const coordinates = [this.parsePoint_()]; while (this.match(WKT.TokenType_.COMMA)) { coordinates.push(this.parsePoint_()); } @@ -854,7 +857,7 @@ WKT.Parser.prototype.parsePointList_ = function() { * @private */ WKT.Parser.prototype.parsePointTextList_ = function() { - var coordinates = [this.parsePointText_()]; + const coordinates = [this.parsePointText_()]; while (this.match(WKT.TokenType_.COMMA)) { coordinates.push(this.parsePointText_()); } @@ -867,7 +870,7 @@ WKT.Parser.prototype.parsePointTextList_ = function() { * @private */ WKT.Parser.prototype.parseLineStringTextList_ = function() { - var coordinates = [this.parseLineStringText_()]; + const coordinates = [this.parseLineStringText_()]; while (this.match(WKT.TokenType_.COMMA)) { coordinates.push(this.parseLineStringText_()); } @@ -880,7 +883,7 @@ WKT.Parser.prototype.parseLineStringTextList_ = function() { * @private */ WKT.Parser.prototype.parsePolygonTextList_ = function() { - var coordinates = [this.parsePolygonText_()]; + const coordinates = [this.parsePolygonText_()]; while (this.match(WKT.TokenType_.COMMA)) { coordinates.push(this.parsePolygonText_()); } @@ -893,7 +896,7 @@ WKT.Parser.prototype.parsePolygonTextList_ = function() { * @private */ WKT.Parser.prototype.isEmptyGeometry_ = function() { - var isEmpty = this.isTokenType(WKT.TokenType_.TEXT) && + const isEmpty = this.isTokenType(WKT.TokenType_.TEXT) && this.token_.value == WKT.EMPTY; if (isEmpty) { this.consume_(); diff --git a/src/ol/format/WMSCapabilities.js b/src/ol/format/WMSCapabilities.js index 62eb05ce68..5e09640d84 100644 --- a/src/ol/format/WMSCapabilities.js +++ b/src/ol/format/WMSCapabilities.js @@ -15,7 +15,7 @@ import _ol_xml_ from '../xml.js'; * @extends {ol.format.XML} * @api */ -var WMSCapabilities = function() { +const WMSCapabilities = function() { XML.call(this); @@ -43,7 +43,7 @@ WMSCapabilities.prototype.read; * @inheritDoc */ WMSCapabilities.prototype.readFromDocument = function(doc) { - for (var n = doc.firstChild; n; n = n.nextSibling) { + for (let n = doc.firstChild; n; n = n.nextSibling) { if (n.nodeType == Node.ELEMENT_NODE) { return this.readFromNode(n); } @@ -57,7 +57,7 @@ WMSCapabilities.prototype.readFromDocument = function(doc) { */ WMSCapabilities.prototype.readFromNode = function(node) { this.version = node.getAttribute('version').trim(); - var wmsCapabilityObject = _ol_xml_.pushParseAndPop({ + const wmsCapabilityObject = _ol_xml_.pushParseAndPop({ 'version': this.version }, WMSCapabilities.PARSERS_, node, []); return wmsCapabilityObject ? wmsCapabilityObject : null; @@ -72,7 +72,7 @@ WMSCapabilities.prototype.readFromNode = function(node) { */ WMSCapabilities.readAttribution_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.ATTRIBUTION_PARSERS_, node, objectStack); + {}, WMSCapabilities.ATTRIBUTION_PARSERS_, node, objectStack); }; @@ -83,14 +83,14 @@ WMSCapabilities.readAttribution_ = function(node, objectStack) { * @return {Object} Bounding box object. */ WMSCapabilities.readBoundingBox_ = function(node, objectStack) { - var extent = [ + const extent = [ XSD.readDecimalString(node.getAttribute('minx')), XSD.readDecimalString(node.getAttribute('miny')), XSD.readDecimalString(node.getAttribute('maxx')), XSD.readDecimalString(node.getAttribute('maxy')) ]; - var resolutions = [ + const resolutions = [ XSD.readDecimalString(node.getAttribute('resx')), XSD.readDecimalString(node.getAttribute('resy')) ]; @@ -110,20 +110,20 @@ WMSCapabilities.readBoundingBox_ = function(node, objectStack) { * @return {ol.Extent|undefined} Bounding box object. */ WMSCapabilities.readEXGeographicBoundingBox_ = function(node, objectStack) { - var geographicBoundingBox = _ol_xml_.pushParseAndPop( - {}, - WMSCapabilities.EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS_, - node, objectStack); + const geographicBoundingBox = _ol_xml_.pushParseAndPop( + {}, + WMSCapabilities.EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS_, + node, objectStack); if (!geographicBoundingBox) { return undefined; } - var westBoundLongitude = /** @type {number|undefined} */ + const westBoundLongitude = /** @type {number|undefined} */ (geographicBoundingBox['westBoundLongitude']); - var southBoundLatitude = /** @type {number|undefined} */ + const southBoundLatitude = /** @type {number|undefined} */ (geographicBoundingBox['southBoundLatitude']); - var eastBoundLongitude = /** @type {number|undefined} */ + const eastBoundLongitude = /** @type {number|undefined} */ (geographicBoundingBox['eastBoundLongitude']); - var northBoundLatitude = /** @type {number|undefined} */ + const northBoundLatitude = /** @type {number|undefined} */ (geographicBoundingBox['northBoundLatitude']); if (westBoundLongitude === undefined || southBoundLatitude === undefined || eastBoundLongitude === undefined || northBoundLatitude === undefined) { @@ -144,7 +144,7 @@ WMSCapabilities.readEXGeographicBoundingBox_ = function(node, objectStack) { */ WMSCapabilities.readCapability_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.CAPABILITY_PARSERS_, node, objectStack); + {}, WMSCapabilities.CAPABILITY_PARSERS_, node, objectStack); }; @@ -156,7 +156,7 @@ WMSCapabilities.readCapability_ = function(node, objectStack) { */ WMSCapabilities.readService_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.SERVICE_PARSERS_, node, objectStack); + {}, WMSCapabilities.SERVICE_PARSERS_, node, objectStack); }; @@ -168,8 +168,8 @@ WMSCapabilities.readService_ = function(node, objectStack) { */ WMSCapabilities.readContactInformation_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.CONTACT_INFORMATION_PARSERS_, - node, objectStack); + {}, WMSCapabilities.CONTACT_INFORMATION_PARSERS_, + node, objectStack); }; @@ -181,8 +181,8 @@ WMSCapabilities.readContactInformation_ = function(node, objectStack) { */ WMSCapabilities.readContactPersonPrimary_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.CONTACT_PERSON_PARSERS_, - node, objectStack); + {}, WMSCapabilities.CONTACT_PERSON_PARSERS_, + node, objectStack); }; @@ -194,8 +194,8 @@ WMSCapabilities.readContactPersonPrimary_ = function(node, objectStack) { */ WMSCapabilities.readContactAddress_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.CONTACT_ADDRESS_PARSERS_, - node, objectStack); + {}, WMSCapabilities.CONTACT_ADDRESS_PARSERS_, + node, objectStack); }; @@ -207,7 +207,7 @@ WMSCapabilities.readContactAddress_ = function(node, objectStack) { */ WMSCapabilities.readException_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - [], WMSCapabilities.EXCEPTION_PARSERS_, node, objectStack); + [], WMSCapabilities.EXCEPTION_PARSERS_, node, objectStack); }; @@ -219,7 +219,7 @@ WMSCapabilities.readException_ = function(node, objectStack) { */ WMSCapabilities.readCapabilityLayer_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.LAYER_PARSERS_, node, objectStack); + {}, WMSCapabilities.LAYER_PARSERS_, node, objectStack); }; @@ -230,50 +230,50 @@ WMSCapabilities.readCapabilityLayer_ = function(node, objectStack) { * @return {Object|undefined} Layer object. */ WMSCapabilities.readLayer_ = function(node, objectStack) { - var parentLayerObject = /** @type {Object.} */ + const parentLayerObject = /** @type {Object.} */ (objectStack[objectStack.length - 1]); - var layerObject = _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.LAYER_PARSERS_, node, objectStack); + const layerObject = _ol_xml_.pushParseAndPop( + {}, WMSCapabilities.LAYER_PARSERS_, node, objectStack); if (!layerObject) { return undefined; } - var queryable = + let queryable = XSD.readBooleanString(node.getAttribute('queryable')); if (queryable === undefined) { queryable = parentLayerObject['queryable']; } layerObject['queryable'] = queryable !== undefined ? queryable : false; - var cascaded = XSD.readNonNegativeIntegerString( - node.getAttribute('cascaded')); + let cascaded = XSD.readNonNegativeIntegerString( + node.getAttribute('cascaded')); if (cascaded === undefined) { cascaded = parentLayerObject['cascaded']; } layerObject['cascaded'] = cascaded; - var opaque = XSD.readBooleanString(node.getAttribute('opaque')); + let opaque = XSD.readBooleanString(node.getAttribute('opaque')); if (opaque === undefined) { opaque = parentLayerObject['opaque']; } layerObject['opaque'] = opaque !== undefined ? opaque : false; - var noSubsets = + let noSubsets = XSD.readBooleanString(node.getAttribute('noSubsets')); if (noSubsets === undefined) { noSubsets = parentLayerObject['noSubsets']; } layerObject['noSubsets'] = noSubsets !== undefined ? noSubsets : false; - var fixedWidth = + let fixedWidth = XSD.readDecimalString(node.getAttribute('fixedWidth')); if (!fixedWidth) { fixedWidth = parentLayerObject['fixedWidth']; } layerObject['fixedWidth'] = fixedWidth; - var fixedHeight = + let fixedHeight = XSD.readDecimalString(node.getAttribute('fixedHeight')); if (!fixedHeight) { fixedHeight = parentLayerObject['fixedHeight']; @@ -281,19 +281,19 @@ WMSCapabilities.readLayer_ = function(node, objectStack) { layerObject['fixedHeight'] = fixedHeight; // See 7.2.4.8 - var addKeys = ['Style', 'CRS', 'AuthorityURL']; + const addKeys = ['Style', 'CRS', 'AuthorityURL']; addKeys.forEach(function(key) { if (key in parentLayerObject) { - var childValue = layerObject[key] || []; + const childValue = layerObject[key] || []; layerObject[key] = childValue.concat(parentLayerObject[key]); } }); - var replaceKeys = ['EX_GeographicBoundingBox', 'BoundingBox', 'Dimension', + const replaceKeys = ['EX_GeographicBoundingBox', 'BoundingBox', 'Dimension', 'Attribution', 'MinScaleDenominator', 'MaxScaleDenominator']; replaceKeys.forEach(function(key) { if (!(key in layerObject)) { - var parentValue = parentLayerObject[key]; + const parentValue = parentLayerObject[key]; layerObject[key] = parentValue; } }); @@ -309,15 +309,15 @@ WMSCapabilities.readLayer_ = function(node, objectStack) { * @return {Object} Dimension object. */ WMSCapabilities.readDimension_ = function(node, objectStack) { - var dimensionObject = { + const dimensionObject = { 'name': node.getAttribute('name'), 'units': node.getAttribute('units'), 'unitSymbol': node.getAttribute('unitSymbol'), 'default': node.getAttribute('default'), 'multipleValues': XSD.readBooleanString( - node.getAttribute('multipleValues')), + node.getAttribute('multipleValues')), 'nearestValue': XSD.readBooleanString( - node.getAttribute('nearestValue')), + node.getAttribute('nearestValue')), 'current': XSD.readBooleanString(node.getAttribute('current')), 'values': XSD.readString(node) }; @@ -333,8 +333,8 @@ WMSCapabilities.readDimension_ = function(node, objectStack) { */ WMSCapabilities.readFormatOnlineresource_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.FORMAT_ONLINERESOURCE_PARSERS_, - node, objectStack); + {}, WMSCapabilities.FORMAT_ONLINERESOURCE_PARSERS_, + node, objectStack); }; @@ -346,7 +346,7 @@ WMSCapabilities.readFormatOnlineresource_ = function(node, objectStack) { */ WMSCapabilities.readRequest_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.REQUEST_PARSERS_, node, objectStack); + {}, WMSCapabilities.REQUEST_PARSERS_, node, objectStack); }; @@ -358,7 +358,7 @@ WMSCapabilities.readRequest_ = function(node, objectStack) { */ WMSCapabilities.readDCPType_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.DCPTYPE_PARSERS_, node, objectStack); + {}, WMSCapabilities.DCPTYPE_PARSERS_, node, objectStack); }; @@ -370,7 +370,7 @@ WMSCapabilities.readDCPType_ = function(node, objectStack) { */ WMSCapabilities.readHTTP_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.HTTP_PARSERS_, node, objectStack); + {}, WMSCapabilities.HTTP_PARSERS_, node, objectStack); }; @@ -382,7 +382,7 @@ WMSCapabilities.readHTTP_ = function(node, objectStack) { */ WMSCapabilities.readOperationType_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.OPERATIONTYPE_PARSERS_, node, objectStack); + {}, WMSCapabilities.OPERATIONTYPE_PARSERS_, node, objectStack); }; @@ -393,10 +393,10 @@ WMSCapabilities.readOperationType_ = function(node, objectStack) { * @return {Object|undefined} Online resource object. */ WMSCapabilities.readSizedFormatOnlineresource_ = function(node, objectStack) { - var formatOnlineresource = + const formatOnlineresource = WMSCapabilities.readFormatOnlineresource_(node, objectStack); if (formatOnlineresource) { - var size = [ + const size = [ XSD.readNonNegativeIntegerString(node.getAttribute('width')), XSD.readNonNegativeIntegerString(node.getAttribute('height')) ]; @@ -414,7 +414,7 @@ WMSCapabilities.readSizedFormatOnlineresource_ = function(node, objectStack) { * @return {Object|undefined} Authority URL object. */ WMSCapabilities.readAuthorityURL_ = function(node, objectStack) { - var authorityObject = + const authorityObject = WMSCapabilities.readFormatOnlineresource_(node, objectStack); if (authorityObject) { authorityObject['name'] = node.getAttribute('name'); @@ -431,7 +431,7 @@ WMSCapabilities.readAuthorityURL_ = function(node, objectStack) { * @return {Object|undefined} Metadata URL object. */ WMSCapabilities.readMetadataURL_ = function(node, objectStack) { - var metadataObject = + const metadataObject = WMSCapabilities.readFormatOnlineresource_(node, objectStack); if (metadataObject) { metadataObject['type'] = node.getAttribute('type'); @@ -449,7 +449,7 @@ WMSCapabilities.readMetadataURL_ = function(node, objectStack) { */ WMSCapabilities.readStyle_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - {}, WMSCapabilities.STYLE_PARSERS_, node, objectStack); + {}, WMSCapabilities.STYLE_PARSERS_, node, objectStack); }; @@ -461,7 +461,7 @@ WMSCapabilities.readStyle_ = function(node, objectStack) { */ WMSCapabilities.readKeywordList_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop( - [], WMSCapabilities.KEYWORDLIST_PARSERS_, node, objectStack); + [], WMSCapabilities.KEYWORDLIST_PARSERS_, node, objectStack); }; @@ -482,12 +482,12 @@ WMSCapabilities.NAMESPACE_URIS_ = [ * @private */ WMSCapabilities.PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'Service': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readService_), - 'Capability': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readCapability_) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'Service': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readService_), + 'Capability': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readCapability_) + }); /** @@ -496,14 +496,14 @@ WMSCapabilities.PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.CAPABILITY_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'Request': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readRequest_), - 'Exception': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readException_), - 'Layer': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readCapabilityLayer_) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'Request': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readRequest_), + 'Exception': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readException_), + 'Layer': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readCapabilityLayer_) + }); /** @@ -512,26 +512,26 @@ WMSCapabilities.CAPABILITY_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.SERVICE_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'Name': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Title': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Abstract': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'KeywordList': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readKeywordList_), - 'OnlineResource': _ol_xml_.makeObjectPropertySetter( - XLink.readHref), - 'ContactInformation': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readContactInformation_), - 'Fees': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'AccessConstraints': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'LayerLimit': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger), - 'MaxWidth': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger), - 'MaxHeight': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'Name': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Title': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Abstract': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'KeywordList': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readKeywordList_), + 'OnlineResource': _ol_xml_.makeObjectPropertySetter( + XLink.readHref), + 'ContactInformation': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readContactInformation_), + 'Fees': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'AccessConstraints': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'LayerLimit': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger), + 'MaxWidth': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger), + 'MaxHeight': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger) + }); /** @@ -540,20 +540,20 @@ WMSCapabilities.SERVICE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.CONTACT_INFORMATION_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'ContactPersonPrimary': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readContactPersonPrimary_), - 'ContactPosition': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'ContactAddress': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readContactAddress_), - 'ContactVoiceTelephone': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'ContactFacsimileTelephone': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'ContactElectronicMailAddress': _ol_xml_.makeObjectPropertySetter( - XSD.readString) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'ContactPersonPrimary': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readContactPersonPrimary_), + 'ContactPosition': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'ContactAddress': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readContactAddress_), + 'ContactVoiceTelephone': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'ContactFacsimileTelephone': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'ContactElectronicMailAddress': _ol_xml_.makeObjectPropertySetter( + XSD.readString) + }); /** @@ -562,12 +562,12 @@ WMSCapabilities.CONTACT_INFORMATION_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.CONTACT_PERSON_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'ContactPerson': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'ContactOrganization': _ol_xml_.makeObjectPropertySetter( - XSD.readString) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'ContactPerson': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'ContactOrganization': _ol_xml_.makeObjectPropertySetter( + XSD.readString) + }); /** @@ -576,15 +576,15 @@ WMSCapabilities.CONTACT_PERSON_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.CONTACT_ADDRESS_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'AddressType': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Address': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'City': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'StateOrProvince': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'PostCode': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Country': _ol_xml_.makeObjectPropertySetter(XSD.readString) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'AddressType': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Address': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'City': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'StateOrProvince': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'PostCode': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Country': _ol_xml_.makeObjectPropertySetter(XSD.readString) + }); /** @@ -593,9 +593,9 @@ WMSCapabilities.CONTACT_ADDRESS_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.EXCEPTION_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'Format': _ol_xml_.makeArrayPusher(XSD.readString) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'Format': _ol_xml_.makeArrayPusher(XSD.readString) + }); /** @@ -604,39 +604,39 @@ WMSCapabilities.EXCEPTION_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.LAYER_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'Name': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Title': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Abstract': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'KeywordList': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readKeywordList_), - 'CRS': _ol_xml_.makeObjectPropertyPusher(XSD.readString), - 'EX_GeographicBoundingBox': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readEXGeographicBoundingBox_), - 'BoundingBox': _ol_xml_.makeObjectPropertyPusher( - WMSCapabilities.readBoundingBox_), - 'Dimension': _ol_xml_.makeObjectPropertyPusher( - WMSCapabilities.readDimension_), - 'Attribution': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readAttribution_), - 'AuthorityURL': _ol_xml_.makeObjectPropertyPusher( - WMSCapabilities.readAuthorityURL_), - 'Identifier': _ol_xml_.makeObjectPropertyPusher(XSD.readString), - 'MetadataURL': _ol_xml_.makeObjectPropertyPusher( - WMSCapabilities.readMetadataURL_), - 'DataURL': _ol_xml_.makeObjectPropertyPusher( - WMSCapabilities.readFormatOnlineresource_), - 'FeatureListURL': _ol_xml_.makeObjectPropertyPusher( - WMSCapabilities.readFormatOnlineresource_), - 'Style': _ol_xml_.makeObjectPropertyPusher( - WMSCapabilities.readStyle_), - 'MinScaleDenominator': _ol_xml_.makeObjectPropertySetter( - XSD.readDecimal), - 'MaxScaleDenominator': _ol_xml_.makeObjectPropertySetter( - XSD.readDecimal), - 'Layer': _ol_xml_.makeObjectPropertyPusher( - WMSCapabilities.readLayer_) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'Name': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Title': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Abstract': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'KeywordList': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readKeywordList_), + 'CRS': _ol_xml_.makeObjectPropertyPusher(XSD.readString), + 'EX_GeographicBoundingBox': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readEXGeographicBoundingBox_), + 'BoundingBox': _ol_xml_.makeObjectPropertyPusher( + WMSCapabilities.readBoundingBox_), + 'Dimension': _ol_xml_.makeObjectPropertyPusher( + WMSCapabilities.readDimension_), + 'Attribution': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readAttribution_), + 'AuthorityURL': _ol_xml_.makeObjectPropertyPusher( + WMSCapabilities.readAuthorityURL_), + 'Identifier': _ol_xml_.makeObjectPropertyPusher(XSD.readString), + 'MetadataURL': _ol_xml_.makeObjectPropertyPusher( + WMSCapabilities.readMetadataURL_), + 'DataURL': _ol_xml_.makeObjectPropertyPusher( + WMSCapabilities.readFormatOnlineresource_), + 'FeatureListURL': _ol_xml_.makeObjectPropertyPusher( + WMSCapabilities.readFormatOnlineresource_), + 'Style': _ol_xml_.makeObjectPropertyPusher( + WMSCapabilities.readStyle_), + 'MinScaleDenominator': _ol_xml_.makeObjectPropertySetter( + XSD.readDecimal), + 'MaxScaleDenominator': _ol_xml_.makeObjectPropertySetter( + XSD.readDecimal), + 'Layer': _ol_xml_.makeObjectPropertyPusher( + WMSCapabilities.readLayer_) + }); /** @@ -645,13 +645,13 @@ WMSCapabilities.LAYER_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.ATTRIBUTION_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'Title': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'OnlineResource': _ol_xml_.makeObjectPropertySetter( - XLink.readHref), - 'LogoURL': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readSizedFormatOnlineresource_) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'Title': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'OnlineResource': _ol_xml_.makeObjectPropertySetter( + XLink.readHref), + 'LogoURL': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readSizedFormatOnlineresource_) + }); /** @@ -662,13 +662,13 @@ WMSCapabilities.ATTRIBUTION_PARSERS_ = _ol_xml_.makeStructureNS( WMSCapabilities.EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS_ = _ol_xml_.makeStructureNS(WMSCapabilities.NAMESPACE_URIS_, { 'westBoundLongitude': _ol_xml_.makeObjectPropertySetter( - XSD.readDecimal), + XSD.readDecimal), 'eastBoundLongitude': _ol_xml_.makeObjectPropertySetter( - XSD.readDecimal), + XSD.readDecimal), 'southBoundLatitude': _ol_xml_.makeObjectPropertySetter( - XSD.readDecimal), + XSD.readDecimal), 'northBoundLatitude': _ol_xml_.makeObjectPropertySetter( - XSD.readDecimal) + XSD.readDecimal) }); @@ -678,14 +678,14 @@ WMSCapabilities.EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS_ = * @private */ WMSCapabilities.REQUEST_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'GetCapabilities': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readOperationType_), - 'GetMap': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readOperationType_), - 'GetFeatureInfo': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readOperationType_) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'GetCapabilities': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readOperationType_), + 'GetMap': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readOperationType_), + 'GetFeatureInfo': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readOperationType_) + }); /** @@ -694,11 +694,11 @@ WMSCapabilities.REQUEST_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.OPERATIONTYPE_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'Format': _ol_xml_.makeObjectPropertyPusher(XSD.readString), - 'DCPType': _ol_xml_.makeObjectPropertyPusher( - WMSCapabilities.readDCPType_) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'Format': _ol_xml_.makeObjectPropertyPusher(XSD.readString), + 'DCPType': _ol_xml_.makeObjectPropertyPusher( + WMSCapabilities.readDCPType_) + }); /** @@ -707,10 +707,10 @@ WMSCapabilities.OPERATIONTYPE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.DCPTYPE_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'HTTP': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readHTTP_) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'HTTP': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readHTTP_) + }); /** @@ -719,12 +719,12 @@ WMSCapabilities.DCPTYPE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.HTTP_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'Get': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readFormatOnlineresource_), - 'Post': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readFormatOnlineresource_) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'Get': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readFormatOnlineresource_), + 'Post': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readFormatOnlineresource_) + }); /** @@ -733,17 +733,17 @@ WMSCapabilities.HTTP_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ WMSCapabilities.STYLE_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'Name': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Title': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'Abstract': _ol_xml_.makeObjectPropertySetter(XSD.readString), - 'LegendURL': _ol_xml_.makeObjectPropertyPusher( - WMSCapabilities.readSizedFormatOnlineresource_), - 'StyleSheetURL': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readFormatOnlineresource_), - 'StyleURL': _ol_xml_.makeObjectPropertySetter( - WMSCapabilities.readFormatOnlineresource_) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'Name': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Title': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'Abstract': _ol_xml_.makeObjectPropertySetter(XSD.readString), + 'LegendURL': _ol_xml_.makeObjectPropertyPusher( + WMSCapabilities.readSizedFormatOnlineresource_), + 'StyleSheetURL': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readFormatOnlineresource_), + 'StyleURL': _ol_xml_.makeObjectPropertySetter( + WMSCapabilities.readFormatOnlineresource_) + }); /** @@ -755,7 +755,7 @@ WMSCapabilities.FORMAT_ONLINERESOURCE_PARSERS_ = _ol_xml_.makeStructureNS(WMSCapabilities.NAMESPACE_URIS_, { 'Format': _ol_xml_.makeObjectPropertySetter(XSD.readString), 'OnlineResource': _ol_xml_.makeObjectPropertySetter( - XLink.readHref) + XLink.readHref) }); @@ -765,7 +765,7 @@ WMSCapabilities.FORMAT_ONLINERESOURCE_PARSERS_ = * @private */ WMSCapabilities.KEYWORDLIST_PARSERS_ = _ol_xml_.makeStructureNS( - WMSCapabilities.NAMESPACE_URIS_, { - 'Keyword': _ol_xml_.makeArrayPusher(XSD.readString) - }); + WMSCapabilities.NAMESPACE_URIS_, { + 'Keyword': _ol_xml_.makeArrayPusher(XSD.readString) + }); export default WMSCapabilities; diff --git a/src/ol/format/WMSGetFeatureInfo.js b/src/ol/format/WMSGetFeatureInfo.js index 1eae9882b3..72502cdf86 100644 --- a/src/ol/format/WMSGetFeatureInfo.js +++ b/src/ol/format/WMSGetFeatureInfo.js @@ -18,9 +18,9 @@ import _ol_xml_ from '../xml.js'; * @param {olx.format.WMSGetFeatureInfoOptions=} opt_options Options. * @api */ -var WMSGetFeatureInfo = function(opt_options) { +const WMSGetFeatureInfo = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @private @@ -88,50 +88,50 @@ WMSGetFeatureInfo.prototype.setLayers = function(layers) { */ WMSGetFeatureInfo.prototype.readFeatures_ = function(node, objectStack) { node.setAttribute('namespaceURI', this.featureNS_); - var localName = node.localName; + const localName = node.localName; /** @type {Array.} */ - var features = []; + let features = []; if (node.childNodes.length === 0) { return features; } if (localName == 'msGMLOutput') { - for (var i = 0, ii = node.childNodes.length; i < ii; i++) { - var layer = node.childNodes[i]; + for (let i = 0, ii = node.childNodes.length; i < ii; i++) { + const layer = node.childNodes[i]; if (layer.nodeType !== Node.ELEMENT_NODE) { continue; } - var context = objectStack[0]; + const context = objectStack[0]; - var toRemove = WMSGetFeatureInfo.layerIdentifier_; - var layerName = layer.localName.replace(toRemove, ''); + const toRemove = WMSGetFeatureInfo.layerIdentifier_; + const layerName = layer.localName.replace(toRemove, ''); if (this.layers_ && !includes(this.layers_, layerName)) { continue; } - var featureType = layerName + + const featureType = layerName + WMSGetFeatureInfo.featureIdentifier_; context['featureType'] = featureType; context['featureNS'] = this.featureNS_; - var parsers = {}; + const parsers = {}; parsers[featureType] = _ol_xml_.makeArrayPusher( - this.gmlFormat_.readFeatureElement, this.gmlFormat_); - var parsersNS = _ol_xml_.makeStructureNS( - [context['featureNS'], null], parsers); + this.gmlFormat_.readFeatureElement, this.gmlFormat_); + const parsersNS = _ol_xml_.makeStructureNS( + [context['featureNS'], null], parsers); layer.setAttribute('namespaceURI', this.featureNS_); - var layerFeatures = _ol_xml_.pushParseAndPop( - [], parsersNS, layer, objectStack, this.gmlFormat_); + const layerFeatures = _ol_xml_.pushParseAndPop( + [], parsersNS, layer, objectStack, this.gmlFormat_); if (layerFeatures) { extend(features, layerFeatures); } } } if (localName == 'FeatureCollection') { - var gmlFeatures = _ol_xml_.pushParseAndPop([], - this.gmlFormat_.FEATURE_COLLECTION_PARSERS, node, - [{}], this.gmlFormat_); + const gmlFeatures = _ol_xml_.pushParseAndPop([], + this.gmlFormat_.FEATURE_COLLECTION_PARSERS, node, + [{}], this.gmlFormat_); if (gmlFeatures) { features = gmlFeatures; } @@ -156,7 +156,7 @@ WMSGetFeatureInfo.prototype.readFeatures; * @inheritDoc */ WMSGetFeatureInfo.prototype.readFeaturesFromNode = function(node, opt_options) { - var options = {}; + const options = {}; if (opt_options) { _ol_obj_.assign(options, this.getReadOptions(node, opt_options)); } diff --git a/src/ol/format/WMTSCapabilities.js b/src/ol/format/WMTSCapabilities.js index 2973a0105b..3ff13193d3 100644 --- a/src/ol/format/WMTSCapabilities.js +++ b/src/ol/format/WMTSCapabilities.js @@ -17,7 +17,7 @@ import _ol_xml_ from '../xml.js'; * @extends {ol.format.XML} * @api */ -var _ol_format_WMTSCapabilities_ = function() { +const _ol_format_WMTSCapabilities_ = function() { XML.call(this); /** @@ -45,7 +45,7 @@ _ol_format_WMTSCapabilities_.prototype.read; * @inheritDoc */ _ol_format_WMTSCapabilities_.prototype.readFromDocument = function(doc) { - for (var n = doc.firstChild; n; n = n.nextSibling) { + for (let n = doc.firstChild; n; n = n.nextSibling) { if (n.nodeType == Node.ELEMENT_NODE) { return this.readFromNode(n); } @@ -58,14 +58,14 @@ _ol_format_WMTSCapabilities_.prototype.readFromDocument = function(doc) { * @inheritDoc */ _ol_format_WMTSCapabilities_.prototype.readFromNode = function(node) { - var version = node.getAttribute('version').trim(); - var WMTSCapabilityObject = this.owsParser_.readFromNode(node); + const version = node.getAttribute('version').trim(); + let WMTSCapabilityObject = this.owsParser_.readFromNode(node); if (!WMTSCapabilityObject) { return null; } WMTSCapabilityObject['version'] = version; WMTSCapabilityObject = _ol_xml_.pushParseAndPop(WMTSCapabilityObject, - _ol_format_WMTSCapabilities_.PARSERS_, node, []); + _ol_format_WMTSCapabilities_.PARSERS_, node, []); return WMTSCapabilityObject ? WMTSCapabilityObject : null; }; @@ -78,7 +78,7 @@ _ol_format_WMTSCapabilities_.prototype.readFromNode = function(node) { */ _ol_format_WMTSCapabilities_.readContents_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - _ol_format_WMTSCapabilities_.CONTENTS_PARSERS_, node, objectStack); + _ol_format_WMTSCapabilities_.CONTENTS_PARSERS_, node, objectStack); }; @@ -90,7 +90,7 @@ _ol_format_WMTSCapabilities_.readContents_ = function(node, objectStack) { */ _ol_format_WMTSCapabilities_.readLayer_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - _ol_format_WMTSCapabilities_.LAYER_PARSERS_, node, objectStack); + _ol_format_WMTSCapabilities_.LAYER_PARSERS_, node, objectStack); }; @@ -102,7 +102,7 @@ _ol_format_WMTSCapabilities_.readLayer_ = function(node, objectStack) { */ _ol_format_WMTSCapabilities_.readTileMatrixSet_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - _ol_format_WMTSCapabilities_.TMS_PARSERS_, node, objectStack); + _ol_format_WMTSCapabilities_.TMS_PARSERS_, node, objectStack); }; @@ -113,12 +113,12 @@ _ol_format_WMTSCapabilities_.readTileMatrixSet_ = function(node, objectStack) { * @return {Object|undefined} Style object. */ _ol_format_WMTSCapabilities_.readStyle_ = function(node, objectStack) { - var style = _ol_xml_.pushParseAndPop({}, - _ol_format_WMTSCapabilities_.STYLE_PARSERS_, node, objectStack); + const style = _ol_xml_.pushParseAndPop({}, + _ol_format_WMTSCapabilities_.STYLE_PARSERS_, node, objectStack); if (!style) { return undefined; } - var isDefault = node.getAttribute('isDefault') === 'true'; + const isDefault = node.getAttribute('isDefault') === 'true'; style['isDefault'] = isDefault; return style; @@ -132,9 +132,9 @@ _ol_format_WMTSCapabilities_.readStyle_ = function(node, objectStack) { * @return {Object|undefined} Tile Matrix Set Link object. */ _ol_format_WMTSCapabilities_.readTileMatrixSetLink_ = function(node, - objectStack) { + objectStack) { return _ol_xml_.pushParseAndPop({}, - _ol_format_WMTSCapabilities_.TMS_LINKS_PARSERS_, node, objectStack); + _ol_format_WMTSCapabilities_.TMS_LINKS_PARSERS_, node, objectStack); }; @@ -146,7 +146,7 @@ _ol_format_WMTSCapabilities_.readTileMatrixSetLink_ = function(node, */ _ol_format_WMTSCapabilities_.readDimensions_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - _ol_format_WMTSCapabilities_.DIMENSION_PARSERS_, node, objectStack); + _ol_format_WMTSCapabilities_.DIMENSION_PARSERS_, node, objectStack); }; @@ -157,10 +157,10 @@ _ol_format_WMTSCapabilities_.readDimensions_ = function(node, objectStack) { * @return {Object|undefined} Resource URL object. */ _ol_format_WMTSCapabilities_.readResourceUrl_ = function(node, objectStack) { - var format = node.getAttribute('format'); - var template = node.getAttribute('template'); - var resourceType = node.getAttribute('resourceType'); - var resource = {}; + const format = node.getAttribute('format'); + const template = node.getAttribute('template'); + const resourceType = node.getAttribute('resourceType'); + const resource = {}; if (format) { resource['format'] = format; } @@ -181,8 +181,8 @@ _ol_format_WMTSCapabilities_.readResourceUrl_ = function(node, objectStack) { * @return {Object|undefined} WGS84 BBox object. */ _ol_format_WMTSCapabilities_.readWgs84BoundingBox_ = function(node, objectStack) { - var coordinates = _ol_xml_.pushParseAndPop([], - _ol_format_WMTSCapabilities_.WGS84_BBOX_READERS_, node, objectStack); + const coordinates = _ol_xml_.pushParseAndPop([], + _ol_format_WMTSCapabilities_.WGS84_BBOX_READERS_, node, objectStack); if (coordinates.length != 2) { return undefined; } @@ -197,7 +197,7 @@ _ol_format_WMTSCapabilities_.readWgs84BoundingBox_ = function(node, objectStack) * @return {Object|undefined} Legend object. */ _ol_format_WMTSCapabilities_.readLegendUrl_ = function(node, objectStack) { - var legend = {}; + const legend = {}; legend['format'] = node.getAttribute('format'); legend['href'] = XLink.readHref(node); return legend; @@ -211,12 +211,12 @@ _ol_format_WMTSCapabilities_.readLegendUrl_ = function(node, objectStack) { * @return {Object|undefined} Coordinates object. */ _ol_format_WMTSCapabilities_.readCoordinates_ = function(node, objectStack) { - var coordinates = XSD.readString(node).split(' '); + const coordinates = XSD.readString(node).split(' '); if (!coordinates || coordinates.length != 2) { return undefined; } - var x = +coordinates[0]; - var y = +coordinates[1]; + const x = +coordinates[0]; + const y = +coordinates[1]; if (isNaN(x) || isNaN(y)) { return undefined; } @@ -232,7 +232,7 @@ _ol_format_WMTSCapabilities_.readCoordinates_ = function(node, objectStack) { */ _ol_format_WMTSCapabilities_.readTileMatrix_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - _ol_format_WMTSCapabilities_.TM_PARSERS_, node, objectStack); + _ol_format_WMTSCapabilities_.TM_PARSERS_, node, objectStack); }; @@ -243,10 +243,10 @@ _ol_format_WMTSCapabilities_.readTileMatrix_ = function(node, objectStack) { * @return {Object|undefined} TileMatrixSetLimits Object. */ _ol_format_WMTSCapabilities_.readTileMatrixLimitsList_ = function(node, - objectStack) { + objectStack) { return _ol_xml_.pushParseAndPop([], - _ol_format_WMTSCapabilities_.TMS_LIMITS_LIST_PARSERS_, node, - objectStack); + _ol_format_WMTSCapabilities_.TMS_LIMITS_LIST_PARSERS_, node, + objectStack); }; @@ -258,7 +258,7 @@ _ol_format_WMTSCapabilities_.readTileMatrixLimitsList_ = function(node, */ _ol_format_WMTSCapabilities_.readTileMatrixLimits_ = function(node, objectStack) { return _ol_xml_.pushParseAndPop({}, - _ol_format_WMTSCapabilities_.TMS_LIMITS_PARSERS_, node, objectStack); + _ol_format_WMTSCapabilities_.TMS_LIMITS_PARSERS_, node, objectStack); }; @@ -290,10 +290,10 @@ _ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_ = [ * @private */ _ol_format_WMTSCapabilities_.PARSERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { - 'Contents': _ol_xml_.makeObjectPropertySetter( - _ol_format_WMTSCapabilities_.readContents_) - }); + _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { + 'Contents': _ol_xml_.makeObjectPropertySetter( + _ol_format_WMTSCapabilities_.readContents_) + }); /** @@ -302,12 +302,12 @@ _ol_format_WMTSCapabilities_.PARSERS_ = _ol_xml_.makeStructureNS( * @private */ _ol_format_WMTSCapabilities_.CONTENTS_PARSERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { - 'Layer': _ol_xml_.makeObjectPropertyPusher( - _ol_format_WMTSCapabilities_.readLayer_), - 'TileMatrixSet': _ol_xml_.makeObjectPropertyPusher( - _ol_format_WMTSCapabilities_.readTileMatrixSet_) - }); + _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { + 'Layer': _ol_xml_.makeObjectPropertyPusher( + _ol_format_WMTSCapabilities_.readLayer_), + 'TileMatrixSet': _ol_xml_.makeObjectPropertyPusher( + _ol_format_WMTSCapabilities_.readTileMatrixSet_) + }); /** @@ -316,27 +316,27 @@ _ol_format_WMTSCapabilities_.CONTENTS_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ _ol_format_WMTSCapabilities_.LAYER_PARSERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { - 'Style': _ol_xml_.makeObjectPropertyPusher( - _ol_format_WMTSCapabilities_.readStyle_), - 'Format': _ol_xml_.makeObjectPropertyPusher( - XSD.readString), - 'TileMatrixSetLink': _ol_xml_.makeObjectPropertyPusher( - _ol_format_WMTSCapabilities_.readTileMatrixSetLink_), - 'Dimension': _ol_xml_.makeObjectPropertyPusher( - _ol_format_WMTSCapabilities_.readDimensions_), - 'ResourceURL': _ol_xml_.makeObjectPropertyPusher( - _ol_format_WMTSCapabilities_.readResourceUrl_) - }, _ol_xml_.makeStructureNS(_ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { - 'Title': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'Abstract': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'WGS84BoundingBox': _ol_xml_.makeObjectPropertySetter( - _ol_format_WMTSCapabilities_.readWgs84BoundingBox_), - 'Identifier': _ol_xml_.makeObjectPropertySetter( - XSD.readString) - })); + _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { + 'Style': _ol_xml_.makeObjectPropertyPusher( + _ol_format_WMTSCapabilities_.readStyle_), + 'Format': _ol_xml_.makeObjectPropertyPusher( + XSD.readString), + 'TileMatrixSetLink': _ol_xml_.makeObjectPropertyPusher( + _ol_format_WMTSCapabilities_.readTileMatrixSetLink_), + 'Dimension': _ol_xml_.makeObjectPropertyPusher( + _ol_format_WMTSCapabilities_.readDimensions_), + 'ResourceURL': _ol_xml_.makeObjectPropertyPusher( + _ol_format_WMTSCapabilities_.readResourceUrl_) + }, _ol_xml_.makeStructureNS(_ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { + 'Title': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'Abstract': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'WGS84BoundingBox': _ol_xml_.makeObjectPropertySetter( + _ol_format_WMTSCapabilities_.readWgs84BoundingBox_), + 'Identifier': _ol_xml_.makeObjectPropertySetter( + XSD.readString) + })); /** @@ -345,15 +345,15 @@ _ol_format_WMTSCapabilities_.LAYER_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ _ol_format_WMTSCapabilities_.STYLE_PARSERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { - 'LegendURL': _ol_xml_.makeObjectPropertyPusher( - _ol_format_WMTSCapabilities_.readLegendUrl_) - }, _ol_xml_.makeStructureNS(_ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { - 'Title': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'Identifier': _ol_xml_.makeObjectPropertySetter( - XSD.readString) - })); + _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { + 'LegendURL': _ol_xml_.makeObjectPropertyPusher( + _ol_format_WMTSCapabilities_.readLegendUrl_) + }, _ol_xml_.makeStructureNS(_ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { + 'Title': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'Identifier': _ol_xml_.makeObjectPropertySetter( + XSD.readString) + })); /** @@ -362,12 +362,12 @@ _ol_format_WMTSCapabilities_.STYLE_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ _ol_format_WMTSCapabilities_.TMS_LINKS_PARSERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { - 'TileMatrixSet': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'TileMatrixSetLimits': _ol_xml_.makeObjectPropertySetter( - _ol_format_WMTSCapabilities_.readTileMatrixLimitsList_) - }); + _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { + 'TileMatrixSet': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'TileMatrixSetLimits': _ol_xml_.makeObjectPropertySetter( + _ol_format_WMTSCapabilities_.readTileMatrixLimitsList_) + }); /** * @const @@ -375,10 +375,10 @@ _ol_format_WMTSCapabilities_.TMS_LINKS_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ _ol_format_WMTSCapabilities_.TMS_LIMITS_LIST_PARSERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { - 'TileMatrixLimits': _ol_xml_.makeArrayPusher( - _ol_format_WMTSCapabilities_.readTileMatrixLimits_) - }); + _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { + 'TileMatrixLimits': _ol_xml_.makeArrayPusher( + _ol_format_WMTSCapabilities_.readTileMatrixLimits_) + }); /** @@ -387,18 +387,18 @@ _ol_format_WMTSCapabilities_.TMS_LIMITS_LIST_PARSERS_ = _ol_xml_.makeStructureNS * @private */ _ol_format_WMTSCapabilities_.TMS_LIMITS_PARSERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { - 'TileMatrix': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'MinTileRow': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger), - 'MaxTileRow': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger), - 'MinTileCol': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger), - 'MaxTileCol': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger) - }); + _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { + 'TileMatrix': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'MinTileRow': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger), + 'MaxTileRow': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger), + 'MinTileCol': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger), + 'MaxTileCol': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger) + }); /** @@ -407,15 +407,15 @@ _ol_format_WMTSCapabilities_.TMS_LIMITS_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ _ol_format_WMTSCapabilities_.DIMENSION_PARSERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { - 'Default': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'Value': _ol_xml_.makeObjectPropertyPusher( - XSD.readString) - }, _ol_xml_.makeStructureNS(_ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { - 'Identifier': _ol_xml_.makeObjectPropertySetter( - XSD.readString) - })); + _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { + 'Default': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'Value': _ol_xml_.makeObjectPropertyPusher( + XSD.readString) + }, _ol_xml_.makeStructureNS(_ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { + 'Identifier': _ol_xml_.makeObjectPropertySetter( + XSD.readString) + })); /** @@ -424,12 +424,12 @@ _ol_format_WMTSCapabilities_.DIMENSION_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ _ol_format_WMTSCapabilities_.WGS84_BBOX_READERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { - 'LowerCorner': _ol_xml_.makeArrayPusher( - _ol_format_WMTSCapabilities_.readCoordinates_), - 'UpperCorner': _ol_xml_.makeArrayPusher( - _ol_format_WMTSCapabilities_.readCoordinates_) - }); + _ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { + 'LowerCorner': _ol_xml_.makeArrayPusher( + _ol_format_WMTSCapabilities_.readCoordinates_), + 'UpperCorner': _ol_xml_.makeArrayPusher( + _ol_format_WMTSCapabilities_.readCoordinates_) + }); /** @@ -438,17 +438,17 @@ _ol_format_WMTSCapabilities_.WGS84_BBOX_READERS_ = _ol_xml_.makeStructureNS( * @private */ _ol_format_WMTSCapabilities_.TMS_PARSERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { - 'WellKnownScaleSet': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'TileMatrix': _ol_xml_.makeObjectPropertyPusher( - _ol_format_WMTSCapabilities_.readTileMatrix_) - }, _ol_xml_.makeStructureNS(_ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { - 'SupportedCRS': _ol_xml_.makeObjectPropertySetter( - XSD.readString), - 'Identifier': _ol_xml_.makeObjectPropertySetter( - XSD.readString) - })); + _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { + 'WellKnownScaleSet': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'TileMatrix': _ol_xml_.makeObjectPropertyPusher( + _ol_format_WMTSCapabilities_.readTileMatrix_) + }, _ol_xml_.makeStructureNS(_ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { + 'SupportedCRS': _ol_xml_.makeObjectPropertySetter( + XSD.readString), + 'Identifier': _ol_xml_.makeObjectPropertySetter( + XSD.readString) + })); /** @@ -457,21 +457,21 @@ _ol_format_WMTSCapabilities_.TMS_PARSERS_ = _ol_xml_.makeStructureNS( * @private */ _ol_format_WMTSCapabilities_.TM_PARSERS_ = _ol_xml_.makeStructureNS( - _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { - 'TopLeftCorner': _ol_xml_.makeObjectPropertySetter( - _ol_format_WMTSCapabilities_.readCoordinates_), - 'ScaleDenominator': _ol_xml_.makeObjectPropertySetter( - XSD.readDecimal), - 'TileWidth': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger), - 'TileHeight': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger), - 'MatrixWidth': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger), - 'MatrixHeight': _ol_xml_.makeObjectPropertySetter( - XSD.readNonNegativeInteger) - }, _ol_xml_.makeStructureNS(_ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { - 'Identifier': _ol_xml_.makeObjectPropertySetter( - XSD.readString) - })); + _ol_format_WMTSCapabilities_.NAMESPACE_URIS_, { + 'TopLeftCorner': _ol_xml_.makeObjectPropertySetter( + _ol_format_WMTSCapabilities_.readCoordinates_), + 'ScaleDenominator': _ol_xml_.makeObjectPropertySetter( + XSD.readDecimal), + 'TileWidth': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger), + 'TileHeight': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger), + 'MatrixWidth': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger), + 'MatrixHeight': _ol_xml_.makeObjectPropertySetter( + XSD.readNonNegativeInteger) + }, _ol_xml_.makeStructureNS(_ol_format_WMTSCapabilities_.OWS_NAMESPACE_URIS_, { + 'Identifier': _ol_xml_.makeObjectPropertySetter( + XSD.readString) + })); export default _ol_format_WMTSCapabilities_; diff --git a/src/ol/format/XLink.js b/src/ol/format/XLink.js index 6b0f256d64..db684f45f9 100644 --- a/src/ol/format/XLink.js +++ b/src/ol/format/XLink.js @@ -1,14 +1,14 @@ /** * @module ol/format/XLink */ -var XLink = {}; +const XLink = {}; /** * @const * @type {string} */ -var NAMESPACE_URI = 'http://www.w3.org/1999/xlink'; +const NAMESPACE_URI = 'http://www.w3.org/1999/xlink'; /** diff --git a/src/ol/format/XML.js b/src/ol/format/XML.js index c5e6af0649..c3b528d757 100644 --- a/src/ol/format/XML.js +++ b/src/ol/format/XML.js @@ -11,7 +11,7 @@ import _ol_xml_ from '../xml.js'; * @abstract * @struct */ -var XML = function() { +const XML = function() { }; @@ -25,7 +25,7 @@ XML.prototype.read = function(source) { } else if (_ol_xml_.isNode(source)) { return this.readFromNode(/** @type {Node} */ (source)); } else if (typeof source === 'string') { - var doc = _ol_xml_.parse(source); + const doc = _ol_xml_.parse(source); return this.readFromDocument(doc); } else { return null; diff --git a/src/ol/format/XMLFeature.js b/src/ol/format/XMLFeature.js index dde29bffdc..d5d3dafe5d 100644 --- a/src/ol/format/XMLFeature.js +++ b/src/ol/format/XMLFeature.js @@ -17,7 +17,7 @@ import _ol_xml_ from '../xml.js'; * @abstract * @extends {ol.format.Feature} */ -var XMLFeature = function() { +const XMLFeature = function() { /** * @type {XMLSerializer} @@ -45,11 +45,11 @@ XMLFeature.prototype.getType = function() { XMLFeature.prototype.readFeature = function(source, opt_options) { if (_ol_xml_.isDocument(source)) { return this.readFeatureFromDocument( - /** @type {Document} */ (source), opt_options); + /** @type {Document} */ (source), opt_options); } else if (_ol_xml_.isNode(source)) { return this.readFeatureFromNode(/** @type {Node} */ (source), opt_options); } else if (typeof source === 'string') { - var doc = _ol_xml_.parse(source); + const doc = _ol_xml_.parse(source); return this.readFeatureFromDocument(doc, opt_options); } else { return null; @@ -63,8 +63,8 @@ XMLFeature.prototype.readFeature = function(source, opt_options) { * @return {ol.Feature} Feature. */ XMLFeature.prototype.readFeatureFromDocument = function( - doc, opt_options) { - var features = this.readFeaturesFromDocument(doc, opt_options); + doc, opt_options) { + const features = this.readFeaturesFromDocument(doc, opt_options); if (features.length > 0) { return features[0]; } else { @@ -89,11 +89,11 @@ XMLFeature.prototype.readFeatureFromNode = function(node, opt_options) { XMLFeature.prototype.readFeatures = function(source, opt_options) { if (_ol_xml_.isDocument(source)) { return this.readFeaturesFromDocument( - /** @type {Document} */ (source), opt_options); + /** @type {Document} */ (source), opt_options); } else if (_ol_xml_.isNode(source)) { return this.readFeaturesFromNode(/** @type {Node} */ (source), opt_options); } else if (typeof source === 'string') { - var doc = _ol_xml_.parse(source); + const doc = _ol_xml_.parse(source); return this.readFeaturesFromDocument(doc, opt_options); } else { return []; @@ -108,10 +108,10 @@ XMLFeature.prototype.readFeatures = function(source, opt_options) { * @return {Array.} Features. */ XMLFeature.prototype.readFeaturesFromDocument = function( - doc, opt_options) { + doc, opt_options) { /** @type {Array.} */ - var features = []; - var n; + const features = []; + let n; for (n = doc.firstChild; n; n = n.nextSibling) { if (n.nodeType == Node.ELEMENT_NODE) { extend(features, this.readFeaturesFromNode(n, opt_options)); @@ -137,11 +137,11 @@ XMLFeature.prototype.readFeaturesFromNode = function(node, opt_options) {}; XMLFeature.prototype.readGeometry = function(source, opt_options) { if (_ol_xml_.isDocument(source)) { return this.readGeometryFromDocument( - /** @type {Document} */ (source), opt_options); + /** @type {Document} */ (source), opt_options); } else if (_ol_xml_.isNode(source)) { return this.readGeometryFromNode(/** @type {Node} */ (source), opt_options); } else if (typeof source === 'string') { - var doc = _ol_xml_.parse(source); + const doc = _ol_xml_.parse(source); return this.readGeometryFromDocument(doc, opt_options); } else { return null; @@ -180,7 +180,7 @@ XMLFeature.prototype.readProjection = function(source) { } else if (_ol_xml_.isNode(source)) { return this.readProjectionFromNode(/** @type {Node} */ (source)); } else if (typeof source === 'string') { - var doc = _ol_xml_.parse(source); + const doc = _ol_xml_.parse(source); return this.readProjectionFromDocument(doc); } else { return null; @@ -212,7 +212,7 @@ XMLFeature.prototype.readProjectionFromNode = function(node) { * @inheritDoc */ XMLFeature.prototype.writeFeature = function(feature, opt_options) { - var node = this.writeFeatureNode(feature, opt_options); + const node = this.writeFeatureNode(feature, opt_options); return this.xmlSerializer_.serializeToString(node); }; @@ -232,7 +232,7 @@ XMLFeature.prototype.writeFeatureNode = function(feature, opt_options) { * @inheritDoc */ XMLFeature.prototype.writeFeatures = function(features, opt_options) { - var node = this.writeFeaturesNode(features, opt_options); + const node = this.writeFeaturesNode(features, opt_options); return this.xmlSerializer_.serializeToString(node); }; @@ -251,7 +251,7 @@ XMLFeature.prototype.writeFeaturesNode = function(features, opt_options) { * @inheritDoc */ XMLFeature.prototype.writeGeometry = function(geometry, opt_options) { - var node = this.writeGeometryNode(geometry, opt_options); + const node = this.writeGeometryNode(geometry, opt_options); return this.xmlSerializer_.serializeToString(node); }; diff --git a/src/ol/format/XSD.js b/src/ol/format/XSD.js index cf51d857be..bed9b09e7e 100644 --- a/src/ol/format/XSD.js +++ b/src/ol/format/XSD.js @@ -3,7 +3,7 @@ */ import _ol_xml_ from '../xml.js'; import _ol_string_ from '../string.js'; -var XSD = {}; +const XSD = {}; /** @@ -11,7 +11,7 @@ var XSD = {}; * @return {boolean|undefined} Boolean. */ XSD.readBoolean = function(node) { - var s = _ol_xml_.getAllTextContent(node, false); + const s = _ol_xml_.getAllTextContent(node, false); return XSD.readBooleanString(s); }; @@ -21,7 +21,7 @@ XSD.readBoolean = function(node) { * @return {boolean|undefined} Boolean. */ XSD.readBooleanString = function(string) { - var m = /^\s*(true|1)|(false|0)\s*$/.exec(string); + const m = /^\s*(true|1)|(false|0)\s*$/.exec(string); if (m) { return m[1] !== undefined || false; } else { @@ -35,8 +35,8 @@ XSD.readBooleanString = function(string) { * @return {number|undefined} DateTime in seconds. */ XSD.readDateTime = function(node) { - var s = _ol_xml_.getAllTextContent(node, false); - var dateTime = Date.parse(s); + const s = _ol_xml_.getAllTextContent(node, false); + const dateTime = Date.parse(s); return isNaN(dateTime) ? undefined : dateTime / 1000; }; @@ -46,7 +46,7 @@ XSD.readDateTime = function(node) { * @return {number|undefined} Decimal. */ XSD.readDecimal = function(node) { - var s = _ol_xml_.getAllTextContent(node, false); + const s = _ol_xml_.getAllTextContent(node, false); return XSD.readDecimalString(s); }; @@ -57,7 +57,7 @@ XSD.readDecimal = function(node) { */ XSD.readDecimalString = function(string) { // FIXME check spec - var m = /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*$/i.exec(string); + const m = /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*$/i.exec(string); if (m) { return parseFloat(m[1]); } else { @@ -71,7 +71,7 @@ XSD.readDecimalString = function(string) { * @return {number|undefined} Non negative integer. */ XSD.readNonNegativeInteger = function(node) { - var s = _ol_xml_.getAllTextContent(node, false); + const s = _ol_xml_.getAllTextContent(node, false); return XSD.readNonNegativeIntegerString(s); }; @@ -81,7 +81,7 @@ XSD.readNonNegativeInteger = function(node) { * @return {number|undefined} Non negative integer. */ XSD.readNonNegativeIntegerString = function(string) { - var m = /^\s*(\d+)\s*$/.exec(string); + const m = /^\s*(\d+)\s*$/.exec(string); if (m) { return parseInt(m[1], 10); } else { @@ -122,8 +122,8 @@ XSD.writeCDATASection = function(node, string) { * @param {number} dateTime DateTime in seconds. */ XSD.writeDateTimeTextNode = function(node, dateTime) { - var date = new Date(dateTime * 1000); - var string = date.getUTCFullYear() + '-' + + const date = new Date(dateTime * 1000); + const string = date.getUTCFullYear() + '-' + _ol_string_.padNumber(date.getUTCMonth() + 1, 2) + '-' + _ol_string_.padNumber(date.getUTCDate(), 2) + 'T' + _ol_string_.padNumber(date.getUTCHours(), 2) + ':' + @@ -138,7 +138,7 @@ XSD.writeDateTimeTextNode = function(node, dateTime) { * @param {number} decimal Decimal. */ XSD.writeDecimalTextNode = function(node, decimal) { - var string = decimal.toPrecision(); + const string = decimal.toPrecision(); node.appendChild(_ol_xml_.DOCUMENT.createTextNode(string)); }; @@ -148,7 +148,7 @@ XSD.writeDecimalTextNode = function(node, decimal) { * @param {number} nonNegativeInteger Non negative integer. */ XSD.writeNonNegativeIntegerTextNode = function(node, nonNegativeInteger) { - var string = nonNegativeInteger.toString(); + const string = nonNegativeInteger.toString(); node.appendChild(_ol_xml_.DOCUMENT.createTextNode(string)); }; diff --git a/src/ol/format/filter.js b/src/ol/format/filter.js index f67492f7bd..9565523a7c 100644 --- a/src/ol/format/filter.js +++ b/src/ol/format/filter.js @@ -18,7 +18,7 @@ import _ol_format_filter_Not_ from '../format/filter/Not.js'; import _ol_format_filter_NotEqualTo_ from '../format/filter/NotEqualTo.js'; import _ol_format_filter_Or_ from '../format/filter/Or.js'; import _ol_format_filter_Within_ from '../format/filter/Within.js'; -var _ol_format_filter_ = {}; +const _ol_format_filter_ = {}; /** @@ -29,7 +29,7 @@ var _ol_format_filter_ = {}; * @api */ _ol_format_filter_.and = function(conditions) { - var params = [null].concat(Array.prototype.slice.call(arguments)); + const params = [null].concat(Array.prototype.slice.call(arguments)); return new (Function.prototype.bind.apply(_ol_format_filter_And_, params)); }; @@ -42,7 +42,7 @@ _ol_format_filter_.and = function(conditions) { * @api */ _ol_format_filter_.or = function(conditions) { - var params = [null].concat(Array.prototype.slice.call(arguments)); + const params = [null].concat(Array.prototype.slice.call(arguments)); return new (Function.prototype.bind.apply(_ol_format_filter_Or_, params)); }; @@ -245,9 +245,9 @@ _ol_format_filter_.between = function(propertyName, lowerBoundary, upperBoundary * @api */ _ol_format_filter_.like = function(propertyName, pattern, - opt_wildCard, opt_singleChar, opt_escapeChar, opt_matchCase) { + opt_wildCard, opt_singleChar, opt_escapeChar, opt_matchCase) { return new _ol_format_filter_IsLike_(propertyName, pattern, - opt_wildCard, opt_singleChar, opt_escapeChar, opt_matchCase); + opt_wildCard, opt_singleChar, opt_escapeChar, opt_matchCase); }; diff --git a/src/ol/format/filter/And.js b/src/ol/format/filter/And.js index 13c5c46a48..d24bcf9f73 100644 --- a/src/ol/format/filter/And.js +++ b/src/ol/format/filter/And.js @@ -13,8 +13,8 @@ import LogicalNary from '../filter/LogicalNary.js'; * @param {...ol.format.filter.Filter} conditions Conditions. * @extends {ol.format.filter.LogicalNary} */ -var And = function(conditions) { - var params = ['And'].concat(Array.prototype.slice.call(arguments)); +const And = function(conditions) { + const params = ['And'].concat(Array.prototype.slice.call(arguments)); LogicalNary.apply(this, params); }; diff --git a/src/ol/format/filter/Bbox.js b/src/ol/format/filter/Bbox.js index 6fd4f309cc..cece19978c 100644 --- a/src/ol/format/filter/Bbox.js +++ b/src/ol/format/filter/Bbox.js @@ -17,7 +17,7 @@ import Filter from '../filter/Filter.js'; * @extends {ol.format.filter.Filter} * @api */ -var Bbox = function(geometryName, extent, opt_srsName) { +const Bbox = function(geometryName, extent, opt_srsName) { Filter.call(this, 'BBOX'); diff --git a/src/ol/format/filter/Comparison.js b/src/ol/format/filter/Comparison.js index b30f1df5e7..0ada715ad1 100644 --- a/src/ol/format/filter/Comparison.js +++ b/src/ol/format/filter/Comparison.js @@ -15,7 +15,7 @@ import Filter from '../filter/Filter.js'; * @param {!string} propertyName Name of the context property to compare. * @extends {ol.format.filter.Filter} */ -var Comparison = function(tagName, propertyName) { +const Comparison = function(tagName, propertyName) { Filter.call(this, tagName); diff --git a/src/ol/format/filter/ComparisonBinary.js b/src/ol/format/filter/ComparisonBinary.js index d169596aac..bae55f060c 100644 --- a/src/ol/format/filter/ComparisonBinary.js +++ b/src/ol/format/filter/ComparisonBinary.js @@ -17,7 +17,7 @@ import Comparison from '../filter/Comparison.js'; * @param {boolean=} opt_matchCase Case-sensitive? * @extends {ol.format.filter.Comparison} */ -var ComparisonBinary = function(tagName, propertyName, expression, opt_matchCase) { +const ComparisonBinary = function(tagName, propertyName, expression, opt_matchCase) { Comparison.call(this, tagName, propertyName); diff --git a/src/ol/format/filter/Contains.js b/src/ol/format/filter/Contains.js index 2b9a593b67..93b42bb1e3 100644 --- a/src/ol/format/filter/Contains.js +++ b/src/ol/format/filter/Contains.js @@ -17,7 +17,7 @@ import Spatial from '../filter/Spatial.js'; * @extends {ol.format.filter.Spatial} * @api */ -var Contains = function(geometryName, geometry, opt_srsName) { +const Contains = function(geometryName, geometry, opt_srsName) { Spatial.call(this, 'Contains', geometryName, geometry, opt_srsName); diff --git a/src/ol/format/filter/During.js b/src/ol/format/filter/During.js index 0f4c3e7c17..337ef0e906 100644 --- a/src/ol/format/filter/During.js +++ b/src/ol/format/filter/During.js @@ -15,7 +15,7 @@ import Comparison from '../filter/Comparison.js'; * @extends {ol.format.filter.Comparison} * @api */ -var During = function(propertyName, begin, end) { +const During = function(propertyName, begin, end) { Comparison.call(this, 'During', propertyName); /** diff --git a/src/ol/format/filter/EqualTo.js b/src/ol/format/filter/EqualTo.js index 63faedc574..e122dcf090 100644 --- a/src/ol/format/filter/EqualTo.js +++ b/src/ol/format/filter/EqualTo.js @@ -15,7 +15,7 @@ import ComparisonBinary from '../filter/ComparisonBinary.js'; * @extends {ol.format.filter.ComparisonBinary} * @api */ -var EqualTo = function(propertyName, expression, opt_matchCase) { +const EqualTo = function(propertyName, expression, opt_matchCase) { ComparisonBinary.call(this, 'PropertyIsEqualTo', propertyName, expression, opt_matchCase); }; diff --git a/src/ol/format/filter/Filter.js b/src/ol/format/filter/Filter.js index 336fe29631..7ec8c2f36e 100644 --- a/src/ol/format/filter/Filter.js +++ b/src/ol/format/filter/Filter.js @@ -13,7 +13,7 @@ * @param {!string} tagName The XML tag name for this filter. * @struct */ -var Filter = function(tagName) { +const Filter = function(tagName) { /** * @private diff --git a/src/ol/format/filter/GreaterThan.js b/src/ol/format/filter/GreaterThan.js index 0607cdd0ef..38d42537fa 100644 --- a/src/ol/format/filter/GreaterThan.js +++ b/src/ol/format/filter/GreaterThan.js @@ -14,7 +14,7 @@ import ComparisonBinary from '../filter/ComparisonBinary.js'; * @extends {ol.format.filter.ComparisonBinary} * @api */ -var GreaterThan = function(propertyName, expression) { +const GreaterThan = function(propertyName, expression) { ComparisonBinary.call(this, 'PropertyIsGreaterThan', propertyName, expression); }; diff --git a/src/ol/format/filter/GreaterThanOrEqualTo.js b/src/ol/format/filter/GreaterThanOrEqualTo.js index d5bea6173e..668243621e 100644 --- a/src/ol/format/filter/GreaterThanOrEqualTo.js +++ b/src/ol/format/filter/GreaterThanOrEqualTo.js @@ -14,7 +14,7 @@ import ComparisonBinary from '../filter/ComparisonBinary.js'; * @extends {ol.format.filter.ComparisonBinary} * @api */ -var GreaterThanOrEqualTo = function(propertyName, expression) { +const GreaterThanOrEqualTo = function(propertyName, expression) { ComparisonBinary.call(this, 'PropertyIsGreaterThanOrEqualTo', propertyName, expression); }; diff --git a/src/ol/format/filter/Intersects.js b/src/ol/format/filter/Intersects.js index a8f12771cf..9d401d1f95 100644 --- a/src/ol/format/filter/Intersects.js +++ b/src/ol/format/filter/Intersects.js @@ -17,7 +17,7 @@ import Spatial from '../filter/Spatial.js'; * @extends {ol.format.filter.Spatial} * @api */ -var Intersects = function(geometryName, geometry, opt_srsName) { +const Intersects = function(geometryName, geometry, opt_srsName) { Spatial.call(this, 'Intersects', geometryName, geometry, opt_srsName); diff --git a/src/ol/format/filter/IsBetween.js b/src/ol/format/filter/IsBetween.js index fbea8fe79d..0c47a1ec33 100644 --- a/src/ol/format/filter/IsBetween.js +++ b/src/ol/format/filter/IsBetween.js @@ -15,7 +15,7 @@ import Comparison from '../filter/Comparison.js'; * @extends {ol.format.filter.Comparison} * @api */ -var IsBetween = function(propertyName, lowerBoundary, upperBoundary) { +const IsBetween = function(propertyName, lowerBoundary, upperBoundary) { Comparison.call(this, 'PropertyIsBetween', propertyName); /** diff --git a/src/ol/format/filter/IsLike.js b/src/ol/format/filter/IsLike.js index 60bb676ab0..e16f1f9b1f 100644 --- a/src/ol/format/filter/IsLike.js +++ b/src/ol/format/filter/IsLike.js @@ -21,7 +21,7 @@ import Comparison from '../filter/Comparison.js'; * @extends {ol.format.filter.Comparison} * @api */ -var IsLike = function(propertyName, pattern, opt_wildCard, opt_singleChar, opt_escapeChar, opt_matchCase) { +const IsLike = function(propertyName, pattern, opt_wildCard, opt_singleChar, opt_escapeChar, opt_matchCase) { Comparison.call(this, 'PropertyIsLike', propertyName); /** diff --git a/src/ol/format/filter/IsNull.js b/src/ol/format/filter/IsNull.js index 013d2c4ed2..05d141e302 100644 --- a/src/ol/format/filter/IsNull.js +++ b/src/ol/format/filter/IsNull.js @@ -13,7 +13,7 @@ import Comparison from '../filter/Comparison.js'; * @extends {ol.format.filter.Comparison} * @api */ -var IsNull = function(propertyName) { +const IsNull = function(propertyName) { Comparison.call(this, 'PropertyIsNull', propertyName); }; diff --git a/src/ol/format/filter/LessThan.js b/src/ol/format/filter/LessThan.js index 2f628dd656..89344e4a47 100644 --- a/src/ol/format/filter/LessThan.js +++ b/src/ol/format/filter/LessThan.js @@ -14,7 +14,7 @@ import ComparisonBinary from '../filter/ComparisonBinary.js'; * @extends {ol.format.filter.ComparisonBinary} * @api */ -var LessThan = function(propertyName, expression) { +const LessThan = function(propertyName, expression) { ComparisonBinary.call(this, 'PropertyIsLessThan', propertyName, expression); }; diff --git a/src/ol/format/filter/LessThanOrEqualTo.js b/src/ol/format/filter/LessThanOrEqualTo.js index 1c2e4d52c0..7a78d8874d 100644 --- a/src/ol/format/filter/LessThanOrEqualTo.js +++ b/src/ol/format/filter/LessThanOrEqualTo.js @@ -14,7 +14,7 @@ import ComparisonBinary from '../filter/ComparisonBinary.js'; * @extends {ol.format.filter.ComparisonBinary} * @api */ -var LessThanOrEqualTo = function(propertyName, expression) { +const LessThanOrEqualTo = function(propertyName, expression) { ComparisonBinary.call(this, 'PropertyIsLessThanOrEqualTo', propertyName, expression); }; diff --git a/src/ol/format/filter/LogicalNary.js b/src/ol/format/filter/LogicalNary.js index 054d540e74..51d40c2c4e 100644 --- a/src/ol/format/filter/LogicalNary.js +++ b/src/ol/format/filter/LogicalNary.js @@ -16,7 +16,7 @@ import Filter from '../filter/Filter.js'; * @param {...ol.format.filter.Filter} conditions Conditions. * @extends {ol.format.filter.Filter} */ -var LogicalNary = function(tagName, conditions) { +const LogicalNary = function(tagName, conditions) { Filter.call(this, tagName); diff --git a/src/ol/format/filter/Not.js b/src/ol/format/filter/Not.js index 22f30a9aaf..74f4c6f156 100644 --- a/src/ol/format/filter/Not.js +++ b/src/ol/format/filter/Not.js @@ -13,7 +13,7 @@ import Filter from '../filter/Filter.js'; * @extends {ol.format.filter.Filter} * @api */ -var Not = function(condition) { +const Not = function(condition) { Filter.call(this, 'Not'); diff --git a/src/ol/format/filter/NotEqualTo.js b/src/ol/format/filter/NotEqualTo.js index a670ce6216..5c651f5a3d 100644 --- a/src/ol/format/filter/NotEqualTo.js +++ b/src/ol/format/filter/NotEqualTo.js @@ -15,7 +15,7 @@ import ComparisonBinary from '../filter/ComparisonBinary.js'; * @extends {ol.format.filter.ComparisonBinary} * @api */ -var NotEqualTo = function(propertyName, expression, opt_matchCase) { +const NotEqualTo = function(propertyName, expression, opt_matchCase) { ComparisonBinary.call(this, 'PropertyIsNotEqualTo', propertyName, expression, opt_matchCase); }; diff --git a/src/ol/format/filter/Or.js b/src/ol/format/filter/Or.js index ab9657a6f7..da75224d48 100644 --- a/src/ol/format/filter/Or.js +++ b/src/ol/format/filter/Or.js @@ -13,8 +13,8 @@ import LogicalNary from '../filter/LogicalNary.js'; * @extends {ol.format.filter.LogicalNary} * @api */ -var Or = function(conditions) { - var params = ['Or'].concat(Array.prototype.slice.call(arguments)); +const Or = function(conditions) { + const params = ['Or'].concat(Array.prototype.slice.call(arguments)); LogicalNary.apply(this, params); }; diff --git a/src/ol/format/filter/Spatial.js b/src/ol/format/filter/Spatial.js index ac838f838c..da23fe297d 100644 --- a/src/ol/format/filter/Spatial.js +++ b/src/ol/format/filter/Spatial.js @@ -19,7 +19,7 @@ import Filter from '../filter/Filter.js'; * set on geometries when this is not provided. * @extends {ol.format.filter.Filter} */ -var Spatial = function(tagName, geometryName, geometry, opt_srsName) { +const Spatial = function(tagName, geometryName, geometry, opt_srsName) { Filter.call(this, tagName); diff --git a/src/ol/format/filter/Within.js b/src/ol/format/filter/Within.js index fc0eb65552..6f55512c33 100644 --- a/src/ol/format/filter/Within.js +++ b/src/ol/format/filter/Within.js @@ -17,7 +17,7 @@ import Spatial from '../filter/Spatial.js'; * @extends {ol.format.filter.Spatial} * @api */ -var Within = function(geometryName, geometry, opt_srsName) { +const Within = function(geometryName, geometry, opt_srsName) { Spatial.call(this, 'Within', geometryName, geometry, opt_srsName); diff --git a/src/ol/geom/Circle.js b/src/ol/geom/Circle.js index c50572fde4..d41591cdcd 100644 --- a/src/ol/geom/Circle.js +++ b/src/ol/geom/Circle.js @@ -19,9 +19,9 @@ import _ol_geom_flat_deflate_ from '../geom/flat/deflate.js'; * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api */ -var Circle = function(center, opt_radius, opt_layout) { +const Circle = function(center, opt_radius, opt_layout) { SimpleGeometry.call(this); - var radius = opt_radius ? opt_radius : 0; + const radius = opt_radius ? opt_radius : 0; this.setCenterAndRadius(center, radius, opt_layout); }; @@ -35,7 +35,7 @@ inherits(Circle, SimpleGeometry); * @api */ Circle.prototype.clone = function() { - var circle = new Circle(null); + const circle = new Circle(null); circle.setFlatCoordinates(this.layout, this.flatCoordinates.slice()); return circle; }; @@ -45,18 +45,18 @@ Circle.prototype.clone = function() { * @inheritDoc */ Circle.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDistance) { - var flatCoordinates = this.flatCoordinates; - var dx = x - flatCoordinates[0]; - var dy = y - flatCoordinates[1]; - var squaredDistance = dx * dx + dy * dy; + const flatCoordinates = this.flatCoordinates; + const dx = x - flatCoordinates[0]; + const dy = y - flatCoordinates[1]; + const squaredDistance = dx * dx + dy * dy; if (squaredDistance < minSquaredDistance) { - var i; + let i; if (squaredDistance === 0) { for (i = 0; i < this.stride; ++i) { closestPoint[i] = flatCoordinates[i]; } } else { - var delta = this.getRadius() / Math.sqrt(squaredDistance); + const delta = this.getRadius() / Math.sqrt(squaredDistance); closestPoint[0] = flatCoordinates[0] + delta * dx; closestPoint[1] = flatCoordinates[1] + delta * dy; for (i = 2; i < this.stride; ++i) { @@ -75,9 +75,9 @@ Circle.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDistanc * @inheritDoc */ Circle.prototype.containsXY = function(x, y) { - var flatCoordinates = this.flatCoordinates; - var dx = x - flatCoordinates[0]; - var dy = y - flatCoordinates[1]; + const flatCoordinates = this.flatCoordinates; + const dx = x - flatCoordinates[0]; + const dy = y - flatCoordinates[1]; return dx * dx + dy * dy <= this.getRadiusSquared_(); }; @@ -96,12 +96,12 @@ Circle.prototype.getCenter = function() { * @inheritDoc */ Circle.prototype.computeExtent = function(extent) { - var flatCoordinates = this.flatCoordinates; - var radius = flatCoordinates[this.stride] - flatCoordinates[0]; + const flatCoordinates = this.flatCoordinates; + const radius = flatCoordinates[this.stride] - flatCoordinates[0]; return createOrUpdate( - flatCoordinates[0] - radius, flatCoordinates[1] - radius, - flatCoordinates[0] + radius, flatCoordinates[1] + radius, - extent); + flatCoordinates[0] - radius, flatCoordinates[1] - radius, + flatCoordinates[0] + radius, flatCoordinates[1] + radius, + extent); }; @@ -120,8 +120,8 @@ Circle.prototype.getRadius = function() { * @return {number} Radius squared. */ Circle.prototype.getRadiusSquared_ = function() { - var dx = this.flatCoordinates[this.stride] - this.flatCoordinates[0]; - var dy = this.flatCoordinates[this.stride + 1] - this.flatCoordinates[1]; + const dx = this.flatCoordinates[this.stride] - this.flatCoordinates[0]; + const dy = this.flatCoordinates[this.stride + 1] - this.flatCoordinates[1]; return dx * dx + dy * dy; }; @@ -140,9 +140,9 @@ Circle.prototype.getType = function() { * @api */ Circle.prototype.intersectsExtent = function(extent) { - var circleExtent = this.getExtent(); + const circleExtent = this.getExtent(); if (intersects(extent, circleExtent)) { - var center = this.getCenter(); + const center = this.getCenter(); if (extent[0] <= center[0] && extent[2] >= center[0]) { return true; @@ -164,11 +164,11 @@ Circle.prototype.intersectsExtent = function(extent) { * @api */ Circle.prototype.setCenter = function(center) { - var stride = this.stride; - var radius = this.flatCoordinates[stride] - this.flatCoordinates[0]; - var flatCoordinates = center.slice(); + const stride = this.stride; + const radius = this.flatCoordinates[stride] - this.flatCoordinates[0]; + const flatCoordinates = center.slice(); flatCoordinates[stride] = flatCoordinates[0] + radius; - var i; + let i; for (i = 1; i < stride; ++i) { flatCoordinates[stride + i] = center[i]; } @@ -193,11 +193,11 @@ Circle.prototype.setCenterAndRadius = function(center, radius, opt_layout) { this.flatCoordinates = []; } /** @type {Array.} */ - var flatCoordinates = this.flatCoordinates; - var offset = _ol_geom_flat_deflate_.coordinate( - flatCoordinates, 0, center, this.stride); + const flatCoordinates = this.flatCoordinates; + let offset = _ol_geom_flat_deflate_.coordinate( + flatCoordinates, 0, center, this.stride); flatCoordinates[offset++] = flatCoordinates[0] + radius; - var i, ii; + let i, ii; for (i = 1, ii = this.stride; i < ii; ++i) { flatCoordinates[offset++] = flatCoordinates[i]; } diff --git a/src/ol/geom/Geometry.js b/src/ol/geom/Geometry.js index 00f6e1db12..52b092973a 100644 --- a/src/ol/geom/Geometry.js +++ b/src/ol/geom/Geometry.js @@ -24,7 +24,7 @@ import _ol_transform_ from '../transform.js'; * @extends {ol.Object} * @api */ -var Geometry = function() { +const Geometry = function() { BaseObject.call(this); @@ -97,7 +97,7 @@ Geometry.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDista * @api */ Geometry.prototype.getClosestPoint = function(point, opt_closestPoint) { - var closestPoint = opt_closestPoint ? opt_closestPoint : [NaN, NaN]; + const closestPoint = opt_closestPoint ? opt_closestPoint : [NaN, NaN]; this.closestPointXY(point[0], point[1], closestPoint, Infinity); return closestPoint; }; @@ -254,19 +254,19 @@ Geometry.prototype.translate = function(deltaX, deltaY) {}; * @api */ Geometry.prototype.transform = function(source, destination) { - var tmpTransform = this.tmpTransform_; + const tmpTransform = this.tmpTransform_; source = getProjection(source); - var transformFn = source.getUnits() == Units.TILE_PIXELS ? + const transformFn = source.getUnits() == Units.TILE_PIXELS ? function(inCoordinates, outCoordinates, stride) { - var pixelExtent = source.getExtent(); - var projectedExtent = source.getWorldExtent(); - var scale = getHeight(projectedExtent) / getHeight(pixelExtent); + const pixelExtent = source.getExtent(); + const projectedExtent = source.getWorldExtent(); + const scale = getHeight(projectedExtent) / getHeight(pixelExtent); _ol_transform_.compose(tmpTransform, - projectedExtent[0], projectedExtent[3], - scale, -scale, 0, - 0, 0); + projectedExtent[0], projectedExtent[3], + scale, -scale, 0, + 0, 0); _ol_geom_flat_transform_.transform2D(inCoordinates, 0, inCoordinates.length, stride, - tmpTransform, outCoordinates); + tmpTransform, outCoordinates); return getTransform(source, destination)(inCoordinates, outCoordinates, stride); } : getTransform(source, destination); diff --git a/src/ol/geom/GeometryCollection.js b/src/ol/geom/GeometryCollection.js index f03a7fb85d..664714cfb3 100644 --- a/src/ol/geom/GeometryCollection.js +++ b/src/ol/geom/GeometryCollection.js @@ -18,7 +18,7 @@ import _ol_obj_ from '../obj.js'; * @param {Array.=} opt_geometries Geometries. * @api */ -var GeometryCollection = function(opt_geometries) { +const GeometryCollection = function(opt_geometries) { Geometry.call(this); @@ -40,8 +40,8 @@ inherits(GeometryCollection, Geometry); * @return {Array.} Cloned geometries. */ GeometryCollection.cloneGeometries_ = function(geometries) { - var clonedGeometries = []; - var i, ii; + const clonedGeometries = []; + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { clonedGeometries.push(geometries[i].clone()); } @@ -53,14 +53,14 @@ GeometryCollection.cloneGeometries_ = function(geometries) { * @private */ GeometryCollection.prototype.unlistenGeometriesChange_ = function() { - var i, ii; + let i, ii; if (!this.geometries_) { return; } for (i = 0, ii = this.geometries_.length; i < ii; ++i) { _ol_events_.unlisten( - this.geometries_[i], EventType.CHANGE, - this.changed, this); + this.geometries_[i], EventType.CHANGE, + this.changed, this); } }; @@ -69,14 +69,14 @@ GeometryCollection.prototype.unlistenGeometriesChange_ = function() { * @private */ GeometryCollection.prototype.listenGeometriesChange_ = function() { - var i, ii; + let i, ii; if (!this.geometries_) { return; } for (i = 0, ii = this.geometries_.length; i < ii; ++i) { _ol_events_.listen( - this.geometries_[i], EventType.CHANGE, - this.changed, this); + this.geometries_[i], EventType.CHANGE, + this.changed, this); } }; @@ -88,7 +88,7 @@ GeometryCollection.prototype.listenGeometriesChange_ = function() { * @api */ GeometryCollection.prototype.clone = function() { - var geometryCollection = new GeometryCollection(null); + const geometryCollection = new GeometryCollection(null); geometryCollection.setGeometries(this.geometries_); return geometryCollection; }; @@ -101,11 +101,11 @@ GeometryCollection.prototype.closestPointXY = function(x, y, closestPoint, minSq if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) { return minSquaredDistance; } - var geometries = this.geometries_; - var i, ii; + const geometries = this.geometries_; + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { minSquaredDistance = geometries[i].closestPointXY( - x, y, closestPoint, minSquaredDistance); + x, y, closestPoint, minSquaredDistance); } return minSquaredDistance; }; @@ -115,8 +115,8 @@ GeometryCollection.prototype.closestPointXY = function(x, y, closestPoint, minSq * @inheritDoc */ GeometryCollection.prototype.containsXY = function(x, y) { - var geometries = this.geometries_; - var i, ii; + const geometries = this.geometries_; + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { if (geometries[i].containsXY(x, y)) { return true; @@ -131,8 +131,8 @@ GeometryCollection.prototype.containsXY = function(x, y) { */ GeometryCollection.prototype.computeExtent = function(extent) { createOrUpdateEmpty(extent); - var geometries = this.geometries_; - for (var i = 0, ii = geometries.length; i < ii; ++i) { + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { extend(extent, geometries[i].getExtent()); } return extent; @@ -171,24 +171,24 @@ GeometryCollection.prototype.getSimplifiedGeometry = function(squaredTolerance) squaredTolerance < this.simplifiedGeometryMaxMinSquaredTolerance)) { return this; } - var key = squaredTolerance.toString(); + const key = squaredTolerance.toString(); if (this.simplifiedGeometryCache.hasOwnProperty(key)) { return this.simplifiedGeometryCache[key]; } else { - var simplifiedGeometries = []; - var geometries = this.geometries_; - var simplified = false; - var i, ii; + const simplifiedGeometries = []; + const geometries = this.geometries_; + let simplified = false; + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { - var geometry = geometries[i]; - var simplifiedGeometry = geometry.getSimplifiedGeometry(squaredTolerance); + const geometry = geometries[i]; + const simplifiedGeometry = geometry.getSimplifiedGeometry(squaredTolerance); simplifiedGeometries.push(simplifiedGeometry); if (simplifiedGeometry !== geometry) { simplified = true; } } if (simplified) { - var simplifiedGeometryCollection = new GeometryCollection(null); + const simplifiedGeometryCollection = new GeometryCollection(null); simplifiedGeometryCollection.setGeometriesArray(simplifiedGeometries); this.simplifiedGeometryCache[key] = simplifiedGeometryCollection; return simplifiedGeometryCollection; @@ -214,8 +214,8 @@ GeometryCollection.prototype.getType = function() { * @api */ GeometryCollection.prototype.intersectsExtent = function(extent) { - var geometries = this.geometries_; - var i, ii; + const geometries = this.geometries_; + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { if (geometries[i].intersectsExtent(extent)) { return true; @@ -238,8 +238,8 @@ GeometryCollection.prototype.isEmpty = function() { * @api */ GeometryCollection.prototype.rotate = function(angle, anchor) { - var geometries = this.geometries_; - for (var i = 0, ii = geometries.length; i < ii; ++i) { + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { geometries[i].rotate(angle, anchor); } this.changed(); @@ -251,12 +251,12 @@ GeometryCollection.prototype.rotate = function(angle, anchor) { * @api */ GeometryCollection.prototype.scale = function(sx, opt_sy, opt_anchor) { - var anchor = opt_anchor; + let anchor = opt_anchor; if (!anchor) { anchor = getCenter(this.getExtent()); } - var geometries = this.geometries_; - for (var i = 0, ii = geometries.length; i < ii; ++i) { + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { geometries[i].scale(sx, opt_sy, anchor); } this.changed(); @@ -270,7 +270,7 @@ GeometryCollection.prototype.scale = function(sx, opt_sy, opt_anchor) { */ GeometryCollection.prototype.setGeometries = function(geometries) { this.setGeometriesArray( - GeometryCollection.cloneGeometries_(geometries)); + GeometryCollection.cloneGeometries_(geometries)); }; @@ -290,8 +290,8 @@ GeometryCollection.prototype.setGeometriesArray = function(geometries) { * @api */ GeometryCollection.prototype.applyTransform = function(transformFn) { - var geometries = this.geometries_; - var i, ii; + const geometries = this.geometries_; + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { geometries[i].applyTransform(transformFn); } @@ -307,8 +307,8 @@ GeometryCollection.prototype.applyTransform = function(transformFn) { * @api */ GeometryCollection.prototype.translate = function(deltaX, deltaY) { - var geometries = this.geometries_; - var i, ii; + const geometries = this.geometries_; + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { geometries[i].translate(deltaX, deltaY); } diff --git a/src/ol/geom/LineString.js b/src/ol/geom/LineString.js index 1a6fb30f89..ba1fe244ef 100644 --- a/src/ol/geom/LineString.js +++ b/src/ol/geom/LineString.js @@ -26,7 +26,7 @@ import _ol_geom_flat_simplify_ from '../geom/flat/simplify.js'; * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api */ -var LineString = function(coordinates, opt_layout) { +const LineString = function(coordinates, opt_layout) { SimpleGeometry.call(this); @@ -83,7 +83,7 @@ LineString.prototype.appendCoordinate = function(coordinate) { * @api */ LineString.prototype.clone = function() { - var lineString = new LineString(null); + const lineString = new LineString(null); lineString.setFlatCoordinates(this.layout, this.flatCoordinates.slice()); return lineString; }; @@ -98,12 +98,12 @@ LineString.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDis } if (this.maxDeltaRevision_ != this.getRevision()) { this.maxDelta_ = Math.sqrt(_ol_geom_flat_closest_.getMaxSquaredDelta( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, 0)); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, 0)); this.maxDeltaRevision_ = this.getRevision(); } return _ol_geom_flat_closest_.getClosestPoint( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, - this.maxDelta_, false, x, y, closestPoint, minSquaredDistance); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, + this.maxDelta_, false, x, y, closestPoint, minSquaredDistance); }; @@ -120,7 +120,7 @@ LineString.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDis */ LineString.prototype.forEachSegment = function(callback) { return _ol_geom_flat_segments_.forEach(this.flatCoordinates, 0, - this.flatCoordinates.length, this.stride, callback); + this.flatCoordinates.length, this.stride, callback); }; @@ -143,9 +143,9 @@ LineString.prototype.getCoordinateAtM = function(m, opt_extrapolate) { this.layout != GeometryLayout.XYZM) { return null; } - var extrapolate = opt_extrapolate !== undefined ? opt_extrapolate : false; + const extrapolate = opt_extrapolate !== undefined ? opt_extrapolate : false; return _ol_geom_flat_interpolate_.lineStringCoordinateAtM(this.flatCoordinates, 0, - this.flatCoordinates.length, this.stride, m, extrapolate); + this.flatCoordinates.length, this.stride, m, extrapolate); }; @@ -157,7 +157,7 @@ LineString.prototype.getCoordinateAtM = function(m, opt_extrapolate) { */ LineString.prototype.getCoordinates = function() { return _ol_geom_flat_inflate_.coordinates( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride); }; @@ -173,8 +173,8 @@ LineString.prototype.getCoordinates = function() { */ LineString.prototype.getCoordinateAt = function(fraction, opt_dest) { return _ol_geom_flat_interpolate_.lineString( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, - fraction, opt_dest); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, + fraction, opt_dest); }; @@ -185,7 +185,7 @@ LineString.prototype.getCoordinateAt = function(fraction, opt_dest) { */ LineString.prototype.getLength = function() { return _ol_geom_flat_length_.lineString( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride); }; @@ -205,13 +205,13 @@ LineString.prototype.getFlatMidpoint = function() { * @inheritDoc */ LineString.prototype.getSimplifiedGeometryInternal = function(squaredTolerance) { - var simplifiedFlatCoordinates = []; + const simplifiedFlatCoordinates = []; simplifiedFlatCoordinates.length = _ol_geom_flat_simplify_.douglasPeucker( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, - squaredTolerance, simplifiedFlatCoordinates, 0); - var simplifiedLineString = new LineString(null); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, + squaredTolerance, simplifiedFlatCoordinates, 0); + const simplifiedLineString = new LineString(null); simplifiedLineString.setFlatCoordinates( - GeometryLayout.XY, simplifiedFlatCoordinates); + GeometryLayout.XY, simplifiedFlatCoordinates); return simplifiedLineString; }; @@ -231,8 +231,8 @@ LineString.prototype.getType = function() { */ LineString.prototype.intersectsExtent = function(extent) { return _ol_geom_flat_intersectsextent_.lineString( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, - extent); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, + extent); }; @@ -252,7 +252,7 @@ LineString.prototype.setCoordinates = function(coordinates, opt_layout) { this.flatCoordinates = []; } this.flatCoordinates.length = _ol_geom_flat_deflate_.coordinates( - this.flatCoordinates, 0, coordinates, this.stride); + this.flatCoordinates, 0, coordinates, this.stride); this.changed(); } }; diff --git a/src/ol/geom/LinearRing.js b/src/ol/geom/LinearRing.js index b382cd36ea..ac3b354449 100644 --- a/src/ol/geom/LinearRing.js +++ b/src/ol/geom/LinearRing.js @@ -23,7 +23,7 @@ import _ol_geom_flat_simplify_ from '../geom/flat/simplify.js'; * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api */ -var LinearRing = function(coordinates, opt_layout) { +const LinearRing = function(coordinates, opt_layout) { SimpleGeometry.call(this); @@ -53,7 +53,7 @@ inherits(LinearRing, SimpleGeometry); * @api */ LinearRing.prototype.clone = function() { - var linearRing = new LinearRing(null); + const linearRing = new LinearRing(null); linearRing.setFlatCoordinates(this.layout, this.flatCoordinates.slice()); return linearRing; }; @@ -68,12 +68,12 @@ LinearRing.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDis } if (this.maxDeltaRevision_ != this.getRevision()) { this.maxDelta_ = Math.sqrt(_ol_geom_flat_closest_.getMaxSquaredDelta( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, 0)); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, 0)); this.maxDeltaRevision_ = this.getRevision(); } return _ol_geom_flat_closest_.getClosestPoint( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, - this.maxDelta_, true, x, y, closestPoint, minSquaredDistance); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, + this.maxDelta_, true, x, y, closestPoint, minSquaredDistance); }; @@ -84,7 +84,7 @@ LinearRing.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDis */ LinearRing.prototype.getArea = function() { return _ol_geom_flat_area_.linearRing( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride); }; @@ -96,7 +96,7 @@ LinearRing.prototype.getArea = function() { */ LinearRing.prototype.getCoordinates = function() { return _ol_geom_flat_inflate_.coordinates( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride); }; @@ -104,13 +104,13 @@ LinearRing.prototype.getCoordinates = function() { * @inheritDoc */ LinearRing.prototype.getSimplifiedGeometryInternal = function(squaredTolerance) { - var simplifiedFlatCoordinates = []; + const simplifiedFlatCoordinates = []; simplifiedFlatCoordinates.length = _ol_geom_flat_simplify_.douglasPeucker( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, - squaredTolerance, simplifiedFlatCoordinates, 0); - var simplifiedLinearRing = new LinearRing(null); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, + squaredTolerance, simplifiedFlatCoordinates, 0); + const simplifiedLinearRing = new LinearRing(null); simplifiedLinearRing.setFlatCoordinates( - GeometryLayout.XY, simplifiedFlatCoordinates); + GeometryLayout.XY, simplifiedFlatCoordinates); return simplifiedLinearRing; }; @@ -146,7 +146,7 @@ LinearRing.prototype.setCoordinates = function(coordinates, opt_layout) { this.flatCoordinates = []; } this.flatCoordinates.length = _ol_geom_flat_deflate_.coordinates( - this.flatCoordinates, 0, coordinates, this.stride); + this.flatCoordinates, 0, coordinates, this.stride); this.changed(); } }; diff --git a/src/ol/geom/MultiLineString.js b/src/ol/geom/MultiLineString.js index 23f70b1fbc..283aac83df 100644 --- a/src/ol/geom/MultiLineString.js +++ b/src/ol/geom/MultiLineString.js @@ -25,7 +25,7 @@ import _ol_geom_flat_simplify_ from '../geom/flat/simplify.js'; * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api */ -var MultiLineString = function(coordinates, opt_layout) { +const MultiLineString = function(coordinates, opt_layout) { SimpleGeometry.call(this); @@ -77,9 +77,9 @@ MultiLineString.prototype.appendLineString = function(lineString) { * @api */ MultiLineString.prototype.clone = function() { - var multiLineString = new MultiLineString(null); + const multiLineString = new MultiLineString(null); multiLineString.setFlatCoordinates( - this.layout, this.flatCoordinates.slice(), this.ends_.slice()); + this.layout, this.flatCoordinates.slice(), this.ends_.slice()); return multiLineString; }; @@ -93,12 +93,12 @@ MultiLineString.prototype.closestPointXY = function(x, y, closestPoint, minSquar } if (this.maxDeltaRevision_ != this.getRevision()) { this.maxDelta_ = Math.sqrt(_ol_geom_flat_closest_.getsMaxSquaredDelta( - this.flatCoordinates, 0, this.ends_, this.stride, 0)); + this.flatCoordinates, 0, this.ends_, this.stride, 0)); this.maxDeltaRevision_ = this.getRevision(); } return _ol_geom_flat_closest_.getsClosestPoint( - this.flatCoordinates, 0, this.ends_, this.stride, - this.maxDelta_, false, x, y, closestPoint, minSquaredDistance); + this.flatCoordinates, 0, this.ends_, this.stride, + this.maxDelta_, false, x, y, closestPoint, minSquaredDistance); }; @@ -130,10 +130,10 @@ MultiLineString.prototype.getCoordinateAtM = function(m, opt_extrapolate, opt_in this.flatCoordinates.length === 0) { return null; } - var extrapolate = opt_extrapolate !== undefined ? opt_extrapolate : false; - var interpolate = opt_interpolate !== undefined ? opt_interpolate : false; + const extrapolate = opt_extrapolate !== undefined ? opt_extrapolate : false; + const interpolate = opt_interpolate !== undefined ? opt_interpolate : false; return _ol_geom_flat_interpolate_.lineStringsCoordinateAtM(this.flatCoordinates, 0, - this.ends_, this.stride, m, extrapolate, interpolate); + this.ends_, this.stride, m, extrapolate, interpolate); }; @@ -145,7 +145,7 @@ MultiLineString.prototype.getCoordinateAtM = function(m, opt_extrapolate, opt_in */ MultiLineString.prototype.getCoordinates = function() { return _ol_geom_flat_inflate_.coordinatess( - this.flatCoordinates, 0, this.ends_, this.stride); + this.flatCoordinates, 0, this.ends_, this.stride); }; @@ -167,9 +167,9 @@ MultiLineString.prototype.getLineString = function(index) { if (index < 0 || this.ends_.length <= index) { return null; } - var lineString = new LineString(null); + const lineString = new LineString(null); lineString.setFlatCoordinates(this.layout, this.flatCoordinates.slice( - index === 0 ? 0 : this.ends_[index - 1], this.ends_[index])); + index === 0 ? 0 : this.ends_[index - 1], this.ends_[index])); return lineString; }; @@ -180,16 +180,16 @@ MultiLineString.prototype.getLineString = function(index) { * @api */ MultiLineString.prototype.getLineStrings = function() { - var flatCoordinates = this.flatCoordinates; - var ends = this.ends_; - var layout = this.layout; + const flatCoordinates = this.flatCoordinates; + const ends = this.ends_; + const layout = this.layout; /** @type {Array.} */ - var lineStrings = []; - var offset = 0; - var i, ii; + const lineStrings = []; + let offset = 0; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; - var lineString = new LineString(null); + const end = ends[i]; + const lineString = new LineString(null); lineString.setFlatCoordinates(layout, flatCoordinates.slice(offset, end)); lineStrings.push(lineString); offset = end; @@ -202,16 +202,16 @@ MultiLineString.prototype.getLineStrings = function() { * @return {Array.} Flat midpoints. */ MultiLineString.prototype.getFlatMidpoints = function() { - var midpoints = []; - var flatCoordinates = this.flatCoordinates; - var offset = 0; - var ends = this.ends_; - var stride = this.stride; - var i, ii; + const midpoints = []; + const flatCoordinates = this.flatCoordinates; + let offset = 0; + const ends = this.ends_; + const stride = this.stride; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; - var midpoint = _ol_geom_flat_interpolate_.lineString( - flatCoordinates, offset, end, stride, 0.5); + const end = ends[i]; + const midpoint = _ol_geom_flat_interpolate_.lineString( + flatCoordinates, offset, end, stride, 0.5); extend(midpoints, midpoint); offset = end; } @@ -223,14 +223,14 @@ MultiLineString.prototype.getFlatMidpoints = function() { * @inheritDoc */ MultiLineString.prototype.getSimplifiedGeometryInternal = function(squaredTolerance) { - var simplifiedFlatCoordinates = []; - var simplifiedEnds = []; + const simplifiedFlatCoordinates = []; + const simplifiedEnds = []; simplifiedFlatCoordinates.length = _ol_geom_flat_simplify_.douglasPeuckers( - this.flatCoordinates, 0, this.ends_, this.stride, squaredTolerance, - simplifiedFlatCoordinates, 0, simplifiedEnds); - var simplifiedMultiLineString = new MultiLineString(null); + this.flatCoordinates, 0, this.ends_, this.stride, squaredTolerance, + simplifiedFlatCoordinates, 0, simplifiedEnds); + const simplifiedMultiLineString = new MultiLineString(null); simplifiedMultiLineString.setFlatCoordinates( - GeometryLayout.XY, simplifiedFlatCoordinates, simplifiedEnds); + GeometryLayout.XY, simplifiedFlatCoordinates, simplifiedEnds); return simplifiedMultiLineString; }; @@ -250,7 +250,7 @@ MultiLineString.prototype.getType = function() { */ MultiLineString.prototype.intersectsExtent = function(extent) { return _ol_geom_flat_intersectsextent_.lineStrings( - this.flatCoordinates, 0, this.ends_, this.stride, extent); + this.flatCoordinates, 0, this.ends_, this.stride, extent); }; @@ -269,8 +269,8 @@ MultiLineString.prototype.setCoordinates = function(coordinates, opt_layout) { if (!this.flatCoordinates) { this.flatCoordinates = []; } - var ends = _ol_geom_flat_deflate_.coordinatess( - this.flatCoordinates, 0, coordinates, this.stride, this.ends_); + const ends = _ol_geom_flat_deflate_.coordinatess( + this.flatCoordinates, 0, coordinates, this.stride, this.ends_); this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1]; this.changed(); } @@ -293,12 +293,12 @@ MultiLineString.prototype.setFlatCoordinates = function(layout, flatCoordinates, * @param {Array.} lineStrings LineStrings. */ MultiLineString.prototype.setLineStrings = function(lineStrings) { - var layout = this.getLayout(); - var flatCoordinates = []; - var ends = []; - var i, ii; + let layout = this.getLayout(); + const flatCoordinates = []; + const ends = []; + let i, ii; for (i = 0, ii = lineStrings.length; i < ii; ++i) { - var lineString = lineStrings[i]; + const lineString = lineStrings[i]; if (i === 0) { layout = lineString.getLayout(); } diff --git a/src/ol/geom/MultiPoint.js b/src/ol/geom/MultiPoint.js index 859117a9eb..29b3e13987 100644 --- a/src/ol/geom/MultiPoint.js +++ b/src/ol/geom/MultiPoint.js @@ -22,7 +22,7 @@ import {squaredDistance as squaredDx} from '../math.js'; * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api */ -var MultiPoint = function(coordinates, opt_layout) { +const MultiPoint = function(coordinates, opt_layout) { SimpleGeometry.call(this); this.setCoordinates(coordinates, opt_layout); }; @@ -52,7 +52,7 @@ MultiPoint.prototype.appendPoint = function(point) { * @api */ MultiPoint.prototype.clone = function() { - var multiPoint = new MultiPoint(null); + const multiPoint = new MultiPoint(null); multiPoint.setFlatCoordinates(this.layout, this.flatCoordinates.slice()); return multiPoint; }; @@ -65,12 +65,12 @@ MultiPoint.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDis if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) { return minSquaredDistance; } - var flatCoordinates = this.flatCoordinates; - var stride = this.stride; - var i, ii, j; + const flatCoordinates = this.flatCoordinates; + const stride = this.stride; + let i, ii, j; for (i = 0, ii = flatCoordinates.length; i < ii; i += stride) { - var squaredDistance = squaredDx( - x, y, flatCoordinates[i], flatCoordinates[i + 1]); + const squaredDistance = squaredDx( + x, y, flatCoordinates[i], flatCoordinates[i + 1]); if (squaredDistance < minSquaredDistance) { minSquaredDistance = squaredDistance; for (j = 0; j < stride; ++j) { @@ -91,7 +91,7 @@ MultiPoint.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDis */ MultiPoint.prototype.getCoordinates = function() { return _ol_geom_flat_inflate_.coordinates( - this.flatCoordinates, 0, this.flatCoordinates.length, this.stride); + this.flatCoordinates, 0, this.flatCoordinates.length, this.stride); }; @@ -102,14 +102,14 @@ MultiPoint.prototype.getCoordinates = function() { * @api */ MultiPoint.prototype.getPoint = function(index) { - var n = !this.flatCoordinates ? + const n = !this.flatCoordinates ? 0 : this.flatCoordinates.length / this.stride; if (index < 0 || n <= index) { return null; } - var point = new Point(null); + const point = new Point(null); point.setFlatCoordinates(this.layout, this.flatCoordinates.slice( - index * this.stride, (index + 1) * this.stride)); + index * this.stride, (index + 1) * this.stride)); return point; }; @@ -120,14 +120,14 @@ MultiPoint.prototype.getPoint = function(index) { * @api */ MultiPoint.prototype.getPoints = function() { - var flatCoordinates = this.flatCoordinates; - var layout = this.layout; - var stride = this.stride; + const flatCoordinates = this.flatCoordinates; + const layout = this.layout; + const stride = this.stride; /** @type {Array.} */ - var points = []; - var i, ii; + const points = []; + let i, ii; for (i = 0, ii = flatCoordinates.length; i < ii; i += stride) { - var point = new Point(null); + const point = new Point(null); point.setFlatCoordinates(layout, flatCoordinates.slice(i, i + stride)); points.push(point); } @@ -149,9 +149,9 @@ MultiPoint.prototype.getType = function() { * @api */ MultiPoint.prototype.intersectsExtent = function(extent) { - var flatCoordinates = this.flatCoordinates; - var stride = this.stride; - var i, ii, x, y; + const flatCoordinates = this.flatCoordinates; + const stride = this.stride; + let i, ii, x, y; for (i = 0, ii = flatCoordinates.length; i < ii; i += stride) { x = flatCoordinates[i]; y = flatCoordinates[i + 1]; @@ -179,7 +179,7 @@ MultiPoint.prototype.setCoordinates = function(coordinates, opt_layout) { this.flatCoordinates = []; } this.flatCoordinates.length = _ol_geom_flat_deflate_.coordinates( - this.flatCoordinates, 0, coordinates, this.stride); + this.flatCoordinates, 0, coordinates, this.stride); this.changed(); } }; diff --git a/src/ol/geom/MultiPolygon.js b/src/ol/geom/MultiPolygon.js index 997ddc5ad2..c2f7bab8cd 100644 --- a/src/ol/geom/MultiPolygon.js +++ b/src/ol/geom/MultiPolygon.js @@ -30,7 +30,7 @@ import _ol_geom_flat_simplify_ from '../geom/flat/simplify.js'; * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api */ -var MultiPolygon = function(coordinates, opt_layout) { +const MultiPolygon = function(coordinates, opt_layout) { SimpleGeometry.call(this); @@ -90,16 +90,16 @@ inherits(MultiPolygon, SimpleGeometry); */ MultiPolygon.prototype.appendPolygon = function(polygon) { /** @type {Array.} */ - var ends; + let ends; if (!this.flatCoordinates) { this.flatCoordinates = polygon.getFlatCoordinates().slice(); ends = polygon.getEnds().slice(); this.endss_.push(); } else { - var offset = this.flatCoordinates.length; + const offset = this.flatCoordinates.length; extend(this.flatCoordinates, polygon.getFlatCoordinates()); ends = polygon.getEnds().slice(); - var i, ii; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { ends[i] += offset; } @@ -116,16 +116,16 @@ MultiPolygon.prototype.appendPolygon = function(polygon) { * @api */ MultiPolygon.prototype.clone = function() { - var multiPolygon = new MultiPolygon(null); + const multiPolygon = new MultiPolygon(null); - var len = this.endss_.length; - var newEndss = new Array(len); - for (var i = 0; i < len; ++i) { + const len = this.endss_.length; + const newEndss = new Array(len); + for (let i = 0; i < len; ++i) { newEndss[i] = this.endss_[i].slice(); } multiPolygon.setFlatCoordinates( - this.layout, this.flatCoordinates.slice(), newEndss); + this.layout, this.flatCoordinates.slice(), newEndss); return multiPolygon; }; @@ -139,12 +139,12 @@ MultiPolygon.prototype.closestPointXY = function(x, y, closestPoint, minSquaredD } if (this.maxDeltaRevision_ != this.getRevision()) { this.maxDelta_ = Math.sqrt(_ol_geom_flat_closest_.getssMaxSquaredDelta( - this.flatCoordinates, 0, this.endss_, this.stride, 0)); + this.flatCoordinates, 0, this.endss_, this.stride, 0)); this.maxDeltaRevision_ = this.getRevision(); } return _ol_geom_flat_closest_.getssClosestPoint( - this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride, - this.maxDelta_, true, x, y, closestPoint, minSquaredDistance); + this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride, + this.maxDelta_, true, x, y, closestPoint, minSquaredDistance); }; @@ -153,7 +153,7 @@ MultiPolygon.prototype.closestPointXY = function(x, y, closestPoint, minSquaredD */ MultiPolygon.prototype.containsXY = function(x, y) { return _ol_geom_flat_contains_.linearRingssContainsXY( - this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride, x, y); + this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride, x, y); }; @@ -164,7 +164,7 @@ MultiPolygon.prototype.containsXY = function(x, y) { */ MultiPolygon.prototype.getArea = function() { return _ol_geom_flat_area_.linearRingss( - this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride); + this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride); }; @@ -183,17 +183,17 @@ MultiPolygon.prototype.getArea = function() { * @api */ MultiPolygon.prototype.getCoordinates = function(opt_right) { - var flatCoordinates; + let flatCoordinates; if (opt_right !== undefined) { flatCoordinates = this.getOrientedFlatCoordinates().slice(); _ol_geom_flat_orient_.orientLinearRingss( - flatCoordinates, 0, this.endss_, this.stride, opt_right); + flatCoordinates, 0, this.endss_, this.stride, opt_right); } else { flatCoordinates = this.flatCoordinates; } return _ol_geom_flat_inflate_.coordinatesss( - flatCoordinates, 0, this.endss_, this.stride); + flatCoordinates, 0, this.endss_, this.stride); }; @@ -210,11 +210,11 @@ MultiPolygon.prototype.getEndss = function() { */ MultiPolygon.prototype.getFlatInteriorPoints = function() { if (this.flatInteriorPointsRevision_ != this.getRevision()) { - var flatCenters = _ol_geom_flat_center_.linearRingss( - this.flatCoordinates, 0, this.endss_, this.stride); + const flatCenters = _ol_geom_flat_center_.linearRingss( + this.flatCoordinates, 0, this.endss_, this.stride); this.flatInteriorPoints_ = _ol_geom_flat_interiorpoint_.linearRingss( - this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride, - flatCenters); + this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride, + flatCenters); this.flatInteriorPointsRevision_ = this.getRevision(); } return this.flatInteriorPoints_; @@ -228,9 +228,9 @@ MultiPolygon.prototype.getFlatInteriorPoints = function() { * @api */ MultiPolygon.prototype.getInteriorPoints = function() { - var interiorPoints = new MultiPoint(null); + const interiorPoints = new MultiPoint(null); interiorPoints.setFlatCoordinates(GeometryLayout.XYM, - this.getFlatInteriorPoints().slice()); + this.getFlatInteriorPoints().slice()); return interiorPoints; }; @@ -240,15 +240,15 @@ MultiPolygon.prototype.getInteriorPoints = function() { */ MultiPolygon.prototype.getOrientedFlatCoordinates = function() { if (this.orientedRevision_ != this.getRevision()) { - var flatCoordinates = this.flatCoordinates; + const flatCoordinates = this.flatCoordinates; if (_ol_geom_flat_orient_.linearRingssAreOriented( - flatCoordinates, 0, this.endss_, this.stride)) { + flatCoordinates, 0, this.endss_, this.stride)) { this.orientedFlatCoordinates_ = flatCoordinates; } else { this.orientedFlatCoordinates_ = flatCoordinates.slice(); this.orientedFlatCoordinates_.length = _ol_geom_flat_orient_.orientLinearRingss( - this.orientedFlatCoordinates_, 0, this.endss_, this.stride); + this.orientedFlatCoordinates_, 0, this.endss_, this.stride); } this.orientedRevision_ = this.getRevision(); } @@ -260,15 +260,15 @@ MultiPolygon.prototype.getOrientedFlatCoordinates = function() { * @inheritDoc */ MultiPolygon.prototype.getSimplifiedGeometryInternal = function(squaredTolerance) { - var simplifiedFlatCoordinates = []; - var simplifiedEndss = []; + const simplifiedFlatCoordinates = []; + const simplifiedEndss = []; simplifiedFlatCoordinates.length = _ol_geom_flat_simplify_.quantizess( - this.flatCoordinates, 0, this.endss_, this.stride, - Math.sqrt(squaredTolerance), - simplifiedFlatCoordinates, 0, simplifiedEndss); - var simplifiedMultiPolygon = new MultiPolygon(null); + this.flatCoordinates, 0, this.endss_, this.stride, + Math.sqrt(squaredTolerance), + simplifiedFlatCoordinates, 0, simplifiedEndss); + const simplifiedMultiPolygon = new MultiPolygon(null); simplifiedMultiPolygon.setFlatCoordinates( - GeometryLayout.XY, simplifiedFlatCoordinates, simplifiedEndss); + GeometryLayout.XY, simplifiedFlatCoordinates, simplifiedEndss); return simplifiedMultiPolygon; }; @@ -283,24 +283,24 @@ MultiPolygon.prototype.getPolygon = function(index) { if (index < 0 || this.endss_.length <= index) { return null; } - var offset; + let offset; if (index === 0) { offset = 0; } else { - var prevEnds = this.endss_[index - 1]; + const prevEnds = this.endss_[index - 1]; offset = prevEnds[prevEnds.length - 1]; } - var ends = this.endss_[index].slice(); - var end = ends[ends.length - 1]; + const ends = this.endss_[index].slice(); + const end = ends[ends.length - 1]; if (offset !== 0) { - var i, ii; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { ends[i] -= offset; } } - var polygon = new Polygon(null); + const polygon = new Polygon(null); polygon.setFlatCoordinates( - this.layout, this.flatCoordinates.slice(offset, end), ends); + this.layout, this.flatCoordinates.slice(offset, end), ends); return polygon; }; @@ -311,23 +311,23 @@ MultiPolygon.prototype.getPolygon = function(index) { * @api */ MultiPolygon.prototype.getPolygons = function() { - var layout = this.layout; - var flatCoordinates = this.flatCoordinates; - var endss = this.endss_; - var polygons = []; - var offset = 0; - var i, ii, j, jj; + const layout = this.layout; + const flatCoordinates = this.flatCoordinates; + const endss = this.endss_; + const polygons = []; + let offset = 0; + let i, ii, j, jj; for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i].slice(); - var end = ends[ends.length - 1]; + const ends = endss[i].slice(); + const end = ends[ends.length - 1]; if (offset !== 0) { for (j = 0, jj = ends.length; j < jj; ++j) { ends[j] -= offset; } } - var polygon = new Polygon(null); + const polygon = new Polygon(null); polygon.setFlatCoordinates( - layout, flatCoordinates.slice(offset, end), ends); + layout, flatCoordinates.slice(offset, end), ends); polygons.push(polygon); offset = end; } @@ -350,7 +350,7 @@ MultiPolygon.prototype.getType = function() { */ MultiPolygon.prototype.intersectsExtent = function(extent) { return _ol_geom_flat_intersectsextent_.linearRingss( - this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride, extent); + this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride, extent); }; @@ -369,12 +369,12 @@ MultiPolygon.prototype.setCoordinates = function(coordinates, opt_layout) { if (!this.flatCoordinates) { this.flatCoordinates = []; } - var endss = _ol_geom_flat_deflate_.coordinatesss( - this.flatCoordinates, 0, coordinates, this.stride, this.endss_); + const endss = _ol_geom_flat_deflate_.coordinatesss( + this.flatCoordinates, 0, coordinates, this.stride, this.endss_); if (endss.length === 0) { this.flatCoordinates.length = 0; } else { - var lastEnds = endss[endss.length - 1]; + const lastEnds = endss[endss.length - 1]; this.flatCoordinates.length = lastEnds.length === 0 ? 0 : lastEnds[lastEnds.length - 1]; } @@ -399,19 +399,17 @@ MultiPolygon.prototype.setFlatCoordinates = function(layout, flatCoordinates, en * @param {Array.} polygons Polygons. */ MultiPolygon.prototype.setPolygons = function(polygons) { - var layout = this.getLayout(); - var flatCoordinates = []; - var endss = []; - var i, ii, ends; - for (i = 0, ii = polygons.length; i < ii; ++i) { - var polygon = polygons[i]; + let layout = this.getLayout(); + const flatCoordinates = []; + const endss = []; + for (let i = 0, ii = polygons.length; i < ii; ++i) { + const polygon = polygons[i]; if (i === 0) { layout = polygon.getLayout(); } - var offset = flatCoordinates.length; - ends = polygon.getEnds(); - var j, jj; - for (j = 0, jj = ends.length; j < jj; ++j) { + const offset = flatCoordinates.length; + const ends = polygon.getEnds(); + for (let j = 0, jj = ends.length; j < jj; ++j) { ends[j] += offset; } extend(flatCoordinates, polygon.getFlatCoordinates()); @@ -419,4 +417,5 @@ MultiPolygon.prototype.setPolygons = function(polygons) { } this.setFlatCoordinates(layout, flatCoordinates, endss); }; + export default MultiPolygon; diff --git a/src/ol/geom/Point.js b/src/ol/geom/Point.js index 4e566b42eb..82bf02a4df 100644 --- a/src/ol/geom/Point.js +++ b/src/ol/geom/Point.js @@ -19,7 +19,7 @@ import {squaredDistance as squaredDx} from '../math.js'; * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api */ -var Point = function(coordinates, opt_layout) { +const Point = function(coordinates, opt_layout) { SimpleGeometry.call(this); this.setCoordinates(coordinates, opt_layout); }; @@ -34,7 +34,7 @@ inherits(Point, SimpleGeometry); * @api */ Point.prototype.clone = function() { - var point = new Point(null); + const point = new Point(null); point.setFlatCoordinates(this.layout, this.flatCoordinates.slice()); return point; }; @@ -44,12 +44,12 @@ Point.prototype.clone = function() { * @inheritDoc */ Point.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDistance) { - var flatCoordinates = this.flatCoordinates; - var squaredDistance = squaredDx( - x, y, flatCoordinates[0], flatCoordinates[1]); + const flatCoordinates = this.flatCoordinates; + const squaredDistance = squaredDx( + x, y, flatCoordinates[0], flatCoordinates[1]); if (squaredDistance < minSquaredDistance) { - var stride = this.stride; - var i; + const stride = this.stride; + let i; for (i = 0; i < stride; ++i) { closestPoint[i] = flatCoordinates[i]; } @@ -111,7 +111,7 @@ Point.prototype.setCoordinates = function(coordinates, opt_layout) { this.flatCoordinates = []; } this.flatCoordinates.length = _ol_geom_flat_deflate_.coordinate( - this.flatCoordinates, 0, coordinates, this.stride); + this.flatCoordinates, 0, coordinates, this.stride); this.changed(); } }; diff --git a/src/ol/geom/Polygon.js b/src/ol/geom/Polygon.js index 22c8dbf902..3990e629ed 100644 --- a/src/ol/geom/Polygon.js +++ b/src/ol/geom/Polygon.js @@ -36,7 +36,7 @@ import {modulo} from '../math.js'; * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api */ -var Polygon = function(coordinates, opt_layout) { +const Polygon = function(coordinates, opt_layout) { SimpleGeometry.call(this); @@ -112,9 +112,9 @@ Polygon.prototype.appendLinearRing = function(linearRing) { * @api */ Polygon.prototype.clone = function() { - var polygon = new Polygon(null); + const polygon = new Polygon(null); polygon.setFlatCoordinates( - this.layout, this.flatCoordinates.slice(), this.ends_.slice()); + this.layout, this.flatCoordinates.slice(), this.ends_.slice()); return polygon; }; @@ -128,12 +128,12 @@ Polygon.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDistan } if (this.maxDeltaRevision_ != this.getRevision()) { this.maxDelta_ = Math.sqrt(_ol_geom_flat_closest_.getsMaxSquaredDelta( - this.flatCoordinates, 0, this.ends_, this.stride, 0)); + this.flatCoordinates, 0, this.ends_, this.stride, 0)); this.maxDeltaRevision_ = this.getRevision(); } return _ol_geom_flat_closest_.getsClosestPoint( - this.flatCoordinates, 0, this.ends_, this.stride, - this.maxDelta_, true, x, y, closestPoint, minSquaredDistance); + this.flatCoordinates, 0, this.ends_, this.stride, + this.maxDelta_, true, x, y, closestPoint, minSquaredDistance); }; @@ -142,7 +142,7 @@ Polygon.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDistan */ Polygon.prototype.containsXY = function(x, y) { return _ol_geom_flat_contains_.linearRingsContainsXY( - this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride, x, y); + this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride, x, y); }; @@ -153,7 +153,7 @@ Polygon.prototype.containsXY = function(x, y) { */ Polygon.prototype.getArea = function() { return _ol_geom_flat_area_.linearRings( - this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride); + this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride); }; @@ -172,17 +172,17 @@ Polygon.prototype.getArea = function() { * @api */ Polygon.prototype.getCoordinates = function(opt_right) { - var flatCoordinates; + let flatCoordinates; if (opt_right !== undefined) { flatCoordinates = this.getOrientedFlatCoordinates().slice(); _ol_geom_flat_orient_.orientLinearRings( - flatCoordinates, 0, this.ends_, this.stride, opt_right); + flatCoordinates, 0, this.ends_, this.stride, opt_right); } else { flatCoordinates = this.flatCoordinates; } return _ol_geom_flat_inflate_.coordinatess( - flatCoordinates, 0, this.ends_, this.stride); + flatCoordinates, 0, this.ends_, this.stride); }; @@ -199,10 +199,10 @@ Polygon.prototype.getEnds = function() { */ Polygon.prototype.getFlatInteriorPoint = function() { if (this.flatInteriorPointRevision_ != this.getRevision()) { - var flatCenter = getCenter(this.getExtent()); + const flatCenter = getCenter(this.getExtent()); this.flatInteriorPoint_ = _ol_geom_flat_interiorpoint_.linearRings( - this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride, - flatCenter, 0); + this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride, + flatCenter, 0); this.flatInteriorPointRevision_ = this.getRevision(); } return this.flatInteriorPoint_; @@ -246,9 +246,9 @@ Polygon.prototype.getLinearRing = function(index) { if (index < 0 || this.ends_.length <= index) { return null; } - var linearRing = new LinearRing(null); + const linearRing = new LinearRing(null); linearRing.setFlatCoordinates(this.layout, this.flatCoordinates.slice( - index === 0 ? 0 : this.ends_[index - 1], this.ends_[index])); + index === 0 ? 0 : this.ends_[index - 1], this.ends_[index])); return linearRing; }; @@ -259,15 +259,15 @@ Polygon.prototype.getLinearRing = function(index) { * @api */ Polygon.prototype.getLinearRings = function() { - var layout = this.layout; - var flatCoordinates = this.flatCoordinates; - var ends = this.ends_; - var linearRings = []; - var offset = 0; - var i, ii; + const layout = this.layout; + const flatCoordinates = this.flatCoordinates; + const ends = this.ends_; + const linearRings = []; + let offset = 0; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; - var linearRing = new LinearRing(null); + const end = ends[i]; + const linearRing = new LinearRing(null); linearRing.setFlatCoordinates(layout, flatCoordinates.slice(offset, end)); linearRings.push(linearRing); offset = end; @@ -281,15 +281,15 @@ Polygon.prototype.getLinearRings = function() { */ Polygon.prototype.getOrientedFlatCoordinates = function() { if (this.orientedRevision_ != this.getRevision()) { - var flatCoordinates = this.flatCoordinates; + const flatCoordinates = this.flatCoordinates; if (_ol_geom_flat_orient_.linearRingsAreOriented( - flatCoordinates, 0, this.ends_, this.stride)) { + flatCoordinates, 0, this.ends_, this.stride)) { this.orientedFlatCoordinates_ = flatCoordinates; } else { this.orientedFlatCoordinates_ = flatCoordinates.slice(); this.orientedFlatCoordinates_.length = _ol_geom_flat_orient_.orientLinearRings( - this.orientedFlatCoordinates_, 0, this.ends_, this.stride); + this.orientedFlatCoordinates_, 0, this.ends_, this.stride); } this.orientedRevision_ = this.getRevision(); } @@ -301,15 +301,15 @@ Polygon.prototype.getOrientedFlatCoordinates = function() { * @inheritDoc */ Polygon.prototype.getSimplifiedGeometryInternal = function(squaredTolerance) { - var simplifiedFlatCoordinates = []; - var simplifiedEnds = []; + const simplifiedFlatCoordinates = []; + const simplifiedEnds = []; simplifiedFlatCoordinates.length = _ol_geom_flat_simplify_.quantizes( - this.flatCoordinates, 0, this.ends_, this.stride, - Math.sqrt(squaredTolerance), - simplifiedFlatCoordinates, 0, simplifiedEnds); - var simplifiedPolygon = new Polygon(null); + this.flatCoordinates, 0, this.ends_, this.stride, + Math.sqrt(squaredTolerance), + simplifiedFlatCoordinates, 0, simplifiedEnds); + const simplifiedPolygon = new Polygon(null); simplifiedPolygon.setFlatCoordinates( - GeometryLayout.XY, simplifiedFlatCoordinates, simplifiedEnds); + GeometryLayout.XY, simplifiedFlatCoordinates, simplifiedEnds); return simplifiedPolygon; }; @@ -329,7 +329,7 @@ Polygon.prototype.getType = function() { */ Polygon.prototype.intersectsExtent = function(extent) { return _ol_geom_flat_intersectsextent_.linearRings( - this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride, extent); + this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride, extent); }; @@ -348,8 +348,8 @@ Polygon.prototype.setCoordinates = function(coordinates, opt_layout) { if (!this.flatCoordinates) { this.flatCoordinates = []; } - var ends = _ol_geom_flat_deflate_.coordinatess( - this.flatCoordinates, 0, coordinates, this.stride, this.ends_); + const ends = _ol_geom_flat_deflate_.coordinatess( + this.flatCoordinates, 0, coordinates, this.stride, this.ends_); this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1]; this.changed(); } @@ -383,17 +383,17 @@ export default Polygon; * @api */ export function circular(center, radius, opt_n, opt_sphereRadius) { - var n = opt_n ? opt_n : 32; + const n = opt_n ? opt_n : 32; /** @type {Array.} */ - var flatCoordinates = []; - var i; + const flatCoordinates = []; + let i; for (i = 0; i < n; ++i) { extend(flatCoordinates, sphereOffset(center, radius, 2 * Math.PI * i / n, opt_sphereRadius)); } flatCoordinates.push(flatCoordinates[0], flatCoordinates[1]); - var polygon = new Polygon(null); + const polygon = new Polygon(null); polygon.setFlatCoordinates( - GeometryLayout.XY, flatCoordinates, [flatCoordinates.length]); + GeometryLayout.XY, flatCoordinates, [flatCoordinates.length]); return polygon; } @@ -405,15 +405,15 @@ export function circular(center, radius, opt_n, opt_sphereRadius) { * @api */ export function fromExtent(extent) { - var minX = extent[0]; - var minY = extent[1]; - var maxX = extent[2]; - var maxY = extent[3]; - var flatCoordinates = + const minX = extent[0]; + const minY = extent[1]; + const maxX = extent[2]; + const maxY = extent[3]; + const flatCoordinates = [minX, minY, minX, maxY, maxX, maxY, maxX, minY, minX, minY]; - var polygon = new Polygon(null); + const polygon = new Polygon(null); polygon.setFlatCoordinates( - GeometryLayout.XY, flatCoordinates, [flatCoordinates.length]); + GeometryLayout.XY, flatCoordinates, [flatCoordinates.length]); return polygon; } @@ -428,16 +428,16 @@ export function fromExtent(extent) { * @api */ export function fromCircle(circle, opt_sides, opt_angle) { - var sides = opt_sides ? opt_sides : 32; - var stride = circle.getStride(); - var layout = circle.getLayout(); - var polygon = new Polygon(null, layout); - var arrayLength = stride * (sides + 1); - var flatCoordinates = new Array(arrayLength); - for (var i = 0; i < arrayLength; i++) { + const sides = opt_sides ? opt_sides : 32; + const stride = circle.getStride(); + const layout = circle.getLayout(); + const polygon = new Polygon(null, layout); + const arrayLength = stride * (sides + 1); + const flatCoordinates = new Array(arrayLength); + for (let i = 0; i < arrayLength; i++) { flatCoordinates[i] = 0; } - var ends = [flatCoordinates.length]; + const ends = [flatCoordinates.length]; polygon.setFlatCoordinates(layout, flatCoordinates, ends); makeRegular(polygon, circle.getCenter(), circle.getRadius(), opt_angle); return polygon; @@ -453,14 +453,14 @@ export function fromCircle(circle, opt_sides, opt_angle) { * radians. Default is 0. */ export function makeRegular(polygon, center, radius, opt_angle) { - var flatCoordinates = polygon.getFlatCoordinates(); - var layout = polygon.getLayout(); - var stride = polygon.getStride(); - var ends = polygon.getEnds(); - var sides = flatCoordinates.length / stride - 1; - var startAngle = opt_angle ? opt_angle : 0; - var angle, offset; - for (var i = 0; i <= sides; ++i) { + const flatCoordinates = polygon.getFlatCoordinates(); + const layout = polygon.getLayout(); + const stride = polygon.getStride(); + const ends = polygon.getEnds(); + const sides = flatCoordinates.length / stride - 1; + const startAngle = opt_angle ? opt_angle : 0; + let angle, offset; + for (let i = 0; i <= sides; ++i) { offset = i * stride; angle = startAngle + (modulo(i, sides) * 2 * Math.PI / sides); flatCoordinates[offset] = center[0] + (radius * Math.cos(angle)); diff --git a/src/ol/geom/SimpleGeometry.js b/src/ol/geom/SimpleGeometry.js index 57d658462d..3ab9b421d1 100644 --- a/src/ol/geom/SimpleGeometry.js +++ b/src/ol/geom/SimpleGeometry.js @@ -19,7 +19,7 @@ import _ol_obj_ from '../obj.js'; * @extends {ol.geom.Geometry} * @api */ -var SimpleGeometry = function() { +const SimpleGeometry = function() { Geometry.call(this); @@ -51,7 +51,7 @@ inherits(SimpleGeometry, Geometry); * @return {ol.geom.GeometryLayout} layout Layout. */ function getLayoutForStride(stride) { - var layout; + let layout; if (stride == 2) { layout = GeometryLayout.XY; } else if (stride == 3) { @@ -68,7 +68,7 @@ function getLayoutForStride(stride) { * @return {number} Stride. */ export function getStrideForLayout(layout) { - var stride; + let stride; if (layout == GeometryLayout.XY) { stride = 2; } else if (layout == GeometryLayout.XYZ || layout == GeometryLayout.XYM) { @@ -91,7 +91,7 @@ SimpleGeometry.prototype.containsXY = FALSE; */ SimpleGeometry.prototype.computeExtent = function(extent) { return createOrUpdateFromFlatCoordinates(this.flatCoordinates, - 0, this.flatCoordinates.length, this.stride, extent); + 0, this.flatCoordinates.length, this.stride, extent); }; @@ -156,13 +156,13 @@ SimpleGeometry.prototype.getSimplifiedGeometry = function(squaredTolerance) { squaredTolerance <= this.simplifiedGeometryMaxMinSquaredTolerance)) { return this; } - var key = squaredTolerance.toString(); + const key = squaredTolerance.toString(); if (this.simplifiedGeometryCache.hasOwnProperty(key)) { return this.simplifiedGeometryCache[key]; } else { - var simplifiedGeometry = + const simplifiedGeometry = this.getSimplifiedGeometryInternal(squaredTolerance); - var simplifiedFlatCoordinates = simplifiedGeometry.getFlatCoordinates(); + const simplifiedFlatCoordinates = simplifiedGeometry.getFlatCoordinates(); if (simplifiedFlatCoordinates.length < this.flatCoordinates.length) { this.simplifiedGeometryCache[key] = simplifiedGeometry; return simplifiedGeometry; @@ -226,11 +226,11 @@ SimpleGeometry.prototype.setCoordinates = function(coordinates, opt_layout) {}; */ SimpleGeometry.prototype.setLayout = function(layout, coordinates, nesting) { /** @type {number} */ - var stride; + let stride; if (layout) { stride = getStrideForLayout(layout); } else { - var i; + let i; for (i = 0; i < nesting; ++i) { if (coordinates.length === 0) { this.layout = GeometryLayout.XY; @@ -265,12 +265,12 @@ SimpleGeometry.prototype.applyTransform = function(transformFn) { * @api */ SimpleGeometry.prototype.rotate = function(angle, anchor) { - var flatCoordinates = this.getFlatCoordinates(); + const flatCoordinates = this.getFlatCoordinates(); if (flatCoordinates) { - var stride = this.getStride(); + const stride = this.getStride(); _ol_geom_flat_transform_.rotate( - flatCoordinates, 0, flatCoordinates.length, - stride, angle, anchor, flatCoordinates); + flatCoordinates, 0, flatCoordinates.length, + stride, angle, anchor, flatCoordinates); this.changed(); } }; @@ -281,20 +281,20 @@ SimpleGeometry.prototype.rotate = function(angle, anchor) { * @api */ SimpleGeometry.prototype.scale = function(sx, opt_sy, opt_anchor) { - var sy = opt_sy; + let sy = opt_sy; if (sy === undefined) { sy = sx; } - var anchor = opt_anchor; + let anchor = opt_anchor; if (!anchor) { anchor = getCenter(this.getExtent()); } - var flatCoordinates = this.getFlatCoordinates(); + const flatCoordinates = this.getFlatCoordinates(); if (flatCoordinates) { - var stride = this.getStride(); + const stride = this.getStride(); _ol_geom_flat_transform_.scale( - flatCoordinates, 0, flatCoordinates.length, - stride, sx, sy, anchor, flatCoordinates); + flatCoordinates, 0, flatCoordinates.length, + stride, sx, sy, anchor, flatCoordinates); this.changed(); } }; @@ -305,12 +305,12 @@ SimpleGeometry.prototype.scale = function(sx, opt_sy, opt_anchor) { * @api */ SimpleGeometry.prototype.translate = function(deltaX, deltaY) { - var flatCoordinates = this.getFlatCoordinates(); + const flatCoordinates = this.getFlatCoordinates(); if (flatCoordinates) { - var stride = this.getStride(); + const stride = this.getStride(); _ol_geom_flat_transform_.translate( - flatCoordinates, 0, flatCoordinates.length, stride, - deltaX, deltaY, flatCoordinates); + flatCoordinates, 0, flatCoordinates.length, stride, + deltaX, deltaY, flatCoordinates); this.changed(); } }; @@ -323,14 +323,14 @@ SimpleGeometry.prototype.translate = function(deltaX, deltaY) { * @return {Array.} Transformed flat coordinates. */ SimpleGeometry.transform2D = function(simpleGeometry, transform, opt_dest) { - var flatCoordinates = simpleGeometry.getFlatCoordinates(); + const flatCoordinates = simpleGeometry.getFlatCoordinates(); if (!flatCoordinates) { return null; } else { - var stride = simpleGeometry.getStride(); + const stride = simpleGeometry.getStride(); return _ol_geom_flat_transform_.transform2D( - flatCoordinates, 0, flatCoordinates.length, stride, - transform, opt_dest); + flatCoordinates, 0, flatCoordinates.length, stride, + transform, opt_dest); } }; export default SimpleGeometry; diff --git a/src/ol/geom/flat/area.js b/src/ol/geom/flat/area.js index f4bcd552d0..10291e6496 100644 --- a/src/ol/geom/flat/area.js +++ b/src/ol/geom/flat/area.js @@ -1,7 +1,7 @@ /** * @module ol/geom/flat/area */ -var _ol_geom_flat_area_ = {}; +const _ol_geom_flat_area_ = {}; /** @@ -12,12 +12,12 @@ var _ol_geom_flat_area_ = {}; * @return {number} Area. */ _ol_geom_flat_area_.linearRing = function(flatCoordinates, offset, end, stride) { - var twiceArea = 0; - var x1 = flatCoordinates[end - stride]; - var y1 = flatCoordinates[end - stride + 1]; + let twiceArea = 0; + let x1 = flatCoordinates[end - stride]; + let y1 = flatCoordinates[end - stride + 1]; for (; offset < end; offset += stride) { - var x2 = flatCoordinates[offset]; - var y2 = flatCoordinates[offset + 1]; + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; twiceArea += y1 * x2 - x1 * y2; x1 = x2; y1 = y2; @@ -34,10 +34,10 @@ _ol_geom_flat_area_.linearRing = function(flatCoordinates, offset, end, stride) * @return {number} Area. */ _ol_geom_flat_area_.linearRings = function(flatCoordinates, offset, ends, stride) { - var area = 0; - var i, ii; + let area = 0; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; + const end = ends[i]; area += _ol_geom_flat_area_.linearRing(flatCoordinates, offset, end, stride); offset = end; } @@ -53,10 +53,10 @@ _ol_geom_flat_area_.linearRings = function(flatCoordinates, offset, ends, stride * @return {number} Area. */ _ol_geom_flat_area_.linearRingss = function(flatCoordinates, offset, endss, stride) { - var area = 0; - var i, ii; + let area = 0; + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; + const ends = endss[i]; area += _ol_geom_flat_area_.linearRings(flatCoordinates, offset, ends, stride); offset = ends[ends.length - 1]; diff --git a/src/ol/geom/flat/center.js b/src/ol/geom/flat/center.js index 4f909cacee..e86a523c0c 100644 --- a/src/ol/geom/flat/center.js +++ b/src/ol/geom/flat/center.js @@ -2,7 +2,7 @@ * @module ol/geom/flat/center */ import {createEmpty, createOrUpdateFromFlatCoordinates} from '../../extent.js'; -var _ol_geom_flat_center_ = {}; +const _ol_geom_flat_center_ = {}; /** @@ -13,11 +13,11 @@ var _ol_geom_flat_center_ = {}; * @return {Array.} Flat centers. */ _ol_geom_flat_center_.linearRingss = function(flatCoordinates, offset, endss, stride) { - var flatCenters = []; - var i, ii; - var extent = createEmpty(); + const flatCenters = []; + let i, ii; + let extent = createEmpty(); for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; + const ends = endss[i]; extent = createOrUpdateFromFlatCoordinates(flatCoordinates, offset, ends[0], stride); flatCenters.push((extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2); offset = ends[ends.length - 1]; diff --git a/src/ol/geom/flat/closest.js b/src/ol/geom/flat/closest.js index 72a7618f98..02ac2a1102 100644 --- a/src/ol/geom/flat/closest.js +++ b/src/ol/geom/flat/closest.js @@ -2,7 +2,7 @@ * @module ol/geom/flat/closest */ import {lerp, squaredDistance as squaredDx} from '../../math.js'; -var _ol_geom_flat_closest_ = {}; +const _ol_geom_flat_closest_ = {}; /** @@ -18,21 +18,21 @@ var _ol_geom_flat_closest_ = {}; * @param {Array.} closestPoint Closest point. */ _ol_geom_flat_closest_.point = function(flatCoordinates, offset1, offset2, stride, x, y, closestPoint) { - var x1 = flatCoordinates[offset1]; - var y1 = flatCoordinates[offset1 + 1]; - var dx = flatCoordinates[offset2] - x1; - var dy = flatCoordinates[offset2 + 1] - y1; - var i, offset; + const x1 = flatCoordinates[offset1]; + const y1 = flatCoordinates[offset1 + 1]; + const dx = flatCoordinates[offset2] - x1; + const dy = flatCoordinates[offset2 + 1] - y1; + let i, offset; if (dx === 0 && dy === 0) { offset = offset1; } else { - var t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy); + const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy); if (t > 1) { offset = offset2; } else if (t > 0) { for (i = 0; i < stride; ++i) { closestPoint[i] = lerp(flatCoordinates[offset1 + i], - flatCoordinates[offset2 + i], t); + flatCoordinates[offset2 + i], t); } closestPoint.length = stride; return; @@ -58,12 +58,12 @@ _ol_geom_flat_closest_.point = function(flatCoordinates, offset1, offset2, strid * @return {number} Max squared delta. */ _ol_geom_flat_closest_.getMaxSquaredDelta = function(flatCoordinates, offset, end, stride, maxSquaredDelta) { - var x1 = flatCoordinates[offset]; - var y1 = flatCoordinates[offset + 1]; + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; for (offset += stride; offset < end; offset += stride) { - var x2 = flatCoordinates[offset]; - var y2 = flatCoordinates[offset + 1]; - var squaredDelta = squaredDx(x1, y1, x2, y2); + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; + const squaredDelta = squaredDx(x1, y1, x2, y2); if (squaredDelta > maxSquaredDelta) { maxSquaredDelta = squaredDelta; } @@ -83,11 +83,11 @@ _ol_geom_flat_closest_.getMaxSquaredDelta = function(flatCoordinates, offset, en * @return {number} Max squared delta. */ _ol_geom_flat_closest_.getsMaxSquaredDelta = function(flatCoordinates, offset, ends, stride, maxSquaredDelta) { - var i, ii; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; + const end = ends[i]; maxSquaredDelta = _ol_geom_flat_closest_.getMaxSquaredDelta( - flatCoordinates, offset, end, stride, maxSquaredDelta); + flatCoordinates, offset, end, stride, maxSquaredDelta); offset = end; } return maxSquaredDelta; @@ -103,11 +103,11 @@ _ol_geom_flat_closest_.getsMaxSquaredDelta = function(flatCoordinates, offset, e * @return {number} Max squared delta. */ _ol_geom_flat_closest_.getssMaxSquaredDelta = function(flatCoordinates, offset, endss, stride, maxSquaredDelta) { - var i, ii; + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; + const ends = endss[i]; maxSquaredDelta = _ol_geom_flat_closest_.getsMaxSquaredDelta( - flatCoordinates, offset, ends, stride, maxSquaredDelta); + flatCoordinates, offset, ends, stride, maxSquaredDelta); offset = ends[ends.length - 1]; } return maxSquaredDelta; @@ -129,16 +129,16 @@ _ol_geom_flat_closest_.getssMaxSquaredDelta = function(flatCoordinates, offset, * @return {number} Minimum squared distance. */ _ol_geom_flat_closest_.getClosestPoint = function(flatCoordinates, offset, end, - stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance, - opt_tmpPoint) { + stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance, + opt_tmpPoint) { if (offset == end) { return minSquaredDistance; } - var i, squaredDistance; + let i, squaredDistance; if (maxDelta === 0) { // All points are identical, so just test the first point. squaredDistance = squaredDx( - x, y, flatCoordinates[offset], flatCoordinates[offset + 1]); + x, y, flatCoordinates[offset], flatCoordinates[offset + 1]); if (squaredDistance < minSquaredDistance) { for (i = 0; i < stride; ++i) { closestPoint[i] = flatCoordinates[offset + i]; @@ -149,11 +149,11 @@ _ol_geom_flat_closest_.getClosestPoint = function(flatCoordinates, offset, end, return minSquaredDistance; } } - var tmpPoint = opt_tmpPoint ? opt_tmpPoint : [NaN, NaN]; - var index = offset + stride; + const tmpPoint = opt_tmpPoint ? opt_tmpPoint : [NaN, NaN]; + let index = offset + stride; while (index < end) { _ol_geom_flat_closest_.point( - flatCoordinates, index - stride, index, stride, x, y, tmpPoint); + flatCoordinates, index - stride, index, stride, x, y, tmpPoint); squaredDistance = squaredDx(x, y, tmpPoint[0], tmpPoint[1]); if (squaredDistance < minSquaredDistance) { minSquaredDistance = squaredDistance; @@ -174,14 +174,14 @@ _ol_geom_flat_closest_.getClosestPoint = function(flatCoordinates, offset, end, // finding a closer point. We use Math.max(..., 1) to ensure that we // always advance at least one point, to avoid an infinite loop. index += stride * Math.max( - ((Math.sqrt(squaredDistance) - + ((Math.sqrt(squaredDistance) - Math.sqrt(minSquaredDistance)) / maxDelta) | 0, 1); } } if (isRing) { // Check the closing segment. _ol_geom_flat_closest_.point( - flatCoordinates, end - stride, offset, stride, x, y, tmpPoint); + flatCoordinates, end - stride, offset, stride, x, y, tmpPoint); squaredDistance = squaredDx(x, y, tmpPoint[0], tmpPoint[1]); if (squaredDistance < minSquaredDistance) { minSquaredDistance = squaredDistance; @@ -210,15 +210,15 @@ _ol_geom_flat_closest_.getClosestPoint = function(flatCoordinates, offset, end, * @return {number} Minimum squared distance. */ _ol_geom_flat_closest_.getsClosestPoint = function(flatCoordinates, offset, ends, - stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance, - opt_tmpPoint) { - var tmpPoint = opt_tmpPoint ? opt_tmpPoint : [NaN, NaN]; - var i, ii; + stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance, + opt_tmpPoint) { + const tmpPoint = opt_tmpPoint ? opt_tmpPoint : [NaN, NaN]; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; + const end = ends[i]; minSquaredDistance = _ol_geom_flat_closest_.getClosestPoint( - flatCoordinates, offset, end, stride, - maxDelta, isRing, x, y, closestPoint, minSquaredDistance, tmpPoint); + flatCoordinates, offset, end, stride, + maxDelta, isRing, x, y, closestPoint, minSquaredDistance, tmpPoint); offset = end; } return minSquaredDistance; @@ -240,15 +240,15 @@ _ol_geom_flat_closest_.getsClosestPoint = function(flatCoordinates, offset, ends * @return {number} Minimum squared distance. */ _ol_geom_flat_closest_.getssClosestPoint = function(flatCoordinates, offset, - endss, stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance, - opt_tmpPoint) { - var tmpPoint = opt_tmpPoint ? opt_tmpPoint : [NaN, NaN]; - var i, ii; + endss, stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance, + opt_tmpPoint) { + const tmpPoint = opt_tmpPoint ? opt_tmpPoint : [NaN, NaN]; + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; + const ends = endss[i]; minSquaredDistance = _ol_geom_flat_closest_.getsClosestPoint( - flatCoordinates, offset, ends, stride, - maxDelta, isRing, x, y, closestPoint, minSquaredDistance, tmpPoint); + flatCoordinates, offset, ends, stride, + maxDelta, isRing, x, y, closestPoint, minSquaredDistance, tmpPoint); offset = ends[ends.length - 1]; } return minSquaredDistance; diff --git a/src/ol/geom/flat/contains.js b/src/ol/geom/flat/contains.js index 813fa049b4..00d72acfb2 100644 --- a/src/ol/geom/flat/contains.js +++ b/src/ol/geom/flat/contains.js @@ -2,7 +2,7 @@ * @module ol/geom/flat/contains */ import {forEachCorner} from '../../extent.js'; -var _ol_geom_flat_contains_ = {}; +const _ol_geom_flat_contains_ = {}; /** @@ -14,15 +14,15 @@ var _ol_geom_flat_contains_ = {}; * @return {boolean} Contains extent. */ _ol_geom_flat_contains_.linearRingContainsExtent = function(flatCoordinates, offset, end, stride, extent) { - var outside = forEachCorner(extent, - /** + const outside = forEachCorner(extent, + /** * @param {ol.Coordinate} coordinate Coordinate. * @return {boolean} Contains (x, y). */ - function(coordinate) { - return !_ol_geom_flat_contains_.linearRingContainsXY(flatCoordinates, - offset, end, stride, coordinate[0], coordinate[1]); - }); + function(coordinate) { + return !_ol_geom_flat_contains_.linearRingContainsXY(flatCoordinates, + offset, end, stride, coordinate[0], coordinate[1]); + }); return !outside; }; @@ -44,12 +44,12 @@ _ol_geom_flat_contains_.linearRingContainsXY = function(flatCoordinates, offset, // SoftSurfer makes no warranty for this code, and cannot be held // liable for any real or imagined damage resulting from its use. // Users of this code must verify correctness for their application. - var wn = 0; - var x1 = flatCoordinates[end - stride]; - var y1 = flatCoordinates[end - stride + 1]; + let wn = 0; + let x1 = flatCoordinates[end - stride]; + let y1 = flatCoordinates[end - stride + 1]; for (; offset < end; offset += stride) { - var x2 = flatCoordinates[offset]; - var y2 = flatCoordinates[offset + 1]; + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; if (y1 <= y) { if (y2 > y && ((x2 - x1) * (y - y1)) - ((x - x1) * (y2 - y1)) > 0) { wn++; @@ -78,13 +78,13 @@ _ol_geom_flat_contains_.linearRingsContainsXY = function(flatCoordinates, offset return false; } if (!_ol_geom_flat_contains_.linearRingContainsXY( - flatCoordinates, offset, ends[0], stride, x, y)) { + flatCoordinates, offset, ends[0], stride, x, y)) { return false; } - var i, ii; + let i, ii; for (i = 1, ii = ends.length; i < ii; ++i) { if (_ol_geom_flat_contains_.linearRingContainsXY( - flatCoordinates, ends[i - 1], ends[i], stride, x, y)) { + flatCoordinates, ends[i - 1], ends[i], stride, x, y)) { return false; } } @@ -105,11 +105,11 @@ _ol_geom_flat_contains_.linearRingssContainsXY = function(flatCoordinates, offse if (endss.length === 0) { return false; } - var i, ii; + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; + const ends = endss[i]; if (_ol_geom_flat_contains_.linearRingsContainsXY( - flatCoordinates, offset, ends, stride, x, y)) { + flatCoordinates, offset, ends, stride, x, y)) { return true; } offset = ends[ends.length - 1]; diff --git a/src/ol/geom/flat/deflate.js b/src/ol/geom/flat/deflate.js index 66816e04f2..52f318a2d1 100644 --- a/src/ol/geom/flat/deflate.js +++ b/src/ol/geom/flat/deflate.js @@ -1,7 +1,7 @@ /** * @module ol/geom/flat/deflate */ -var _ol_geom_flat_deflate_ = {}; +const _ol_geom_flat_deflate_ = {}; /** @@ -12,7 +12,7 @@ var _ol_geom_flat_deflate_ = {}; * @return {number} offset Offset. */ _ol_geom_flat_deflate_.coordinate = function(flatCoordinates, offset, coordinate, stride) { - var i, ii; + let i, ii; for (i = 0, ii = coordinate.length; i < ii; ++i) { flatCoordinates[offset++] = coordinate[i]; } @@ -28,11 +28,10 @@ _ol_geom_flat_deflate_.coordinate = function(flatCoordinates, offset, coordinate * @return {number} offset Offset. */ _ol_geom_flat_deflate_.coordinates = function(flatCoordinates, offset, coordinates, stride) { - var i, ii; + let i, ii; for (i = 0, ii = coordinates.length; i < ii; ++i) { - var coordinate = coordinates[i]; - var j; - for (j = 0; j < stride; ++j) { + const coordinate = coordinates[i]; + for (let j = 0; j < stride; ++j) { flatCoordinates[offset++] = coordinate[j]; } } @@ -49,12 +48,12 @@ _ol_geom_flat_deflate_.coordinates = function(flatCoordinates, offset, coordinat * @return {Array.} Ends. */ _ol_geom_flat_deflate_.coordinatess = function(flatCoordinates, offset, coordinatess, stride, opt_ends) { - var ends = opt_ends ? opt_ends : []; - var i = 0; - var j, jj; + const ends = opt_ends ? opt_ends : []; + let i = 0; + let j, jj; for (j = 0, jj = coordinatess.length; j < jj; ++j) { - var end = _ol_geom_flat_deflate_.coordinates( - flatCoordinates, offset, coordinatess[j], stride); + const end = _ol_geom_flat_deflate_.coordinates( + flatCoordinates, offset, coordinatess[j], stride); ends[i++] = end; offset = end; } @@ -72,12 +71,12 @@ _ol_geom_flat_deflate_.coordinatess = function(flatCoordinates, offset, coordina * @return {Array.>} Endss. */ _ol_geom_flat_deflate_.coordinatesss = function(flatCoordinates, offset, coordinatesss, stride, opt_endss) { - var endss = opt_endss ? opt_endss : []; - var i = 0; - var j, jj; + const endss = opt_endss ? opt_endss : []; + let i = 0; + let j, jj; for (j = 0, jj = coordinatesss.length; j < jj; ++j) { - var ends = _ol_geom_flat_deflate_.coordinatess( - flatCoordinates, offset, coordinatesss[j], stride, endss[i]); + const ends = _ol_geom_flat_deflate_.coordinatess( + flatCoordinates, offset, coordinatesss[j], stride, endss[i]); endss[i++] = ends; offset = ends[ends.length - 1]; } diff --git a/src/ol/geom/flat/flip.js b/src/ol/geom/flat/flip.js index 132d20a206..53658ca0e0 100644 --- a/src/ol/geom/flat/flip.js +++ b/src/ol/geom/flat/flip.js @@ -1,7 +1,7 @@ /** * @module ol/geom/flat/flip */ -var _ol_geom_flat_flip_ = {}; +const _ol_geom_flat_flip_ = {}; /** @@ -14,7 +14,7 @@ var _ol_geom_flat_flip_ = {}; * @return {Array.} Flat coordinates. */ _ol_geom_flat_flip_.flipXY = function(flatCoordinates, offset, end, stride, opt_dest, opt_destOffset) { - var dest, destOffset; + let dest, destOffset; if (opt_dest !== undefined) { dest = opt_dest; destOffset = opt_destOffset !== undefined ? opt_destOffset : 0; @@ -22,12 +22,12 @@ _ol_geom_flat_flip_.flipXY = function(flatCoordinates, offset, end, stride, opt_ dest = []; destOffset = 0; } - var j = offset; + let j = offset; while (j < end) { - var x = flatCoordinates[j++]; + const x = flatCoordinates[j++]; dest[destOffset++] = flatCoordinates[j++]; dest[destOffset++] = x; - for (var k = 2; k < stride; ++k) { + for (let k = 2; k < stride; ++k) { dest[destOffset++] = flatCoordinates[j++]; } } diff --git a/src/ol/geom/flat/geodesic.js b/src/ol/geom/flat/geodesic.js index 7cd0b0e39a..dfaeabedcf 100644 --- a/src/ol/geom/flat/geodesic.js +++ b/src/ol/geom/flat/geodesic.js @@ -3,7 +3,7 @@ */ import {squaredSegmentDistance, toRadians, toDegrees} from '../../math.js'; import {get as getProjection, getTransform} from '../../proj.js'; -var _ol_geom_flat_geodesic_ = {}; +const _ol_geom_flat_geodesic_ = {}; /** @@ -19,26 +19,26 @@ _ol_geom_flat_geodesic_.line_ = function(interpolate, transform, squaredToleranc // FIXME optimize stack operations /** @type {Array.} */ - var flatCoordinates = []; + const flatCoordinates = []; - var geoA = interpolate(0); - var geoB = interpolate(1); + let geoA = interpolate(0); + let geoB = interpolate(1); - var a = transform(geoA); - var b = transform(geoB); + let a = transform(geoA); + let b = transform(geoB); /** @type {Array.} */ - var geoStack = [geoB, geoA]; + const geoStack = [geoB, geoA]; /** @type {Array.} */ - var stack = [b, a]; + const stack = [b, a]; /** @type {Array.} */ - var fractionStack = [1, 0]; + const fractionStack = [1, 0]; /** @type {Object.} */ - var fractions = {}; + const fractions = {}; - var maxIterations = 1e5; - var geoM, m, fracA, fracB, fracM, key; + let maxIterations = 1e5; + let geoM, m, fracA, fracB, fracM, key; while (--maxIterations > 0 && fractionStack.length > 0) { // Pop the a coordinate off the stack @@ -60,7 +60,7 @@ _ol_geom_flat_geodesic_.line_ = function(interpolate, transform, squaredToleranc geoM = interpolate(fracM); m = transform(geoM); if (squaredSegmentDistance(m[0], m[1], a[0], a[1], - b[0], b[1]) < squaredTolerance) { + b[0], b[1]) < squaredTolerance) { // If the m point is sufficiently close to the straight line, then we // discard it. Just use the b coordinate and move on to the next line // segment. @@ -91,39 +91,39 @@ _ol_geom_flat_geodesic_.line_ = function(interpolate, transform, squaredToleranc * @return {Array.} Flat coordinates. */ _ol_geom_flat_geodesic_.greatCircleArc = function( - lon1, lat1, lon2, lat2, projection, squaredTolerance) { + lon1, lat1, lon2, lat2, projection, squaredTolerance) { - var geoProjection = getProjection('EPSG:4326'); + const geoProjection = getProjection('EPSG:4326'); - var cosLat1 = Math.cos(toRadians(lat1)); - var sinLat1 = Math.sin(toRadians(lat1)); - var cosLat2 = Math.cos(toRadians(lat2)); - var sinLat2 = Math.sin(toRadians(lat2)); - var cosDeltaLon = Math.cos(toRadians(lon2 - lon1)); - var sinDeltaLon = Math.sin(toRadians(lon2 - lon1)); - var d = sinLat1 * sinLat2 + cosLat1 * cosLat2 * cosDeltaLon; + const cosLat1 = Math.cos(toRadians(lat1)); + const sinLat1 = Math.sin(toRadians(lat1)); + const cosLat2 = Math.cos(toRadians(lat2)); + const sinLat2 = Math.sin(toRadians(lat2)); + const cosDeltaLon = Math.cos(toRadians(lon2 - lon1)); + const sinDeltaLon = Math.sin(toRadians(lon2 - lon1)); + const d = sinLat1 * sinLat2 + cosLat1 * cosLat2 * cosDeltaLon; return _ol_geom_flat_geodesic_.line_( - /** + /** * @param {number} frac Fraction. * @return {ol.Coordinate} Coordinate. */ - function(frac) { - if (1 <= d) { - return [lon2, lat2]; - } - var D = frac * Math.acos(d); - var cosD = Math.cos(D); - var sinD = Math.sin(D); - var y = sinDeltaLon * cosLat2; - var x = cosLat1 * sinLat2 - sinLat1 * cosLat2 * cosDeltaLon; - var theta = Math.atan2(y, x); - var lat = Math.asin(sinLat1 * cosD + cosLat1 * sinD * Math.cos(theta)); - var lon = toRadians(lon1) + + function(frac) { + if (1 <= d) { + return [lon2, lat2]; + } + const D = frac * Math.acos(d); + const cosD = Math.cos(D); + const sinD = Math.sin(D); + const y = sinDeltaLon * cosLat2; + const x = cosLat1 * sinLat2 - sinLat1 * cosLat2 * cosDeltaLon; + const theta = Math.atan2(y, x); + const lat = Math.asin(sinLat1 * cosD + cosLat1 * sinD * Math.cos(theta)); + const lon = toRadians(lon1) + Math.atan2(Math.sin(theta) * sinD * cosLat1, - cosD - sinLat1 * Math.sin(lat)); - return [toDegrees(lon), toDegrees(lat)]; - }, getTransform(geoProjection, projection), squaredTolerance); + cosD - sinLat1 * Math.sin(lat)); + return [toDegrees(lon), toDegrees(lat)]; + }, getTransform(geoProjection, projection), squaredTolerance); }; @@ -137,16 +137,16 @@ _ol_geom_flat_geodesic_.greatCircleArc = function( * @return {Array.} Flat coordinates. */ _ol_geom_flat_geodesic_.meridian = function(lon, lat1, lat2, projection, squaredTolerance) { - var epsg4326Projection = getProjection('EPSG:4326'); + const epsg4326Projection = getProjection('EPSG:4326'); return _ol_geom_flat_geodesic_.line_( - /** + /** * @param {number} frac Fraction. * @return {ol.Coordinate} Coordinate. */ - function(frac) { - return [lon, lat1 + ((lat2 - lat1) * frac)]; - }, - getTransform(epsg4326Projection, projection), squaredTolerance); + function(frac) { + return [lon, lat1 + ((lat2 - lat1) * frac)]; + }, + getTransform(epsg4326Projection, projection), squaredTolerance); }; @@ -160,15 +160,15 @@ _ol_geom_flat_geodesic_.meridian = function(lon, lat1, lat2, projection, squared * @return {Array.} Flat coordinates. */ _ol_geom_flat_geodesic_.parallel = function(lat, lon1, lon2, projection, squaredTolerance) { - var epsg4326Projection = getProjection('EPSG:4326'); + const epsg4326Projection = getProjection('EPSG:4326'); return _ol_geom_flat_geodesic_.line_( - /** + /** * @param {number} frac Fraction. * @return {ol.Coordinate} Coordinate. */ - function(frac) { - return [lon1 + ((lon2 - lon1) * frac), lat]; - }, - getTransform(epsg4326Projection, projection), squaredTolerance); + function(frac) { + return [lon1 + ((lon2 - lon1) * frac), lat]; + }, + getTransform(epsg4326Projection, projection), squaredTolerance); }; export default _ol_geom_flat_geodesic_; diff --git a/src/ol/geom/flat/inflate.js b/src/ol/geom/flat/inflate.js index 825b3078d0..bbe7102a29 100644 --- a/src/ol/geom/flat/inflate.js +++ b/src/ol/geom/flat/inflate.js @@ -1,7 +1,7 @@ /** * @module ol/geom/flat/inflate */ -var _ol_geom_flat_inflate_ = {}; +const _ol_geom_flat_inflate_ = {}; /** @@ -13,9 +13,9 @@ var _ol_geom_flat_inflate_ = {}; * @return {Array.} Coordinates. */ _ol_geom_flat_inflate_.coordinates = function(flatCoordinates, offset, end, stride, opt_coordinates) { - var coordinates = opt_coordinates !== undefined ? opt_coordinates : []; - var i = 0; - var j; + const coordinates = opt_coordinates !== undefined ? opt_coordinates : []; + let i = 0; + let j; for (j = offset; j < end; j += stride) { coordinates[i++] = flatCoordinates.slice(j, j + stride); } @@ -33,13 +33,13 @@ _ol_geom_flat_inflate_.coordinates = function(flatCoordinates, offset, end, stri * @return {Array.>} Coordinatess. */ _ol_geom_flat_inflate_.coordinatess = function(flatCoordinates, offset, ends, stride, opt_coordinatess) { - var coordinatess = opt_coordinatess !== undefined ? opt_coordinatess : []; - var i = 0; - var j, jj; + const coordinatess = opt_coordinatess !== undefined ? opt_coordinatess : []; + let i = 0; + let j, jj; for (j = 0, jj = ends.length; j < jj; ++j) { - var end = ends[j]; + const end = ends[j]; coordinatess[i++] = _ol_geom_flat_inflate_.coordinates( - flatCoordinates, offset, end, stride, coordinatess[i]); + flatCoordinates, offset, end, stride, coordinatess[i]); offset = end; } coordinatess.length = i; @@ -57,13 +57,13 @@ _ol_geom_flat_inflate_.coordinatess = function(flatCoordinates, offset, ends, st * @return {Array.>>} Coordinatesss. */ _ol_geom_flat_inflate_.coordinatesss = function(flatCoordinates, offset, endss, stride, opt_coordinatesss) { - var coordinatesss = opt_coordinatesss !== undefined ? opt_coordinatesss : []; - var i = 0; - var j, jj; + const coordinatesss = opt_coordinatesss !== undefined ? opt_coordinatesss : []; + let i = 0; + let j, jj; for (j = 0, jj = endss.length; j < jj; ++j) { - var ends = endss[j]; + const ends = endss[j]; coordinatesss[i++] = _ol_geom_flat_inflate_.coordinatess( - flatCoordinates, offset, ends, stride, coordinatesss[i]); + flatCoordinates, offset, ends, stride, coordinatesss[i]); offset = ends[ends.length - 1]; } coordinatesss.length = i; diff --git a/src/ol/geom/flat/interiorpoint.js b/src/ol/geom/flat/interiorpoint.js index 6ef7dce65f..079f154768 100644 --- a/src/ol/geom/flat/interiorpoint.js +++ b/src/ol/geom/flat/interiorpoint.js @@ -3,7 +3,7 @@ */ import {numberSafeCompareFunction} from '../../array.js'; import _ol_geom_flat_contains_ from '../flat/contains.js'; -var _ol_geom_flat_interiorpoint_ = {}; +const _ol_geom_flat_interiorpoint_ = {}; /** @@ -20,14 +20,14 @@ var _ol_geom_flat_interiorpoint_ = {}; * length of the horizontal intersection that the point belongs to. */ _ol_geom_flat_interiorpoint_.linearRings = function(flatCoordinates, offset, - ends, stride, flatCenters, flatCentersOffset, opt_dest) { - var i, ii, x, x1, x2, y1, y2; - var y = flatCenters[flatCentersOffset + 1]; + ends, stride, flatCenters, flatCentersOffset, opt_dest) { + let i, ii, x, x1, x2, y1, y2; + const y = flatCenters[flatCentersOffset + 1]; /** @type {Array.} */ - var intersections = []; + const intersections = []; // Calculate intersections with the horizontal line - for (var r = 0, rr = ends.length; r < rr; ++r) { - var end = ends[r]; + for (let r = 0, rr = ends.length; r < rr; ++r) { + const end = ends[r]; x1 = flatCoordinates[end - stride]; y1 = flatCoordinates[end - stride + 1]; for (i = offset; i < end; i += stride) { @@ -43,17 +43,17 @@ _ol_geom_flat_interiorpoint_.linearRings = function(flatCoordinates, offset, } // Find the longest segment of the horizontal line that has its center point // inside the linear ring. - var pointX = NaN; - var maxSegmentLength = -Infinity; + let pointX = NaN; + let maxSegmentLength = -Infinity; intersections.sort(numberSafeCompareFunction); x1 = intersections[0]; for (i = 1, ii = intersections.length; i < ii; ++i) { x2 = intersections[i]; - var segmentLength = Math.abs(x2 - x1); + const segmentLength = Math.abs(x2 - x1); if (segmentLength > maxSegmentLength) { x = (x1 + x2) / 2; if (_ol_geom_flat_contains_.linearRingsContainsXY( - flatCoordinates, offset, ends, stride, x, y)) { + flatCoordinates, offset, ends, stride, x, y)) { pointX = x; maxSegmentLength = segmentLength; } @@ -84,12 +84,12 @@ _ol_geom_flat_interiorpoint_.linearRings = function(flatCoordinates, offset, * length of the horizontal intersection that the point belongs to. */ _ol_geom_flat_interiorpoint_.linearRingss = function(flatCoordinates, offset, endss, stride, flatCenters) { - var interiorPoints = []; - var i, ii; + let interiorPoints = []; + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; + const ends = endss[i]; interiorPoints = _ol_geom_flat_interiorpoint_.linearRings(flatCoordinates, - offset, ends, stride, flatCenters, 2 * i, interiorPoints); + offset, ends, stride, flatCenters, 2 * i, interiorPoints); offset = ends[ends.length - 1]; } return interiorPoints; diff --git a/src/ol/geom/flat/interpolate.js b/src/ol/geom/flat/interpolate.js index 76e55f74bc..6deb41fea2 100644 --- a/src/ol/geom/flat/interpolate.js +++ b/src/ol/geom/flat/interpolate.js @@ -3,7 +3,7 @@ */ import {binarySearch} from '../../array.js'; import {lerp} from '../../math.js'; -var _ol_geom_flat_interpolate_ = {}; +const _ol_geom_flat_interpolate_ = {}; /** @@ -16,9 +16,9 @@ var _ol_geom_flat_interpolate_ = {}; * @return {Array.} Destination. */ _ol_geom_flat_interpolate_.lineString = function(flatCoordinates, offset, end, stride, fraction, opt_dest) { - var pointX = NaN; - var pointY = NaN; - var n = (end - offset) / stride; + let pointX = NaN; + let pointY = NaN; + const n = (end - offset) / stride; if (n === 1) { pointX = flatCoordinates[offset]; pointY = flatCoordinates[offset + 1]; @@ -28,29 +28,29 @@ _ol_geom_flat_interpolate_.lineString = function(flatCoordinates, offset, end, s pointY = (1 - fraction) * flatCoordinates[offset + 1] + fraction * flatCoordinates[offset + stride + 1]; } else if (n !== 0) { - var x1 = flatCoordinates[offset]; - var y1 = flatCoordinates[offset + 1]; - var length = 0; - var cumulativeLengths = [0]; - var i; + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; + let length = 0; + const cumulativeLengths = [0]; + let i; for (i = offset + stride; i < end; i += stride) { - var x2 = flatCoordinates[i]; - var y2 = flatCoordinates[i + 1]; + const x2 = flatCoordinates[i]; + const y2 = flatCoordinates[i + 1]; length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); cumulativeLengths.push(length); x1 = x2; y1 = y2; } - var target = fraction * length; - var index = binarySearch(cumulativeLengths, target); + const target = fraction * length; + const index = binarySearch(cumulativeLengths, target); if (index < 0) { - var t = (target - cumulativeLengths[-index - 2]) / + const t = (target - cumulativeLengths[-index - 2]) / (cumulativeLengths[-index - 1] - cumulativeLengths[-index - 2]); - var o = offset + (-index - 2) * stride; + const o = offset + (-index - 2) * stride; pointX = lerp( - flatCoordinates[o], flatCoordinates[o + stride], t); + flatCoordinates[o], flatCoordinates[o + stride], t); pointY = lerp( - flatCoordinates[o + 1], flatCoordinates[o + stride + 1], t); + flatCoordinates[o + 1], flatCoordinates[o + stride + 1], t); } else { pointX = flatCoordinates[offset + index * stride]; pointY = flatCoordinates[offset + index * stride + 1]; @@ -79,7 +79,7 @@ _ol_geom_flat_interpolate_.lineStringCoordinateAtM = function(flatCoordinates, o if (end == offset) { return null; } - var coordinate; + let coordinate; if (m < flatCoordinates[offset + stride - 1]) { if (extrapolate) { coordinate = flatCoordinates.slice(offset, offset + stride); @@ -101,27 +101,27 @@ _ol_geom_flat_interpolate_.lineStringCoordinateAtM = function(flatCoordinates, o if (m == flatCoordinates[offset + stride - 1]) { return flatCoordinates.slice(offset, offset + stride); } - var lo = offset / stride; - var hi = end / stride; + let lo = offset / stride; + let hi = end / stride; while (lo < hi) { - var mid = (lo + hi) >> 1; + const mid = (lo + hi) >> 1; if (m < flatCoordinates[(mid + 1) * stride - 1]) { hi = mid; } else { lo = mid + 1; } } - var m0 = flatCoordinates[lo * stride - 1]; + const m0 = flatCoordinates[lo * stride - 1]; if (m == m0) { return flatCoordinates.slice((lo - 1) * stride, (lo - 1) * stride + stride); } - var m1 = flatCoordinates[(lo + 1) * stride - 1]; - var t = (m - m0) / (m1 - m0); + const m1 = flatCoordinates[(lo + 1) * stride - 1]; + const t = (m - m0) / (m1 - m0); coordinate = []; - var i; + let i; for (i = 0; i < stride - 1; ++i) { coordinate.push(lerp(flatCoordinates[(lo - 1) * stride + i], - flatCoordinates[lo * stride + i], t)); + flatCoordinates[lo * stride + i], t)); } coordinate.push(m); return coordinate; @@ -139,12 +139,12 @@ _ol_geom_flat_interpolate_.lineStringCoordinateAtM = function(flatCoordinates, o * @return {ol.Coordinate} Coordinate. */ _ol_geom_flat_interpolate_.lineStringsCoordinateAtM = function( - flatCoordinates, offset, ends, stride, m, extrapolate, interpolate) { + flatCoordinates, offset, ends, stride, m, extrapolate, interpolate) { if (interpolate) { return _ol_geom_flat_interpolate_.lineStringCoordinateAtM( - flatCoordinates, offset, ends[ends.length - 1], stride, m, extrapolate); + flatCoordinates, offset, ends[ends.length - 1], stride, m, extrapolate); } - var coordinate; + let coordinate; if (m < flatCoordinates[stride - 1]) { if (extrapolate) { coordinate = flatCoordinates.slice(0, stride); @@ -163,9 +163,9 @@ _ol_geom_flat_interpolate_.lineStringsCoordinateAtM = function( return null; } } - var i, ii; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; + const end = ends[i]; if (offset == end) { continue; } @@ -173,7 +173,7 @@ _ol_geom_flat_interpolate_.lineStringsCoordinateAtM = function( return null; } else if (m <= flatCoordinates[end - 1]) { return _ol_geom_flat_interpolate_.lineStringCoordinateAtM( - flatCoordinates, offset, end, stride, m, false); + flatCoordinates, offset, end, stride, m, false); } offset = end; } diff --git a/src/ol/geom/flat/intersectsextent.js b/src/ol/geom/flat/intersectsextent.js index cdc209f6dd..b632820fdf 100644 --- a/src/ol/geom/flat/intersectsextent.js +++ b/src/ol/geom/flat/intersectsextent.js @@ -4,7 +4,7 @@ import {containsExtent, createEmpty, extendFlatCoordinates, intersects, intersectsSegment} from '../../extent.js'; import _ol_geom_flat_contains_ from '../flat/contains.js'; import _ol_geom_flat_segments_ from '../flat/segments.js'; -var _ol_geom_flat_intersectsextent_ = {}; +const _ol_geom_flat_intersectsextent_ = {}; /** @@ -16,8 +16,8 @@ var _ol_geom_flat_intersectsextent_ = {}; * @return {boolean} True if the geometry and the extent intersect. */ _ol_geom_flat_intersectsextent_.lineString = function(flatCoordinates, offset, end, stride, extent) { - var coordinatesExtent = extendFlatCoordinates( - createEmpty(), flatCoordinates, offset, end, stride); + const coordinatesExtent = extendFlatCoordinates( + createEmpty(), flatCoordinates, offset, end, stride); if (!intersects(extent, coordinatesExtent)) { return false; } @@ -33,15 +33,15 @@ _ol_geom_flat_intersectsextent_.lineString = function(flatCoordinates, offset, e return true; } return _ol_geom_flat_segments_.forEach(flatCoordinates, offset, end, stride, - /** + /** * @param {ol.Coordinate} point1 Start point. * @param {ol.Coordinate} point2 End point. * @return {boolean} `true` if the segment and the extent intersect, * `false` otherwise. */ - function(point1, point2) { - return intersectsSegment(extent, point1, point2); - }); + function(point1, point2) { + return intersectsSegment(extent, point1, point2); + }); }; @@ -54,10 +54,10 @@ _ol_geom_flat_intersectsextent_.lineString = function(flatCoordinates, offset, e * @return {boolean} True if the geometry and the extent intersect. */ _ol_geom_flat_intersectsextent_.lineStrings = function(flatCoordinates, offset, ends, stride, extent) { - var i, ii; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { if (_ol_geom_flat_intersectsextent_.lineString( - flatCoordinates, offset, ends[i], stride, extent)) { + flatCoordinates, offset, ends[i], stride, extent)) { return true; } offset = ends[i]; @@ -76,23 +76,23 @@ _ol_geom_flat_intersectsextent_.lineStrings = function(flatCoordinates, offset, */ _ol_geom_flat_intersectsextent_.linearRing = function(flatCoordinates, offset, end, stride, extent) { if (_ol_geom_flat_intersectsextent_.lineString( - flatCoordinates, offset, end, stride, extent)) { + flatCoordinates, offset, end, stride, extent)) { return true; } if (_ol_geom_flat_contains_.linearRingContainsXY( - flatCoordinates, offset, end, stride, extent[0], extent[1])) { + flatCoordinates, offset, end, stride, extent[0], extent[1])) { return true; } if (_ol_geom_flat_contains_.linearRingContainsXY( - flatCoordinates, offset, end, stride, extent[0], extent[3])) { + flatCoordinates, offset, end, stride, extent[0], extent[3])) { return true; } if (_ol_geom_flat_contains_.linearRingContainsXY( - flatCoordinates, offset, end, stride, extent[2], extent[1])) { + flatCoordinates, offset, end, stride, extent[2], extent[1])) { return true; } if (_ol_geom_flat_contains_.linearRingContainsXY( - flatCoordinates, offset, end, stride, extent[2], extent[3])) { + flatCoordinates, offset, end, stride, extent[2], extent[3])) { return true; } return false; @@ -109,16 +109,16 @@ _ol_geom_flat_intersectsextent_.linearRing = function(flatCoordinates, offset, e */ _ol_geom_flat_intersectsextent_.linearRings = function(flatCoordinates, offset, ends, stride, extent) { if (!_ol_geom_flat_intersectsextent_.linearRing( - flatCoordinates, offset, ends[0], stride, extent)) { + flatCoordinates, offset, ends[0], stride, extent)) { return false; } if (ends.length === 1) { return true; } - var i, ii; + let i, ii; for (i = 1, ii = ends.length; i < ii; ++i) { if (_ol_geom_flat_contains_.linearRingContainsExtent( - flatCoordinates, ends[i - 1], ends[i], stride, extent)) { + flatCoordinates, ends[i - 1], ends[i], stride, extent)) { return false; } } @@ -135,11 +135,11 @@ _ol_geom_flat_intersectsextent_.linearRings = function(flatCoordinates, offset, * @return {boolean} True if the geometry and the extent intersect. */ _ol_geom_flat_intersectsextent_.linearRingss = function(flatCoordinates, offset, endss, stride, extent) { - var i, ii; + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; + const ends = endss[i]; if (_ol_geom_flat_intersectsextent_.linearRings( - flatCoordinates, offset, ends, stride, extent)) { + flatCoordinates, offset, ends, stride, extent)) { return true; } offset = ends[ends.length - 1]; diff --git a/src/ol/geom/flat/length.js b/src/ol/geom/flat/length.js index fff03e7933..1dde4b171a 100644 --- a/src/ol/geom/flat/length.js +++ b/src/ol/geom/flat/length.js @@ -1,7 +1,7 @@ /** * @module ol/geom/flat/length */ -var _ol_geom_flat_length_ = {}; +const _ol_geom_flat_length_ = {}; /** @@ -12,13 +12,13 @@ var _ol_geom_flat_length_ = {}; * @return {number} Length. */ _ol_geom_flat_length_.lineString = function(flatCoordinates, offset, end, stride) { - var x1 = flatCoordinates[offset]; - var y1 = flatCoordinates[offset + 1]; - var length = 0; - var i; + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; + let length = 0; + let i; for (i = offset + stride; i < end; i += stride) { - var x2 = flatCoordinates[i]; - var y2 = flatCoordinates[i + 1]; + const x2 = flatCoordinates[i]; + const y2 = flatCoordinates[i + 1]; length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); x1 = x2; y1 = y2; @@ -35,10 +35,10 @@ _ol_geom_flat_length_.lineString = function(flatCoordinates, offset, end, stride * @return {number} Perimeter. */ _ol_geom_flat_length_.linearRing = function(flatCoordinates, offset, end, stride) { - var perimeter = + let perimeter = _ol_geom_flat_length_.lineString(flatCoordinates, offset, end, stride); - var dx = flatCoordinates[end - stride] - flatCoordinates[offset]; - var dy = flatCoordinates[end - stride + 1] - flatCoordinates[offset + 1]; + const dx = flatCoordinates[end - stride] - flatCoordinates[offset]; + const dy = flatCoordinates[end - stride + 1] - flatCoordinates[offset + 1]; perimeter += Math.sqrt(dx * dx + dy * dy); return perimeter; }; diff --git a/src/ol/geom/flat/orient.js b/src/ol/geom/flat/orient.js index 83591e14ac..0a4e8b88c4 100644 --- a/src/ol/geom/flat/orient.js +++ b/src/ol/geom/flat/orient.js @@ -2,7 +2,7 @@ * @module ol/geom/flat/orient */ import _ol_geom_flat_reverse_ from '../flat/reverse.js'; -var _ol_geom_flat_orient_ = {}; +const _ol_geom_flat_orient_ = {}; /** @@ -15,12 +15,12 @@ var _ol_geom_flat_orient_ = {}; _ol_geom_flat_orient_.linearRingIsClockwise = function(flatCoordinates, offset, end, stride) { // http://tinyurl.com/clockwise-method // https://github.com/OSGeo/gdal/blob/trunk/gdal/ogr/ogrlinearring.cpp - var edge = 0; - var x1 = flatCoordinates[end - stride]; - var y1 = flatCoordinates[end - stride + 1]; + let edge = 0; + let x1 = flatCoordinates[end - stride]; + let y1 = flatCoordinates[end - stride + 1]; for (; offset < end; offset += stride) { - var x2 = flatCoordinates[offset]; - var y2 = flatCoordinates[offset + 1]; + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; edge += (x2 - x1) * (y2 + y1); x1 = x2; y1 = y2; @@ -43,12 +43,12 @@ _ol_geom_flat_orient_.linearRingIsClockwise = function(flatCoordinates, offset, * @return {boolean} Rings are correctly oriented. */ _ol_geom_flat_orient_.linearRingsAreOriented = function(flatCoordinates, offset, ends, stride, opt_right) { - var right = opt_right !== undefined ? opt_right : false; - var i, ii; + const right = opt_right !== undefined ? opt_right : false; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; - var isClockwise = _ol_geom_flat_orient_.linearRingIsClockwise( - flatCoordinates, offset, end, stride); + const end = ends[i]; + const isClockwise = _ol_geom_flat_orient_.linearRingIsClockwise( + flatCoordinates, offset, end, stride); if (i === 0) { if ((right && isClockwise) || (!right && !isClockwise)) { return false; @@ -78,10 +78,10 @@ _ol_geom_flat_orient_.linearRingsAreOriented = function(flatCoordinates, offset, * @return {boolean} Rings are correctly oriented. */ _ol_geom_flat_orient_.linearRingssAreOriented = function(flatCoordinates, offset, endss, stride, opt_right) { - var i, ii; + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { if (!_ol_geom_flat_orient_.linearRingsAreOriented( - flatCoordinates, offset, endss[i], stride, opt_right)) { + flatCoordinates, offset, endss[i], stride, opt_right)) { return false; } } @@ -103,13 +103,13 @@ _ol_geom_flat_orient_.linearRingssAreOriented = function(flatCoordinates, offset * @return {number} End. */ _ol_geom_flat_orient_.orientLinearRings = function(flatCoordinates, offset, ends, stride, opt_right) { - var right = opt_right !== undefined ? opt_right : false; - var i, ii; + const right = opt_right !== undefined ? opt_right : false; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; - var isClockwise = _ol_geom_flat_orient_.linearRingIsClockwise( - flatCoordinates, offset, end, stride); - var reverse = i === 0 ? + const end = ends[i]; + const isClockwise = _ol_geom_flat_orient_.linearRingIsClockwise( + flatCoordinates, offset, end, stride); + const reverse = i === 0 ? (right && isClockwise) || (!right && !isClockwise) : (right && !isClockwise) || (!right && isClockwise); if (reverse) { @@ -135,10 +135,10 @@ _ol_geom_flat_orient_.orientLinearRings = function(flatCoordinates, offset, ends * @return {number} End. */ _ol_geom_flat_orient_.orientLinearRingss = function(flatCoordinates, offset, endss, stride, opt_right) { - var i, ii; + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { offset = _ol_geom_flat_orient_.orientLinearRings( - flatCoordinates, offset, endss[i], stride, opt_right); + flatCoordinates, offset, endss[i], stride, opt_right); } return offset; }; diff --git a/src/ol/geom/flat/reverse.js b/src/ol/geom/flat/reverse.js index 9cec4840a0..e04d450d3f 100644 --- a/src/ol/geom/flat/reverse.js +++ b/src/ol/geom/flat/reverse.js @@ -1,7 +1,7 @@ /** * @module ol/geom/flat/reverse */ -var _ol_geom_flat_reverse_ = {}; +const _ol_geom_flat_reverse_ = {}; /** @@ -12,9 +12,8 @@ var _ol_geom_flat_reverse_ = {}; */ _ol_geom_flat_reverse_.coordinates = function(flatCoordinates, offset, end, stride) { while (offset < end - stride) { - var i; - for (i = 0; i < stride; ++i) { - var tmp = flatCoordinates[offset + i]; + for (let i = 0; i < stride; ++i) { + const tmp = flatCoordinates[offset + i]; flatCoordinates[offset + i] = flatCoordinates[end - stride + i]; flatCoordinates[end - stride + i] = tmp; } diff --git a/src/ol/geom/flat/segments.js b/src/ol/geom/flat/segments.js index cc9bd61007..d97150bee0 100644 --- a/src/ol/geom/flat/segments.js +++ b/src/ol/geom/flat/segments.js @@ -1,7 +1,7 @@ /** * @module ol/geom/flat/segments */ -var _ol_geom_flat_segments_ = {}; +const _ol_geom_flat_segments_ = {}; /** @@ -20,9 +20,9 @@ var _ol_geom_flat_segments_ = {}; * @template T,S */ _ol_geom_flat_segments_.forEach = function(flatCoordinates, offset, end, stride, callback, opt_this) { - var point1 = [flatCoordinates[offset], flatCoordinates[offset + 1]]; - var point2 = []; - var ret; + const point1 = [flatCoordinates[offset], flatCoordinates[offset + 1]]; + const point2 = []; + let ret; for (; (offset + stride) < end; offset += stride) { point2[0] = flatCoordinates[offset + stride]; point2[1] = flatCoordinates[offset + stride + 1]; diff --git a/src/ol/geom/flat/simplify.js b/src/ol/geom/flat/simplify.js index f827f81bc1..972a5f1fcd 100644 --- a/src/ol/geom/flat/simplify.js +++ b/src/ol/geom/flat/simplify.js @@ -28,7 +28,7 @@ // POSSIBILITY OF SUCH DAMAGE. import {squaredSegmentDistance, squaredDistance} from '../../math.js'; -var _ol_geom_flat_simplify_ = {}; +const _ol_geom_flat_simplify_ = {}; /** @@ -43,20 +43,20 @@ var _ol_geom_flat_simplify_ = {}; * @return {Array.} Simplified line string. */ _ol_geom_flat_simplify_.lineString = function(flatCoordinates, offset, end, - stride, squaredTolerance, highQuality, opt_simplifiedFlatCoordinates) { - var simplifiedFlatCoordinates = opt_simplifiedFlatCoordinates !== undefined ? + stride, squaredTolerance, highQuality, opt_simplifiedFlatCoordinates) { + const simplifiedFlatCoordinates = opt_simplifiedFlatCoordinates !== undefined ? opt_simplifiedFlatCoordinates : []; if (!highQuality) { end = _ol_geom_flat_simplify_.radialDistance(flatCoordinates, offset, end, - stride, squaredTolerance, - simplifiedFlatCoordinates, 0); + stride, squaredTolerance, + simplifiedFlatCoordinates, 0); flatCoordinates = simplifiedFlatCoordinates; offset = 0; stride = 2; } simplifiedFlatCoordinates.length = _ol_geom_flat_simplify_.douglasPeucker( - flatCoordinates, offset, end, stride, squaredTolerance, - simplifiedFlatCoordinates, 0); + flatCoordinates, offset, end, stride, squaredTolerance, + simplifiedFlatCoordinates, 0); return simplifiedFlatCoordinates; }; @@ -73,8 +73,8 @@ _ol_geom_flat_simplify_.lineString = function(flatCoordinates, offset, end, * @return {number} Simplified offset. */ _ol_geom_flat_simplify_.douglasPeucker = function(flatCoordinates, offset, end, - stride, squaredTolerance, simplifiedFlatCoordinates, simplifiedOffset) { - var n = (end - offset) / stride; + stride, squaredTolerance, simplifiedFlatCoordinates, simplifiedOffset) { + const n = (end - offset) / stride; if (n < 3) { for (; offset < end; offset += stride) { simplifiedFlatCoordinates[simplifiedOffset++] = @@ -85,26 +85,26 @@ _ol_geom_flat_simplify_.douglasPeucker = function(flatCoordinates, offset, end, return simplifiedOffset; } /** @type {Array.} */ - var markers = new Array(n); + const markers = new Array(n); markers[0] = 1; markers[n - 1] = 1; /** @type {Array.} */ - var stack = [offset, end - stride]; - var index = 0; - var i; + const stack = [offset, end - stride]; + let index = 0; + let i; while (stack.length > 0) { - var last = stack.pop(); - var first = stack.pop(); - var maxSquaredDistance = 0; - var x1 = flatCoordinates[first]; - var y1 = flatCoordinates[first + 1]; - var x2 = flatCoordinates[last]; - var y2 = flatCoordinates[last + 1]; + const last = stack.pop(); + const first = stack.pop(); + let maxSquaredDistance = 0; + const x1 = flatCoordinates[first]; + const y1 = flatCoordinates[first + 1]; + const x2 = flatCoordinates[last]; + const y2 = flatCoordinates[last + 1]; for (i = first + stride; i < last; i += stride) { - var x = flatCoordinates[i]; - var y = flatCoordinates[i + 1]; - var squaredDistance = squaredSegmentDistance( - x, y, x1, y1, x2, y2); + const x = flatCoordinates[i]; + const y = flatCoordinates[i + 1]; + const squaredDistance = squaredSegmentDistance( + x, y, x1, y1, x2, y2); if (squaredDistance > maxSquaredDistance) { index = i; maxSquaredDistance = squaredDistance; @@ -145,14 +145,14 @@ _ol_geom_flat_simplify_.douglasPeucker = function(flatCoordinates, offset, end, * @return {number} Simplified offset. */ _ol_geom_flat_simplify_.douglasPeuckers = function(flatCoordinates, offset, - ends, stride, squaredTolerance, simplifiedFlatCoordinates, - simplifiedOffset, simplifiedEnds) { - var i, ii; + ends, stride, squaredTolerance, simplifiedFlatCoordinates, + simplifiedOffset, simplifiedEnds) { + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; + const end = ends[i]; simplifiedOffset = _ol_geom_flat_simplify_.douglasPeucker( - flatCoordinates, offset, end, stride, squaredTolerance, - simplifiedFlatCoordinates, simplifiedOffset); + flatCoordinates, offset, end, stride, squaredTolerance, + simplifiedFlatCoordinates, simplifiedOffset); simplifiedEnds.push(simplifiedOffset); offset = end; } @@ -173,15 +173,15 @@ _ol_geom_flat_simplify_.douglasPeuckers = function(flatCoordinates, offset, * @return {number} Simplified offset. */ _ol_geom_flat_simplify_.douglasPeuckerss = function( - flatCoordinates, offset, endss, stride, squaredTolerance, - simplifiedFlatCoordinates, simplifiedOffset, simplifiedEndss) { - var i, ii; + flatCoordinates, offset, endss, stride, squaredTolerance, + simplifiedFlatCoordinates, simplifiedOffset, simplifiedEndss) { + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; - var simplifiedEnds = []; + const ends = endss[i]; + const simplifiedEnds = []; simplifiedOffset = _ol_geom_flat_simplify_.douglasPeuckers( - flatCoordinates, offset, ends, stride, squaredTolerance, - simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds); + flatCoordinates, offset, ends, stride, squaredTolerance, + simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds); simplifiedEndss.push(simplifiedEnds); offset = ends[ends.length - 1]; } @@ -201,7 +201,7 @@ _ol_geom_flat_simplify_.douglasPeuckerss = function( * @return {number} Simplified offset. */ _ol_geom_flat_simplify_.radialDistance = function(flatCoordinates, offset, end, - stride, squaredTolerance, simplifiedFlatCoordinates, simplifiedOffset) { + stride, squaredTolerance, simplifiedFlatCoordinates, simplifiedOffset) { if (end <= offset + stride) { // zero or one point, no simplification possible, so copy and return for (; offset < end; offset += stride) { @@ -211,13 +211,13 @@ _ol_geom_flat_simplify_.radialDistance = function(flatCoordinates, offset, end, } return simplifiedOffset; } - var x1 = flatCoordinates[offset]; - var y1 = flatCoordinates[offset + 1]; + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; // copy first point simplifiedFlatCoordinates[simplifiedOffset++] = x1; simplifiedFlatCoordinates[simplifiedOffset++] = y1; - var x2 = x1; - var y2 = y1; + let x2 = x1; + let y2 = y1; for (offset += stride; offset < end; offset += stride) { x2 = flatCoordinates[offset]; y2 = flatCoordinates[offset + 1]; @@ -268,21 +268,21 @@ _ol_geom_flat_simplify_.snap = function(value, tolerance) { * @return {number} Simplified offset. */ _ol_geom_flat_simplify_.quantize = function(flatCoordinates, offset, end, stride, - tolerance, simplifiedFlatCoordinates, simplifiedOffset) { + tolerance, simplifiedFlatCoordinates, simplifiedOffset) { // do nothing if the line is empty if (offset == end) { return simplifiedOffset; } // snap the first coordinate (P1) - var x1 = _ol_geom_flat_simplify_.snap(flatCoordinates[offset], tolerance); - var y1 = _ol_geom_flat_simplify_.snap(flatCoordinates[offset + 1], tolerance); + let x1 = _ol_geom_flat_simplify_.snap(flatCoordinates[offset], tolerance); + let y1 = _ol_geom_flat_simplify_.snap(flatCoordinates[offset + 1], tolerance); offset += stride; // add the first coordinate to the output simplifiedFlatCoordinates[simplifiedOffset++] = x1; simplifiedFlatCoordinates[simplifiedOffset++] = y1; // find the next coordinate that does not snap to the same value as the first // coordinate (P2) - var x2, y2; + let x2, y2; do { x2 = _ol_geom_flat_simplify_.snap(flatCoordinates[offset], tolerance); y2 = _ol_geom_flat_simplify_.snap(flatCoordinates[offset + 1], tolerance); @@ -298,21 +298,20 @@ _ol_geom_flat_simplify_.quantize = function(flatCoordinates, offset, end, stride } } while (x2 == x1 && y2 == y1); while (offset < end) { - var x3, y3; // snap the next coordinate (P3) - x3 = _ol_geom_flat_simplify_.snap(flatCoordinates[offset], tolerance); - y3 = _ol_geom_flat_simplify_.snap(flatCoordinates[offset + 1], tolerance); + const x3 = _ol_geom_flat_simplify_.snap(flatCoordinates[offset], tolerance); + const y3 = _ol_geom_flat_simplify_.snap(flatCoordinates[offset + 1], tolerance); offset += stride; // skip P3 if it is equal to P2 if (x3 == x2 && y3 == y2) { continue; } // calculate the delta between P1 and P2 - var dx1 = x2 - x1; - var dy1 = y2 - y1; + const dx1 = x2 - x1; + const dy1 = y2 - y1; // calculate the delta between P3 and P1 - var dx2 = x3 - x1; - var dy2 = y3 - y1; + const dx2 = x3 - x1; + const dy2 = y3 - y1; // if P1, P2, and P3 are colinear and P3 is further from P1 than P2 is from // P1 in the same direction then P2 is on the straight line between P1 and // P3 @@ -354,16 +353,16 @@ _ol_geom_flat_simplify_.quantize = function(flatCoordinates, offset, end, stride * @return {number} Simplified offset. */ _ol_geom_flat_simplify_.quantizes = function( - flatCoordinates, offset, ends, stride, - tolerance, - simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds) { - var i, ii; + flatCoordinates, offset, ends, stride, + tolerance, + simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds) { + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; + const end = ends[i]; simplifiedOffset = _ol_geom_flat_simplify_.quantize( - flatCoordinates, offset, end, stride, - tolerance, - simplifiedFlatCoordinates, simplifiedOffset); + flatCoordinates, offset, end, stride, + tolerance, + simplifiedFlatCoordinates, simplifiedOffset); simplifiedEnds.push(simplifiedOffset); offset = end; } @@ -384,17 +383,17 @@ _ol_geom_flat_simplify_.quantizes = function( * @return {number} Simplified offset. */ _ol_geom_flat_simplify_.quantizess = function( - flatCoordinates, offset, endss, stride, - tolerance, - simplifiedFlatCoordinates, simplifiedOffset, simplifiedEndss) { - var i, ii; + flatCoordinates, offset, endss, stride, + tolerance, + simplifiedFlatCoordinates, simplifiedOffset, simplifiedEndss) { + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; - var simplifiedEnds = []; + const ends = endss[i]; + const simplifiedEnds = []; simplifiedOffset = _ol_geom_flat_simplify_.quantizes( - flatCoordinates, offset, ends, stride, - tolerance, - simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds); + flatCoordinates, offset, ends, stride, + tolerance, + simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds); simplifiedEndss.push(simplifiedEnds); offset = ends[ends.length - 1]; } diff --git a/src/ol/geom/flat/straightchunk.js b/src/ol/geom/flat/straightchunk.js index d985bf3bd1..16c77598bc 100644 --- a/src/ol/geom/flat/straightchunk.js +++ b/src/ol/geom/flat/straightchunk.js @@ -1,7 +1,7 @@ /** * @module ol/geom/flat/straightchunk */ -var _ol_geom_flat_straightchunk_ = {}; +const _ol_geom_flat_straightchunk_ = {}; /** @@ -14,15 +14,15 @@ var _ol_geom_flat_straightchunk_ = {}; * given `flatCoordinates`. */ _ol_geom_flat_straightchunk_.lineString = function(maxAngle, flatCoordinates, offset, end, stride) { - var chunkStart = offset; - var chunkEnd = offset; - var chunkM = 0; - var m = 0; - var start = offset; - var acos, i, m12, m23, x1, y1, x12, y12, x23, y23; + let chunkStart = offset; + let chunkEnd = offset; + let chunkM = 0; + let m = 0; + let start = offset; + let acos, i, m12, m23, x1, y1, x12, y12, x23, y23; for (i = offset; i < end; i += stride) { - var x2 = flatCoordinates[i]; - var y2 = flatCoordinates[i + 1]; + const x2 = flatCoordinates[i]; + const y2 = flatCoordinates[i + 1]; if (x1 !== undefined) { x23 = x2 - x1; y23 = y2 - y1; diff --git a/src/ol/geom/flat/textpath.js b/src/ol/geom/flat/textpath.js index 1b02a58901..d4bb434f9a 100644 --- a/src/ol/geom/flat/textpath.js +++ b/src/ol/geom/flat/textpath.js @@ -2,7 +2,7 @@ * @module ol/geom/flat/textpath */ import {lerp} from '../../math.js'; -var _ol_geom_flat_textpath_ = {}; +const _ol_geom_flat_textpath_ = {}; /** @@ -19,32 +19,32 @@ var _ol_geom_flat_textpath_ = {}; * exceeded. Entries of the array are x, y, anchorX, angle, chunk. */ _ol_geom_flat_textpath_.lineString = function( - flatCoordinates, offset, end, stride, text, measure, startM, maxAngle) { - var result = []; + flatCoordinates, offset, end, stride, text, measure, startM, maxAngle) { + const result = []; // Keep text upright - var reverse = flatCoordinates[offset] > flatCoordinates[end - stride]; + const reverse = flatCoordinates[offset] > flatCoordinates[end - stride]; - var numChars = text.length; + const numChars = text.length; - var x1 = flatCoordinates[offset]; - var y1 = flatCoordinates[offset + 1]; + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; offset += stride; - var x2 = flatCoordinates[offset]; - var y2 = flatCoordinates[offset + 1]; - var segmentM = 0; - var segmentLength = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); + let x2 = flatCoordinates[offset]; + let y2 = flatCoordinates[offset + 1]; + let segmentM = 0; + let segmentLength = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); - var chunk = ''; - var chunkLength = 0; - var data, index, previousAngle; - for (var i = 0; i < numChars; ++i) { + let chunk = ''; + let chunkLength = 0; + let data, index, previousAngle; + for (let i = 0; i < numChars; ++i) { index = reverse ? numChars - i - 1 : i; - var char = text.charAt(index); + const char = text.charAt(index); chunk = reverse ? char + chunk : chunk + char; - var charLength = measure(chunk) - chunkLength; + const charLength = measure(chunk) - chunkLength; chunkLength += charLength; - var charM = startM + charLength / 2; + const charM = startM + charLength / 2; while (offset < end - stride && segmentM + segmentLength < charM) { x1 = x2; y1 = y2; @@ -54,21 +54,21 @@ _ol_geom_flat_textpath_.lineString = function( segmentM += segmentLength; segmentLength = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); } - var segmentPos = charM - segmentM; - var angle = Math.atan2(y2 - y1, x2 - x1); + const segmentPos = charM - segmentM; + let angle = Math.atan2(y2 - y1, x2 - x1); if (reverse) { angle += angle > 0 ? -Math.PI : Math.PI; } if (previousAngle !== undefined) { - var delta = angle - previousAngle; + let delta = angle - previousAngle; delta += (delta > Math.PI) ? -2 * Math.PI : (delta < -Math.PI) ? 2 * Math.PI : 0; if (Math.abs(delta) > maxAngle) { return null; } } - var interpolate = segmentPos / segmentLength; - var x = lerp(x1, x2, interpolate); - var y = lerp(y1, y2, interpolate); + const interpolate = segmentPos / segmentLength; + const x = lerp(x1, x2, interpolate); + const y = lerp(y1, y2, interpolate); if (previousAngle == angle) { if (reverse) { data[0] = x; diff --git a/src/ol/geom/flat/topology.js b/src/ol/geom/flat/topology.js index 912e3dcd0a..2bd605b88e 100644 --- a/src/ol/geom/flat/topology.js +++ b/src/ol/geom/flat/topology.js @@ -2,7 +2,7 @@ * @module ol/geom/flat/topology */ import _ol_geom_flat_area_ from '../flat/area.js'; -var _ol_geom_flat_topology_ = {}; +const _ol_geom_flat_topology_ = {}; /** * Check if the linestring is a boundary. @@ -13,7 +13,7 @@ var _ol_geom_flat_topology_ = {}; * @return {boolean} The linestring is a boundary. */ _ol_geom_flat_topology_.lineStringIsClosed = function(flatCoordinates, offset, end, stride) { - var lastCoord = end - stride; + const lastCoord = end - stride; if (flatCoordinates[offset] === flatCoordinates[lastCoord] && flatCoordinates[offset + 1] === flatCoordinates[lastCoord + 1] && (end - offset) / stride > 3) { return !!_ol_geom_flat_area_.linearRing(flatCoordinates, offset, end, stride); diff --git a/src/ol/geom/flat/transform.js b/src/ol/geom/flat/transform.js index 1d23f33747..f6896ba463 100644 --- a/src/ol/geom/flat/transform.js +++ b/src/ol/geom/flat/transform.js @@ -1,7 +1,7 @@ /** * @module ol/geom/flat/transform */ -var _ol_geom_flat_transform_ = {}; +const _ol_geom_flat_transform_ = {}; /** @@ -14,12 +14,12 @@ var _ol_geom_flat_transform_ = {}; * @return {Array.} Transformed coordinates. */ _ol_geom_flat_transform_.transform2D = function(flatCoordinates, offset, end, stride, transform, opt_dest) { - var dest = opt_dest ? opt_dest : []; - var i = 0; - var j; + const dest = opt_dest ? opt_dest : []; + let i = 0; + let j; for (j = offset; j < end; j += stride) { - var x = flatCoordinates[j]; - var y = flatCoordinates[j + 1]; + const x = flatCoordinates[j]; + const y = flatCoordinates[j + 1]; dest[i++] = transform[0] * x + transform[2] * y + transform[4]; dest[i++] = transform[1] * x + transform[3] * y + transform[5]; } @@ -41,18 +41,18 @@ _ol_geom_flat_transform_.transform2D = function(flatCoordinates, offset, end, st * @return {Array.} Transformed coordinates. */ _ol_geom_flat_transform_.rotate = function(flatCoordinates, offset, end, stride, angle, anchor, opt_dest) { - var dest = opt_dest ? opt_dest : []; - var cos = Math.cos(angle); - var sin = Math.sin(angle); - var anchorX = anchor[0]; - var anchorY = anchor[1]; - var i = 0; - for (var j = offset; j < end; j += stride) { - var deltaX = flatCoordinates[j] - anchorX; - var deltaY = flatCoordinates[j + 1] - anchorY; + const dest = opt_dest ? opt_dest : []; + const cos = Math.cos(angle); + const sin = Math.sin(angle); + const anchorX = anchor[0]; + const anchorY = anchor[1]; + let i = 0; + for (let j = offset; j < end; j += stride) { + const deltaX = flatCoordinates[j] - anchorX; + const deltaY = flatCoordinates[j + 1] - anchorY; dest[i++] = anchorX + deltaX * cos - deltaY * sin; dest[i++] = anchorY + deltaX * sin + deltaY * cos; - for (var k = j + 2; k < j + stride; ++k) { + for (let k = j + 2; k < j + stride; ++k) { dest[i++] = flatCoordinates[k]; } } @@ -76,16 +76,16 @@ _ol_geom_flat_transform_.rotate = function(flatCoordinates, offset, end, stride, * @return {Array.} Transformed coordinates. */ _ol_geom_flat_transform_.scale = function(flatCoordinates, offset, end, stride, sx, sy, anchor, opt_dest) { - var dest = opt_dest ? opt_dest : []; - var anchorX = anchor[0]; - var anchorY = anchor[1]; - var i = 0; - for (var j = offset; j < end; j += stride) { - var deltaX = flatCoordinates[j] - anchorX; - var deltaY = flatCoordinates[j + 1] - anchorY; + const dest = opt_dest ? opt_dest : []; + const anchorX = anchor[0]; + const anchorY = anchor[1]; + let i = 0; + for (let j = offset; j < end; j += stride) { + const deltaX = flatCoordinates[j] - anchorX; + const deltaY = flatCoordinates[j + 1] - anchorY; dest[i++] = anchorX + sx * deltaX; dest[i++] = anchorY + sy * deltaY; - for (var k = j + 2; k < j + stride; ++k) { + for (let k = j + 2; k < j + stride; ++k) { dest[i++] = flatCoordinates[k]; } } @@ -107,9 +107,9 @@ _ol_geom_flat_transform_.scale = function(flatCoordinates, offset, end, stride, * @return {Array.} Transformed coordinates. */ _ol_geom_flat_transform_.translate = function(flatCoordinates, offset, end, stride, deltaX, deltaY, opt_dest) { - var dest = opt_dest ? opt_dest : []; - var i = 0; - var j, k; + const dest = opt_dest ? opt_dest : []; + let i = 0; + let j, k; for (j = offset; j < end; j += stride) { dest[i++] = flatCoordinates[j] + deltaX; dest[i++] = flatCoordinates[j + 1] + deltaY; diff --git a/src/ol/has.js b/src/ol/has.js index 22d9166e49..86e4b2cf30 100644 --- a/src/ol/has.js +++ b/src/ol/has.js @@ -3,9 +3,9 @@ */ import {HAS_WEBGL} from './index.js'; -var _ol_has_ = {}; +const _ol_has_ = {}; -var ua = typeof navigator !== 'undefined' ? +const ua = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase() : ''; /** @@ -65,7 +65,7 @@ _ol_has_.CANVAS = ( return false; } try { - var context = document.createElement('CANVAS').getContext('2d'); + const context = document.createElement('CANVAS').getContext('2d'); if (!context) { return false; } else { diff --git a/src/ol/index.js b/src/ol/index.js index de21fd4916..05efbdbefd 100644 --- a/src/ol/index.js +++ b/src/ol/index.js @@ -10,7 +10,7 @@ import webgl from './webgl.js'; * @type {boolean} Include debuggable shader sources. Default is `true`. * This should be set to `false` for production builds. */ -export var DEBUG_WEBGL = true; +export const DEBUG_WEBGL = true; /** @@ -20,7 +20,7 @@ export var DEBUG_WEBGL = true; * @const * @type {number|undefined} */ -var WEBGL_MAX_TEXTURE_SIZE; // value is set below +let WEBGL_MAX_TEXTURE_SIZE; // value is set below /** @@ -29,7 +29,7 @@ var WEBGL_MAX_TEXTURE_SIZE; // value is set below * @const * @type {Array.} */ -var WEBGL_EXTENSIONS; // value is set below +let WEBGL_EXTENSIONS; // value is set below /** @@ -37,14 +37,14 @@ var WEBGL_EXTENSIONS; // value is set below * WebGL is available. * @type {boolean} */ -var HAS_WEBGL = false; +let HAS_WEBGL = false; if ('WebGLRenderingContext' in window) { try { - var canvas = /** @type {HTMLCanvasElement} */ + const canvas = /** @type {HTMLCanvasElement} */ (document.createElement('CANVAS')); - var gl = webgl.getContext(canvas, {failIfMajorPerformanceCaveat: true}); + const gl = webgl.getContext(canvas, {failIfMajorPerformanceCaveat: true}); if (gl) { HAS_WEBGL = true; WEBGL_MAX_TEXTURE_SIZE = /** @type {number} */ @@ -62,7 +62,7 @@ export {HAS_WEBGL, WEBGL_MAX_TEXTURE_SIZE, WEBGL_EXTENSIONS}; /** * @type {string} OpenLayers version. */ -export var VERSION = 'v4.6.4'; +export const VERSION = 'v4.6.4'; /** @@ -106,7 +106,7 @@ export function nullFunction() {} * @type {number} * @private */ -var uidCounter_ = 0; +let uidCounter_ = 0; /** * Gets a unique ID for an object. This mutates the object so that further calls diff --git a/src/ol/interaction.js b/src/ol/interaction.js index 6ecd3982b2..c328b078cb 100644 --- a/src/ol/interaction.js +++ b/src/ol/interaction.js @@ -39,19 +39,19 @@ import PinchZoom from './interaction/PinchZoom.js'; */ export function defaults(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; - var interactions = new Collection(); + const interactions = new Collection(); - var kinetic = new Kinetic(-0.005, 0.05, 100); + const kinetic = new Kinetic(-0.005, 0.05, 100); - var altShiftDragRotate = options.altShiftDragRotate !== undefined ? + const altShiftDragRotate = options.altShiftDragRotate !== undefined ? options.altShiftDragRotate : true; if (altShiftDragRotate) { interactions.push(new DragRotate()); } - var doubleClickZoom = options.doubleClickZoom !== undefined ? + const doubleClickZoom = options.doubleClickZoom !== undefined ? options.doubleClickZoom : true; if (doubleClickZoom) { interactions.push(new DoubleClickZoom({ @@ -60,20 +60,20 @@ export function defaults(opt_options) { })); } - var dragPan = options.dragPan !== undefined ? options.dragPan : true; + const dragPan = options.dragPan !== undefined ? options.dragPan : true; if (dragPan) { interactions.push(new DragPan({ kinetic: kinetic })); } - var pinchRotate = options.pinchRotate !== undefined ? options.pinchRotate : + const pinchRotate = options.pinchRotate !== undefined ? options.pinchRotate : true; if (pinchRotate) { interactions.push(new PinchRotate()); } - var pinchZoom = options.pinchZoom !== undefined ? options.pinchZoom : true; + const pinchZoom = options.pinchZoom !== undefined ? options.pinchZoom : true; if (pinchZoom) { interactions.push(new PinchZoom({ constrainResolution: options.constrainResolution, @@ -81,7 +81,7 @@ export function defaults(opt_options) { })); } - var keyboard = options.keyboard !== undefined ? options.keyboard : true; + const keyboard = options.keyboard !== undefined ? options.keyboard : true; if (keyboard) { interactions.push(new KeyboardPan()); interactions.push(new KeyboardZoom({ @@ -90,7 +90,7 @@ export function defaults(opt_options) { })); } - var mouseWheelZoom = options.mouseWheelZoom !== undefined ? + const mouseWheelZoom = options.mouseWheelZoom !== undefined ? options.mouseWheelZoom : true; if (mouseWheelZoom) { interactions.push(new MouseWheelZoom({ @@ -99,7 +99,7 @@ export function defaults(opt_options) { })); } - var shiftDragZoom = options.shiftDragZoom !== undefined ? + const shiftDragZoom = options.shiftDragZoom !== undefined ? options.shiftDragZoom : true; if (shiftDragZoom) { interactions.push(new DragZoom({ diff --git a/src/ol/interaction/DoubleClickZoom.js b/src/ol/interaction/DoubleClickZoom.js index df05e088fe..76c1179b46 100644 --- a/src/ol/interaction/DoubleClickZoom.js +++ b/src/ol/interaction/DoubleClickZoom.js @@ -14,9 +14,9 @@ import Interaction from '../interaction/Interaction.js'; * @param {olx.interaction.DoubleClickZoomOptions=} opt_options Options. * @api */ -var DoubleClickZoom = function(opt_options) { +const DoubleClickZoom = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @private @@ -48,15 +48,15 @@ inherits(DoubleClickZoom, Interaction); * @api */ DoubleClickZoom.handleEvent = function(mapBrowserEvent) { - var stopEvent = false; - var browserEvent = mapBrowserEvent.originalEvent; + let stopEvent = false; + const browserEvent = mapBrowserEvent.originalEvent; if (mapBrowserEvent.type == MapBrowserEventType.DBLCLICK) { - var map = mapBrowserEvent.map; - var anchor = mapBrowserEvent.coordinate; - var delta = browserEvent.shiftKey ? -this.delta_ : this.delta_; - var view = map.getView(); + const map = mapBrowserEvent.map; + const anchor = mapBrowserEvent.coordinate; + const delta = browserEvent.shiftKey ? -this.delta_ : this.delta_; + const view = map.getView(); Interaction.zoomByDelta( - view, delta, anchor, this.duration_); + view, delta, anchor, this.duration_); mapBrowserEvent.preventDefault(); stopEvent = true; } diff --git a/src/ol/interaction/DragAndDrop.js b/src/ol/interaction/DragAndDrop.js index a9a6d8f210..d381a590e9 100644 --- a/src/ol/interaction/DragAndDrop.js +++ b/src/ol/interaction/DragAndDrop.js @@ -21,9 +21,9 @@ import {get as getProjection} from '../proj.js'; * @param {olx.interaction.DragAndDropOptions=} opt_options Options. * @api */ -var DragAndDrop = function(opt_options) { +const DragAndDrop = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; Interaction.call(this, { handleEvent: DragAndDrop.handleEvent @@ -72,13 +72,13 @@ inherits(DragAndDrop, Interaction); * @private */ DragAndDrop.handleDrop_ = function(event) { - var files = event.dataTransfer.files; - var i, ii, file; + const files = event.dataTransfer.files; + let i, ii, file; for (i = 0, ii = files.length; i < ii; ++i) { file = files.item(i); - var reader = new FileReader(); + const reader = new FileReader(); reader.addEventListener(EventType.LOAD, - this.handleResult_.bind(this, file)); + this.handleResult_.bind(this, file)); reader.readAsText(file); } }; @@ -101,27 +101,27 @@ DragAndDrop.handleStop_ = function(event) { * @private */ DragAndDrop.prototype.handleResult_ = function(file, event) { - var result = event.target.result; - var map = this.getMap(); - var projection = this.projection_; + const result = event.target.result; + const map = this.getMap(); + let projection = this.projection_; if (!projection) { - var view = map.getView(); + const view = map.getView(); projection = view.getProjection(); } - var formatConstructors = this.formatConstructors_; - var features = []; - var i, ii; + const formatConstructors = this.formatConstructors_; + let features = []; + let i, ii; for (i = 0, ii = formatConstructors.length; i < ii; ++i) { /** * Avoid "cannot instantiate abstract class" error. * @type {Function} */ - var formatConstructor = formatConstructors[i]; + const formatConstructor = formatConstructors[i]; /** * @type {ol.format.Feature} */ - var format = new formatConstructor(); + const format = new formatConstructor(); features = this.tryReadFeatures_(format, result, { featureProjection: projection }); @@ -134,9 +134,9 @@ DragAndDrop.prototype.handleResult_ = function(file, event) { this.source_.addFeatures(features); } this.dispatchEvent( - new DragAndDrop.Event( - DragAndDrop.EventType_.ADD_FEATURES, file, - features, projection)); + new DragAndDrop.Event( + DragAndDrop.EventType_.ADD_FEATURES, file, + features, projection)); }; @@ -155,18 +155,18 @@ DragAndDrop.handleEvent = TRUE; * @private */ DragAndDrop.prototype.registerListeners_ = function() { - var map = this.getMap(); + const map = this.getMap(); if (map) { - var dropArea = this.target ? this.target : map.getViewport(); + const dropArea = this.target ? this.target : map.getViewport(); this.dropListenKeys_ = [ _ol_events_.listen(dropArea, EventType.DROP, - DragAndDrop.handleDrop_, this), + DragAndDrop.handleDrop_, this), _ol_events_.listen(dropArea, EventType.DRAGENTER, - DragAndDrop.handleStop_, this), + DragAndDrop.handleStop_, this), _ol_events_.listen(dropArea, EventType.DRAGOVER, - DragAndDrop.handleStop_, this), + DragAndDrop.handleStop_, this), _ol_events_.listen(dropArea, EventType.DROP, - DragAndDrop.handleStop_, this) + DragAndDrop.handleStop_, this) ]; } }; diff --git a/src/ol/interaction/DragBox.js b/src/ol/interaction/DragBox.js index 2e2b569bfd..999ba8378b 100644 --- a/src/ol/interaction/DragBox.js +++ b/src/ol/interaction/DragBox.js @@ -25,7 +25,7 @@ import _ol_render_Box_ from '../render/Box.js'; * @param {olx.interaction.DragBoxOptions=} opt_options Options. * @api */ -var DragBox = function(opt_options) { +const DragBox = function(opt_options) { PointerInteraction.call(this, { handleDownEvent: DragBox.handleDownEvent_, @@ -33,7 +33,7 @@ var DragBox = function(opt_options) { handleUpEvent: DragBox.handleUpEvent_ }); - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @type {ol.render.Box} @@ -82,8 +82,8 @@ inherits(DragBox, PointerInteraction); * @this {ol.interaction.DragBox} */ DragBox.defaultBoxEndCondition = function(mapBrowserEvent, startPixel, endPixel) { - var width = endPixel[0] - startPixel[0]; - var height = endPixel[1] - startPixel[1]; + const width = endPixel[0] - startPixel[0]; + const height = endPixel[1] - startPixel[1]; return width * width + height * height >= this.minArea_; }; @@ -101,7 +101,7 @@ DragBox.handleDragEvent_ = function(mapBrowserEvent) { this.box_.setPixels(this.startPixel_, mapBrowserEvent.pixel); this.dispatchEvent(new DragBox.Event(DragBox.EventType_.BOXDRAG, - mapBrowserEvent.coordinate, mapBrowserEvent)); + mapBrowserEvent.coordinate, mapBrowserEvent)); }; @@ -138,10 +138,10 @@ DragBox.handleUpEvent_ = function(mapBrowserEvent) { this.box_.setMap(null); if (this.boxEndCondition_(mapBrowserEvent, - this.startPixel_, mapBrowserEvent.pixel)) { + this.startPixel_, mapBrowserEvent.pixel)) { this.onBoxEnd(mapBrowserEvent); this.dispatchEvent(new DragBox.Event(DragBox.EventType_.BOXEND, - mapBrowserEvent.coordinate, mapBrowserEvent)); + mapBrowserEvent.coordinate, mapBrowserEvent)); } return false; }; @@ -164,7 +164,7 @@ DragBox.handleDownEvent_ = function(mapBrowserEvent) { this.box_.setMap(mapBrowserEvent.map); this.box_.setPixels(this.startPixel_, this.startPixel_); this.dispatchEvent(new DragBox.Event(DragBox.EventType_.BOXSTART, - mapBrowserEvent.coordinate, mapBrowserEvent)); + mapBrowserEvent.coordinate, mapBrowserEvent)); return true; } else { return false; diff --git a/src/ol/interaction/DragPan.js b/src/ol/interaction/DragPan.js index bd7e433847..d266647f43 100644 --- a/src/ol/interaction/DragPan.js +++ b/src/ol/interaction/DragPan.js @@ -18,7 +18,7 @@ import PointerInteraction from '../interaction/Pointer.js'; * @param {olx.interaction.DragPanOptions=} opt_options Options. * @api */ -var DragPan = function(opt_options) { +const DragPan = function(opt_options) { PointerInteraction.call(this, { handleDownEvent: DragPan.handleDownEvent_, @@ -26,7 +26,7 @@ var DragPan = function(opt_options) { handleUpEvent: DragPan.handleUpEvent_ }); - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @private @@ -68,20 +68,20 @@ inherits(DragPan, PointerInteraction); * @private */ DragPan.handleDragEvent_ = function(mapBrowserEvent) { - var targetPointers = this.targetPointers; - var centroid = + const targetPointers = this.targetPointers; + const centroid = PointerInteraction.centroid(targetPointers); if (targetPointers.length == this.lastPointersCount_) { if (this.kinetic_) { this.kinetic_.update(centroid[0], centroid[1]); } if (this.lastCentroid) { - var deltaX = this.lastCentroid[0] - centroid[0]; - var deltaY = centroid[1] - this.lastCentroid[1]; - var map = mapBrowserEvent.map; - var view = map.getView(); - var viewState = view.getState(); - var center = [deltaX, deltaY]; + const deltaX = this.lastCentroid[0] - centroid[0]; + const deltaY = centroid[1] - this.lastCentroid[1]; + const map = mapBrowserEvent.map; + const view = map.getView(); + const viewState = view.getState(); + let center = [deltaX, deltaY]; _ol_coordinate_.scale(center, viewState.resolution); _ol_coordinate_.rotate(center, viewState.rotation); _ol_coordinate_.add(center, viewState.center); @@ -105,15 +105,15 @@ DragPan.handleDragEvent_ = function(mapBrowserEvent) { * @private */ DragPan.handleUpEvent_ = function(mapBrowserEvent) { - var map = mapBrowserEvent.map; - var view = map.getView(); + const map = mapBrowserEvent.map; + const view = map.getView(); if (this.targetPointers.length === 0) { if (!this.noKinetic_ && this.kinetic_ && this.kinetic_.end()) { - var distance = this.kinetic_.getDistance(); - var angle = this.kinetic_.getAngle(); - var center = /** @type {!ol.Coordinate} */ (view.getCenter()); - var centerpx = map.getPixelFromCoordinate(center); - var dest = map.getCoordinateFromPixel([ + const distance = this.kinetic_.getDistance(); + const angle = this.kinetic_.getAngle(); + const center = /** @type {!ol.Coordinate} */ (view.getCenter()); + const centerpx = map.getPixelFromCoordinate(center); + const dest = map.getCoordinateFromPixel([ centerpx[0] - distance * Math.cos(angle), centerpx[1] - distance * Math.sin(angle) ]); @@ -145,8 +145,8 @@ DragPan.handleUpEvent_ = function(mapBrowserEvent) { */ DragPan.handleDownEvent_ = function(mapBrowserEvent) { if (this.targetPointers.length > 0 && this.condition_(mapBrowserEvent)) { - var map = mapBrowserEvent.map; - var view = map.getView(); + const map = mapBrowserEvent.map; + const view = map.getView(); this.lastCentroid = null; if (!this.handlingDownUpSequence) { view.setHint(ViewHint.INTERACTING, 1); diff --git a/src/ol/interaction/DragRotate.js b/src/ol/interaction/DragRotate.js index 87facda506..68b14b5138 100644 --- a/src/ol/interaction/DragRotate.js +++ b/src/ol/interaction/DragRotate.js @@ -22,9 +22,9 @@ import PointerInteraction from '../interaction/Pointer.js'; * @param {olx.interaction.DragRotateOptions=} opt_options Options. * @api */ -var DragRotate = function(opt_options) { +const DragRotate = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; PointerInteraction.call(this, { handleDownEvent: DragRotate.handleDownEvent_, @@ -65,20 +65,20 @@ DragRotate.handleDragEvent_ = function(mapBrowserEvent) { return; } - var map = mapBrowserEvent.map; - var view = map.getView(); + const map = mapBrowserEvent.map; + const view = map.getView(); if (view.getConstraints().rotation === RotationConstraint.disable) { return; } - var size = map.getSize(); - var offset = mapBrowserEvent.pixel; - var theta = + const size = map.getSize(); + const offset = mapBrowserEvent.pixel; + const theta = Math.atan2(size[1] / 2 - offset[1], offset[0] - size[0] / 2); if (this.lastAngle_ !== undefined) { - var delta = theta - this.lastAngle_; - var rotation = view.getRotation(); + const delta = theta - this.lastAngle_; + const rotation = view.getRotation(); Interaction.rotateWithoutConstraints( - view, rotation - delta); + view, rotation - delta); } this.lastAngle_ = theta; }; @@ -95,12 +95,12 @@ DragRotate.handleUpEvent_ = function(mapBrowserEvent) { return true; } - var map = mapBrowserEvent.map; - var view = map.getView(); + const map = mapBrowserEvent.map; + const view = map.getView(); view.setHint(ViewHint.INTERACTING, -1); - var rotation = view.getRotation(); + const rotation = view.getRotation(); Interaction.rotate(view, rotation, - undefined, this.duration_); + undefined, this.duration_); return false; }; @@ -118,7 +118,7 @@ DragRotate.handleDownEvent_ = function(mapBrowserEvent) { if (_ol_events_condition_.mouseActionButton(mapBrowserEvent) && this.condition_(mapBrowserEvent)) { - var map = mapBrowserEvent.map; + const map = mapBrowserEvent.map; map.getView().setHint(ViewHint.INTERACTING, 1); this.lastAngle_ = undefined; return true; diff --git a/src/ol/interaction/DragRotateAndZoom.js b/src/ol/interaction/DragRotateAndZoom.js index 757cdef2a9..5a6c667b7a 100644 --- a/src/ol/interaction/DragRotateAndZoom.js +++ b/src/ol/interaction/DragRotateAndZoom.js @@ -23,9 +23,9 @@ import PointerInteraction from '../interaction/Pointer.js'; * @param {olx.interaction.DragRotateAndZoomOptions=} opt_options Options. * @api */ -var DragRotateAndZoom = function(opt_options) { +const DragRotateAndZoom = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; PointerInteraction.call(this, { handleDownEvent: DragRotateAndZoom.handleDownEvent_, @@ -79,22 +79,22 @@ DragRotateAndZoom.handleDragEvent_ = function(mapBrowserEvent) { return; } - var map = mapBrowserEvent.map; - var size = map.getSize(); - var offset = mapBrowserEvent.pixel; - var deltaX = offset[0] - size[0] / 2; - var deltaY = size[1] / 2 - offset[1]; - var theta = Math.atan2(deltaY, deltaX); - var magnitude = Math.sqrt(deltaX * deltaX + deltaY * deltaY); - var view = map.getView(); + const map = mapBrowserEvent.map; + const size = map.getSize(); + const offset = mapBrowserEvent.pixel; + const deltaX = offset[0] - size[0] / 2; + const deltaY = size[1] / 2 - offset[1]; + const theta = Math.atan2(deltaY, deltaX); + const magnitude = Math.sqrt(deltaX * deltaX + deltaY * deltaY); + const view = map.getView(); if (view.getConstraints().rotation !== RotationConstraint.disable && this.lastAngle_ !== undefined) { - var angleDelta = theta - this.lastAngle_; + const angleDelta = theta - this.lastAngle_; Interaction.rotateWithoutConstraints( - view, view.getRotation() - angleDelta); + view, view.getRotation() - angleDelta); } this.lastAngle_ = theta; if (this.lastMagnitude_ !== undefined) { - var resolution = this.lastMagnitude_ * (view.getResolution() / magnitude); + const resolution = this.lastMagnitude_ * (view.getResolution() / magnitude); Interaction.zoomWithoutConstraints(view, resolution); } if (this.lastMagnitude_ !== undefined) { @@ -115,13 +115,13 @@ DragRotateAndZoom.handleUpEvent_ = function(mapBrowserEvent) { return true; } - var map = mapBrowserEvent.map; - var view = map.getView(); + const map = mapBrowserEvent.map; + const view = map.getView(); view.setHint(ViewHint.INTERACTING, -1); - var direction = this.lastScaleDelta_ - 1; + const direction = this.lastScaleDelta_ - 1; Interaction.rotate(view, view.getRotation()); Interaction.zoom(view, view.getResolution(), - undefined, this.duration_, direction); + undefined, this.duration_, direction); this.lastScaleDelta_ = 0; return false; }; diff --git a/src/ol/interaction/DragZoom.js b/src/ol/interaction/DragZoom.js index 46ca913859..7ad972c743 100644 --- a/src/ol/interaction/DragZoom.js +++ b/src/ol/interaction/DragZoom.js @@ -21,10 +21,10 @@ import DragBox from '../interaction/DragBox.js'; * @param {olx.interaction.DragZoomOptions=} opt_options Options. * @api */ -var DragZoom = function(opt_options) { - var options = opt_options ? opt_options : {}; +const DragZoom = function(opt_options) { + const options = opt_options ? opt_options : {}; - var condition = options.condition ? + const condition = options.condition ? options.condition : _ol_events_condition_.shiftKeyOnly; /** @@ -53,29 +53,29 @@ inherits(DragZoom, DragBox); * @inheritDoc */ DragZoom.prototype.onBoxEnd = function() { - var map = this.getMap(); + const map = this.getMap(); - var view = /** @type {!ol.View} */ (map.getView()); + const view = /** @type {!ol.View} */ (map.getView()); - var size = /** @type {!ol.Size} */ (map.getSize()); + const size = /** @type {!ol.Size} */ (map.getSize()); - var extent = this.getGeometry().getExtent(); + let extent = this.getGeometry().getExtent(); if (this.out_) { - var mapExtent = view.calculateExtent(size); - var boxPixelExtent = createOrUpdateFromCoordinates([ + const mapExtent = view.calculateExtent(size); + const boxPixelExtent = createOrUpdateFromCoordinates([ map.getPixelFromCoordinate(getBottomLeft(extent)), map.getPixelFromCoordinate(getTopRight(extent))]); - var factor = view.getResolutionForExtent(boxPixelExtent, size); + const factor = view.getResolutionForExtent(boxPixelExtent, size); scaleFromCenter(mapExtent, 1 / factor); extent = mapExtent; } - var resolution = view.constrainResolution( - view.getResolutionForExtent(extent, size)); + const resolution = view.constrainResolution( + view.getResolutionForExtent(extent, size)); - var center = getCenter(extent); + let center = getCenter(extent); center = view.constrainCenter(center); view.animate({ diff --git a/src/ol/interaction/Draw.js b/src/ol/interaction/Draw.js index dec83deed4..1422302fb3 100644 --- a/src/ol/interaction/Draw.js +++ b/src/ol/interaction/Draw.js @@ -36,7 +36,7 @@ import Style from '../style/Style.js'; * @param {olx.interaction.DrawOptions} options Options. * @api */ -var Draw = function(options) { +const Draw = function(options) { PointerInteraction.call(this, { handleDownEvent: Draw.handleDownEvent_, @@ -131,7 +131,7 @@ var Draw = function(options) { */ this.finishCondition_ = options.finishCondition ? options.finishCondition : TRUE; - var geometryFunction = options.geometryFunction; + let geometryFunction = options.geometryFunction; if (!geometryFunction) { if (this.type_ === GeometryType.CIRCLE) { /** @@ -141,16 +141,16 @@ var Draw = function(options) { * @return {ol.geom.SimpleGeometry} A geometry. */ geometryFunction = function(coordinates, opt_geometry) { - var circle = opt_geometry ? /** @type {ol.geom.Circle} */ (opt_geometry) : + const circle = opt_geometry ? /** @type {ol.geom.Circle} */ (opt_geometry) : new Circle([NaN, NaN]); - var squaredLength = _ol_coordinate_.squaredDistance( - coordinates[0], coordinates[1]); + const squaredLength = _ol_coordinate_.squaredDistance( + coordinates[0], coordinates[1]); circle.setCenterAndRadius(coordinates[0], Math.sqrt(squaredLength)); return circle; }; } else { - var Constructor; - var mode = this.mode_; + let Constructor; + const mode = this.mode_; if (mode === Draw.Mode_.POINT) { Constructor = Point; } else if (mode === Draw.Mode_.LINE_STRING) { @@ -165,7 +165,7 @@ var Draw = function(options) { * @return {ol.geom.SimpleGeometry} A geometry. */ geometryFunction = function(coordinates, opt_geometry) { - var geometry = opt_geometry; + let geometry = opt_geometry; if (geometry) { if (mode === Draw.Mode_.POLYGON) { if (coordinates[0].length) { @@ -285,8 +285,8 @@ var Draw = function(options) { } _ol_events_.listen(this, - BaseObject.getChangeEventType(InteractionProperty.ACTIVE), - this.updateState_, this); + BaseObject.getChangeEventType(InteractionProperty.ACTIVE), + this.updateState_, this); }; @@ -297,7 +297,7 @@ inherits(Draw, PointerInteraction); * @return {ol.StyleFunction} Styles. */ Draw.getDefaultStyleFunction = function() { - var styles = Style.createDefaultEditing(); + const styles = Style.createDefaultEditing(); return function(feature, resolution) { return styles[feature.getGeometry().getType()]; }; @@ -323,7 +323,7 @@ Draw.prototype.setMap = function(map) { */ Draw.handleEvent = function(event) { this.freehand_ = this.mode_ !== Draw.Mode_.POINT && this.freehandCondition_(event); - var pass = true; + let pass = true; if (this.freehand_ && event.type === MapBrowserEventType.POINTERDRAG && this.sketchFeature_ !== null) { @@ -372,11 +372,11 @@ Draw.handleDownEvent_ = function(event) { * @private */ Draw.handleUpEvent_ = function(event) { - var pass = true; + let pass = true; this.handlePointerMove_(event); - var circleMode = this.mode_ === Draw.Mode_.CIRCLE; + const circleMode = this.mode_ === Draw.Mode_.CIRCLE; if (this.shouldHandle_) { if (!this.finishCoordinate_) { @@ -415,11 +415,11 @@ Draw.prototype.handlePointerMove_ = function(event) { if (this.downPx_ && ((!this.freehand_ && this.shouldHandle_) || (this.freehand_ && !this.shouldHandle_))) { - var downPx = this.downPx_; - var clickPx = event.pixel; - var dx = downPx[0] - clickPx[0]; - var dy = downPx[1] - clickPx[1]; - var squaredDistance = dx * dx + dy * dy; + const downPx = this.downPx_; + const clickPx = event.pixel; + const dx = downPx[0] - clickPx[0]; + const dy = downPx[1] - clickPx[1]; + const squaredDistance = dx * dx + dy * dy; this.shouldHandle_ = this.freehand_ ? squaredDistance > this.squaredClickTolerance_ : squaredDistance <= this.squaredClickTolerance_; @@ -441,10 +441,10 @@ Draw.prototype.handlePointerMove_ = function(event) { * @private */ Draw.prototype.atFinish_ = function(event) { - var at = false; + let at = false; if (this.sketchFeature_) { - var potentiallyDone = false; - var potentiallyFinishCoordinates = [this.finishCoordinate_]; + let potentiallyDone = false; + let potentiallyFinishCoordinates = [this.finishCoordinate_]; if (this.mode_ === Draw.Mode_.LINE_STRING) { potentiallyDone = this.sketchCoords_.length > this.minPoints_; } else if (this.mode_ === Draw.Mode_.POLYGON) { @@ -454,14 +454,14 @@ Draw.prototype.atFinish_ = function(event) { this.sketchCoords_[0][this.sketchCoords_[0].length - 2]]; } if (potentiallyDone) { - var map = event.map; - for (var i = 0, ii = potentiallyFinishCoordinates.length; i < ii; i++) { - var finishCoordinate = potentiallyFinishCoordinates[i]; - var finishPixel = map.getPixelFromCoordinate(finishCoordinate); - var pixel = event.pixel; - var dx = pixel[0] - finishPixel[0]; - var dy = pixel[1] - finishPixel[1]; - var snapTolerance = this.freehand_ ? 1 : this.snapTolerance_; + const map = event.map; + for (let i = 0, ii = potentiallyFinishCoordinates.length; i < ii; i++) { + const finishCoordinate = potentiallyFinishCoordinates[i]; + const finishPixel = map.getPixelFromCoordinate(finishCoordinate); + const pixel = event.pixel; + const dx = pixel[0] - finishPixel[0]; + const dy = pixel[1] - finishPixel[1]; + const snapTolerance = this.freehand_ ? 1 : this.snapTolerance_; at = Math.sqrt(dx * dx + dy * dy) <= snapTolerance; if (at) { this.finishCoordinate_ = finishCoordinate; @@ -479,12 +479,12 @@ Draw.prototype.atFinish_ = function(event) { * @private */ Draw.prototype.createOrUpdateSketchPoint_ = function(event) { - var coordinates = event.coordinate.slice(); + const coordinates = event.coordinate.slice(); if (!this.sketchPoint_) { this.sketchPoint_ = new Feature(new Point(coordinates)); this.updateSketchFeatures_(); } else { - var sketchPointGeom = /** @type {ol.geom.Point} */ (this.sketchPoint_.getGeometry()); + const sketchPointGeom = /** @type {ol.geom.Point} */ (this.sketchPoint_.getGeometry()); sketchPointGeom.setCoordinates(coordinates); } }; @@ -496,7 +496,7 @@ Draw.prototype.createOrUpdateSketchPoint_ = function(event) { * @private */ Draw.prototype.startDrawing_ = function(event) { - var start = event.coordinate; + const start = event.coordinate; this.finishCoordinate_ = start; if (this.mode_ === Draw.Mode_.POINT) { this.sketchCoords_ = start.slice(); @@ -511,9 +511,9 @@ Draw.prototype.startDrawing_ = function(event) { } if (this.sketchLineCoords_) { this.sketchLine_ = new Feature( - new LineString(this.sketchLineCoords_)); + new LineString(this.sketchLineCoords_)); } - var geometry = this.geometryFunction_(this.sketchCoords_); + const geometry = this.geometryFunction_(this.sketchCoords_); this.sketchFeature_ = new Feature(); if (this.geometryName_) { this.sketchFeature_.setGeometryName(this.geometryName_); @@ -530,9 +530,9 @@ Draw.prototype.startDrawing_ = function(event) { * @private */ Draw.prototype.modifyDrawing_ = function(event) { - var coordinate = event.coordinate; - var geometry = /** @type {ol.geom.SimpleGeometry} */ (this.sketchFeature_.getGeometry()); - var coordinates, last; + let coordinate = event.coordinate; + const geometry = /** @type {ol.geom.SimpleGeometry} */ (this.sketchFeature_.getGeometry()); + let coordinates, last; if (this.mode_ === Draw.Mode_.POINT) { last = this.sketchCoords_; } else if (this.mode_ === Draw.Mode_.POLYGON) { @@ -550,19 +550,19 @@ Draw.prototype.modifyDrawing_ = function(event) { last[1] = coordinate[1]; this.geometryFunction_(/** @type {!Array.} */ (this.sketchCoords_), geometry); if (this.sketchPoint_) { - var sketchPointGeom = /** @type {ol.geom.Point} */ (this.sketchPoint_.getGeometry()); + const sketchPointGeom = /** @type {ol.geom.Point} */ (this.sketchPoint_.getGeometry()); sketchPointGeom.setCoordinates(coordinate); } - var sketchLineGeom; + let sketchLineGeom; if (geometry instanceof Polygon && this.mode_ !== Draw.Mode_.POLYGON) { if (!this.sketchLine_) { this.sketchLine_ = new Feature(new LineString(null)); } - var ring = geometry.getLinearRing(0); + const ring = geometry.getLinearRing(0); sketchLineGeom = /** @type {ol.geom.LineString} */ (this.sketchLine_.getGeometry()); sketchLineGeom.setFlatCoordinates( - ring.getLayout(), ring.getFlatCoordinates()); + ring.getLayout(), ring.getFlatCoordinates()); } else if (this.sketchLineCoords_) { sketchLineGeom = /** @type {ol.geom.LineString} */ (this.sketchLine_.getGeometry()); sketchLineGeom.setCoordinates(this.sketchLineCoords_); @@ -577,10 +577,10 @@ Draw.prototype.modifyDrawing_ = function(event) { * @private */ Draw.prototype.addToDrawing_ = function(event) { - var coordinate = event.coordinate; - var geometry = /** @type {ol.geom.SimpleGeometry} */ (this.sketchFeature_.getGeometry()); - var done; - var coordinates; + const coordinate = event.coordinate; + const geometry = /** @type {ol.geom.SimpleGeometry} */ (this.sketchFeature_.getGeometry()); + let done; + let coordinates; if (this.mode_ === Draw.Mode_.LINE_STRING) { this.finishCoordinate_ = coordinate.slice(); coordinates = this.sketchCoords_; @@ -623,8 +623,8 @@ Draw.prototype.removeLastPoint = function() { if (!this.sketchFeature_) { return; } - var geometry = /** @type {ol.geom.SimpleGeometry} */ (this.sketchFeature_.getGeometry()); - var coordinates, sketchLineGeom; + const geometry = /** @type {ol.geom.SimpleGeometry} */ (this.sketchFeature_.getGeometry()); + let coordinates, sketchLineGeom; if (this.mode_ === Draw.Mode_.LINE_STRING) { coordinates = this.sketchCoords_; coordinates.splice(-2, 1); @@ -655,9 +655,9 @@ Draw.prototype.removeLastPoint = function() { * @api */ Draw.prototype.finishDrawing = function() { - var sketchFeature = this.abortDrawing_(); - var coordinates = this.sketchCoords_; - var geometry = /** @type {ol.geom.SimpleGeometry} */ (sketchFeature.getGeometry()); + const sketchFeature = this.abortDrawing_(); + let coordinates = this.sketchCoords_; + const geometry = /** @type {ol.geom.SimpleGeometry} */ (sketchFeature.getGeometry()); if (this.mode_ === Draw.Mode_.LINE_STRING) { // remove the redundant last point coordinates.pop(); @@ -698,7 +698,7 @@ Draw.prototype.finishDrawing = function() { */ Draw.prototype.abortDrawing_ = function() { this.finishCoordinate_ = null; - var sketchFeature = this.sketchFeature_; + const sketchFeature = this.sketchFeature_; if (sketchFeature) { this.sketchFeature_ = null; this.sketchPoint_ = null; @@ -717,11 +717,11 @@ Draw.prototype.abortDrawing_ = function() { * @api */ Draw.prototype.extend = function(feature) { - var geometry = feature.getGeometry(); - var lineString = /** @type {ol.geom.LineString} */ (geometry); + const geometry = feature.getGeometry(); + const lineString = /** @type {ol.geom.LineString} */ (geometry); this.sketchFeature_ = feature; this.sketchCoords_ = lineString.getCoordinates(); - var last = this.sketchCoords_[this.sketchCoords_.length - 1]; + const last = this.sketchCoords_[this.sketchCoords_.length - 1]; this.finishCoordinate_ = last.slice(); this.sketchCoords_.push(last.slice()); this.updateSketchFeatures_(); @@ -740,7 +740,7 @@ Draw.prototype.shouldStopEvent = FALSE; * @private */ Draw.prototype.updateSketchFeatures_ = function() { - var sketchFeatures = []; + const sketchFeatures = []; if (this.sketchFeature_) { sketchFeatures.push(this.sketchFeature_); } @@ -750,7 +750,7 @@ Draw.prototype.updateSketchFeatures_ = function() { if (this.sketchPoint_) { sketchFeatures.push(this.sketchPoint_); } - var overlaySource = this.overlay_.getSource(); + const overlaySource = this.overlay_.getSource(); overlaySource.clear(true); overlaySource.addFeatures(sketchFeatures); }; @@ -760,8 +760,8 @@ Draw.prototype.updateSketchFeatures_ = function() { * @private */ Draw.prototype.updateState_ = function() { - var map = this.getMap(); - var active = this.getActive(); + const map = this.getMap(); + const active = this.getActive(); if (!map || !active) { this.abortDrawing_(); } @@ -790,13 +790,13 @@ Draw.createRegularPolygon = function(opt_sides, opt_angle) { * @return {ol.geom.SimpleGeometry} */ function(coordinates, opt_geometry) { - var center = coordinates[0]; - var end = coordinates[1]; - var radius = Math.sqrt( - _ol_coordinate_.squaredDistance(center, end)); - var geometry = opt_geometry ? /** @type {ol.geom.Polygon} */ (opt_geometry) : + const center = coordinates[0]; + const end = coordinates[1]; + const radius = Math.sqrt( + _ol_coordinate_.squaredDistance(center, end)); + const geometry = opt_geometry ? /** @type {ol.geom.Polygon} */ (opt_geometry) : fromCircle(new Circle(center), opt_sides); - var angle = opt_angle ? opt_angle : + const angle = opt_angle ? opt_angle : Math.atan((end[1] - center[1]) / (end[0] - center[0])); makeRegular(geometry, center, radius, angle); return geometry; @@ -820,8 +820,8 @@ Draw.createBox = function() { * @return {ol.geom.SimpleGeometry} */ function(coordinates, opt_geometry) { - var extent = boundingExtent(coordinates); - var geometry = opt_geometry || new Polygon(null); + const extent = boundingExtent(coordinates); + const geometry = opt_geometry || new Polygon(null); geometry.setCoordinates([[ getBottomLeft(extent), getBottomRight(extent), @@ -843,7 +843,7 @@ Draw.createBox = function() { * @private */ Draw.getMode_ = function(type) { - var mode; + let mode; if (type === GeometryType.POINT || type === GeometryType.MULTI_POINT) { mode = Draw.Mode_.POINT; diff --git a/src/ol/interaction/Extent.js b/src/ol/interaction/Extent.js index a85ebae843..bb445d9a53 100644 --- a/src/ol/interaction/Extent.js +++ b/src/ol/interaction/Extent.js @@ -29,9 +29,9 @@ import Style from '../style/Style.js'; * @param {olx.interaction.ExtentOptions=} opt_options Options. * @api */ -var ExtentInteraction = function(opt_options) { +const ExtentInteraction = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; /** * Extent of the drawn box @@ -152,16 +152,16 @@ ExtentInteraction.handleEvent_ = function(mapBrowserEvent) { * @private */ ExtentInteraction.handleDownEvent_ = function(mapBrowserEvent) { - var pixel = mapBrowserEvent.pixel; - var map = mapBrowserEvent.map; + const pixel = mapBrowserEvent.pixel; + const map = mapBrowserEvent.map; - var extent = this.getExtent(); - var vertex = this.snapToVertex_(pixel, map); + const extent = this.getExtent(); + let vertex = this.snapToVertex_(pixel, map); //find the extent corner opposite the passed corner - var getOpposingPoint = function(point) { - var x_ = null; - var y_ = null; + const getOpposingPoint = function(point) { + let x_ = null; + let y_ = null; if (point[0] == extent[0]) { x_ = extent[2]; } else if (point[0] == extent[2]) { @@ -178,8 +178,8 @@ ExtentInteraction.handleDownEvent_ = function(mapBrowserEvent) { return null; }; if (vertex && extent) { - var x = (vertex[0] == extent[0] || vertex[0] == extent[2]) ? vertex[0] : null; - var y = (vertex[1] == extent[1] || vertex[1] == extent[3]) ? vertex[1] : null; + const x = (vertex[0] == extent[0] || vertex[0] == extent[2]) ? vertex[0] : null; + const y = (vertex[1] == extent[1] || vertex[1] == extent[3]) ? vertex[1] : null; //snap to point if (x !== null && y !== null) { @@ -187,13 +187,13 @@ ExtentInteraction.handleDownEvent_ = function(mapBrowserEvent) { //snap to edge } else if (x !== null) { this.pointerHandler_ = ExtentInteraction.getEdgeHandler_( - getOpposingPoint([x, extent[1]]), - getOpposingPoint([x, extent[3]]) + getOpposingPoint([x, extent[1]]), + getOpposingPoint([x, extent[3]]) ); } else if (y !== null) { this.pointerHandler_ = ExtentInteraction.getEdgeHandler_( - getOpposingPoint([extent[0], y]), - getOpposingPoint([extent[2], y]) + getOpposingPoint([extent[0], y]), + getOpposingPoint([extent[2], y]) ); } //no snap - new bbox @@ -213,7 +213,7 @@ ExtentInteraction.handleDownEvent_ = function(mapBrowserEvent) { */ ExtentInteraction.handleDragEvent_ = function(mapBrowserEvent) { if (this.pointerHandler_) { - var pixelCoordinate = mapBrowserEvent.coordinate; + const pixelCoordinate = mapBrowserEvent.coordinate; this.setExtent(this.pointerHandler_(pixelCoordinate)); this.createOrUpdatePointerFeature_(pixelCoordinate); } @@ -229,7 +229,7 @@ ExtentInteraction.handleDragEvent_ = function(mapBrowserEvent) { ExtentInteraction.handleUpEvent_ = function(mapBrowserEvent) { this.pointerHandler_ = null; //If bbox is zero area, set to null; - var extent = this.getExtent(); + const extent = this.getExtent(); if (!extent || getArea(extent) === 0) { this.setExtent(null); } @@ -243,7 +243,7 @@ ExtentInteraction.handleUpEvent_ = function(mapBrowserEvent) { * @private */ ExtentInteraction.getDefaultExtentStyleFunction_ = function() { - var style = Style.createDefaultEditing(); + const style = Style.createDefaultEditing(); return function(feature, resolution) { return style[GeometryType.POLYGON]; }; @@ -256,7 +256,7 @@ ExtentInteraction.getDefaultExtentStyleFunction_ = function() { * @private */ ExtentInteraction.getDefaultPointerStyleFunction_ = function() { - var style = Style.createDefaultEditing(); + const style = Style.createDefaultEditing(); return function(feature, resolution) { return style[GeometryType.POINT]; }; @@ -314,30 +314,30 @@ ExtentInteraction.getSegments_ = function(extent) { * @private */ ExtentInteraction.prototype.snapToVertex_ = function(pixel, map) { - var pixelCoordinate = map.getCoordinateFromPixel(pixel); - var sortByDistance = function(a, b) { + const pixelCoordinate = map.getCoordinateFromPixel(pixel); + const sortByDistance = function(a, b) { return _ol_coordinate_.squaredDistanceToSegment(pixelCoordinate, a) - _ol_coordinate_.squaredDistanceToSegment(pixelCoordinate, b); }; - var extent = this.getExtent(); + const extent = this.getExtent(); if (extent) { //convert extents to line segments and find the segment closest to pixelCoordinate - var segments = ExtentInteraction.getSegments_(extent); + const segments = ExtentInteraction.getSegments_(extent); segments.sort(sortByDistance); - var closestSegment = segments[0]; + const closestSegment = segments[0]; - var vertex = (_ol_coordinate_.closestOnSegment(pixelCoordinate, - closestSegment)); - var vertexPixel = map.getPixelFromCoordinate(vertex); + let vertex = (_ol_coordinate_.closestOnSegment(pixelCoordinate, + closestSegment)); + const vertexPixel = map.getPixelFromCoordinate(vertex); //if the distance is within tolerance, snap to the segment if (_ol_coordinate_.distance(pixel, vertexPixel) <= this.pixelTolerance_) { //test if we should further snap to a vertex - var pixel1 = map.getPixelFromCoordinate(closestSegment[0]); - var pixel2 = map.getPixelFromCoordinate(closestSegment[1]); - var squaredDist1 = _ol_coordinate_.squaredDistance(vertexPixel, pixel1); - var squaredDist2 = _ol_coordinate_.squaredDistance(vertexPixel, pixel2); - var dist = Math.sqrt(Math.min(squaredDist1, squaredDist2)); + const pixel1 = map.getPixelFromCoordinate(closestSegment[0]); + const pixel2 = map.getPixelFromCoordinate(closestSegment[1]); + const squaredDist1 = _ol_coordinate_.squaredDistance(vertexPixel, pixel1); + const squaredDist2 = _ol_coordinate_.squaredDistance(vertexPixel, pixel2); + const dist = Math.sqrt(Math.min(squaredDist1, squaredDist2)); this.snappedToVertex_ = dist <= this.pixelTolerance_; if (this.snappedToVertex_) { vertex = squaredDist1 > squaredDist2 ? @@ -354,10 +354,10 @@ ExtentInteraction.prototype.snapToVertex_ = function(pixel, map) { * @private */ ExtentInteraction.prototype.handlePointerMove_ = function(mapBrowserEvent) { - var pixel = mapBrowserEvent.pixel; - var map = mapBrowserEvent.map; + const pixel = mapBrowserEvent.pixel; + const map = mapBrowserEvent.map; - var vertex = this.snapToVertex_(pixel, map); + let vertex = this.snapToVertex_(pixel, map); if (!vertex) { vertex = map.getCoordinateFromPixel(pixel); } @@ -370,7 +370,7 @@ ExtentInteraction.prototype.handlePointerMove_ = function(mapBrowserEvent) { * @private */ ExtentInteraction.prototype.createOrUpdateExtentFeature_ = function(extent) { - var extentFeature = this.extentFeature_; + let extentFeature = this.extentFeature_; if (!extentFeature) { if (!extent) { @@ -397,13 +397,13 @@ ExtentInteraction.prototype.createOrUpdateExtentFeature_ = function(extent) { * @private */ ExtentInteraction.prototype.createOrUpdatePointerFeature_ = function(vertex) { - var vertexFeature = this.vertexFeature_; + let vertexFeature = this.vertexFeature_; if (!vertexFeature) { vertexFeature = new Feature(new Point(vertex)); this.vertexFeature_ = vertexFeature; this.vertexOverlay_.getSource().addFeature(vertexFeature); } else { - var geometry = /** @type {ol.geom.Point} */ (vertexFeature.getGeometry()); + const geometry = /** @type {ol.geom.Point} */ (vertexFeature.getGeometry()); geometry.setCoordinates(vertex); } return vertexFeature; diff --git a/src/ol/interaction/Interaction.js b/src/ol/interaction/Interaction.js index be50c55879..d707b113da 100644 --- a/src/ol/interaction/Interaction.js +++ b/src/ol/interaction/Interaction.js @@ -12,7 +12,7 @@ import {clamp} from '../math.js'; * Object literal with config options for interactions. * @typedef {{handleEvent: function(ol.MapBrowserEvent):boolean}} */ -export var InteractionOptions; +export let InteractionOptions; /** @@ -38,7 +38,7 @@ export var InteractionOptions; * @extends {ol.Object} * @api */ -var Interaction = function(options) { +const Interaction = function(options) { BaseObject.call(this); @@ -109,10 +109,10 @@ Interaction.prototype.setMap = function(map) { * @param {number=} opt_duration Duration. */ Interaction.pan = function(view, delta, opt_duration) { - var currentCenter = view.getCenter(); + const currentCenter = view.getCenter(); if (currentCenter) { - var center = view.constrainCenter( - [currentCenter[0] + delta[0], currentCenter[1] + delta[1]]); + const center = view.constrainCenter( + [currentCenter[0] + delta[0], currentCenter[1] + delta[1]]); if (opt_duration) { view.animate({ duration: opt_duration, @@ -135,7 +135,7 @@ Interaction.pan = function(view, delta, opt_duration) { Interaction.rotate = function(view, rotation, opt_anchor, opt_duration) { rotation = view.constrainRotation(rotation, 0); Interaction.rotateWithoutConstraints( - view, rotation, opt_anchor, opt_duration); + view, rotation, opt_anchor, opt_duration); }; @@ -147,8 +147,8 @@ Interaction.rotate = function(view, rotation, opt_anchor, opt_duration) { */ Interaction.rotateWithoutConstraints = function(view, rotation, opt_anchor, opt_duration) { if (rotation !== undefined) { - var currentRotation = view.getRotation(); - var currentCenter = view.getCenter(); + const currentRotation = view.getRotation(); + const currentCenter = view.getCenter(); if (currentRotation !== undefined && currentCenter && opt_duration > 0) { view.animate({ rotation: rotation, @@ -180,7 +180,7 @@ Interaction.rotateWithoutConstraints = function(view, rotation, opt_anchor, opt_ Interaction.zoom = function(view, resolution, opt_anchor, opt_duration, opt_direction) { resolution = view.constrainResolution(resolution, 0, opt_direction); Interaction.zoomWithoutConstraints( - view, resolution, opt_anchor, opt_duration); + view, resolution, opt_anchor, opt_duration); }; @@ -191,23 +191,23 @@ Interaction.zoom = function(view, resolution, opt_anchor, opt_duration, opt_dire * @param {number=} opt_duration Duration. */ Interaction.zoomByDelta = function(view, delta, opt_anchor, opt_duration) { - var currentResolution = view.getResolution(); - var resolution = view.constrainResolution(currentResolution, delta, 0); + const currentResolution = view.getResolution(); + let resolution = view.constrainResolution(currentResolution, delta, 0); if (resolution !== undefined) { - var resolutions = view.getResolutions(); + const resolutions = view.getResolutions(); resolution = clamp( - resolution, - view.getMinResolution() || resolutions[resolutions.length - 1], - view.getMaxResolution() || resolutions[0]); + resolution, + view.getMinResolution() || resolutions[resolutions.length - 1], + view.getMaxResolution() || resolutions[0]); } // If we have a constraint on center, we need to change the anchor so that the // new center is within the extent. We first calculate the new center, apply // the constraint to it, and then calculate back the anchor if (opt_anchor && resolution !== undefined && resolution !== currentResolution) { - var currentCenter = view.getCenter(); - var center = view.calculateCenterZoom(resolution, opt_anchor); + const currentCenter = view.getCenter(); + let center = view.calculateCenterZoom(resolution, opt_anchor); center = view.constrainCenter(center); opt_anchor = [ @@ -219,7 +219,7 @@ Interaction.zoomByDelta = function(view, delta, opt_anchor, opt_duration) { } Interaction.zoomWithoutConstraints( - view, resolution, opt_anchor, opt_duration); + view, resolution, opt_anchor, opt_duration); }; @@ -231,8 +231,8 @@ Interaction.zoomByDelta = function(view, delta, opt_anchor, opt_duration) { */ Interaction.zoomWithoutConstraints = function(view, resolution, opt_anchor, opt_duration) { if (resolution) { - var currentResolution = view.getResolution(); - var currentCenter = view.getCenter(); + const currentResolution = view.getResolution(); + const currentCenter = view.getCenter(); if (currentResolution !== undefined && currentCenter && resolution !== currentResolution && opt_duration) { view.animate({ @@ -243,7 +243,7 @@ Interaction.zoomWithoutConstraints = function(view, resolution, opt_anchor, opt_ }); } else { if (opt_anchor) { - var center = view.calculateCenterZoom(resolution, opt_anchor); + const center = view.calculateCenterZoom(resolution, opt_anchor); view.setCenter(center); } view.setResolution(resolution); diff --git a/src/ol/interaction/KeyboardPan.js b/src/ol/interaction/KeyboardPan.js index 274ea2ad83..b3cb67e99a 100644 --- a/src/ol/interaction/KeyboardPan.js +++ b/src/ol/interaction/KeyboardPan.js @@ -25,13 +25,13 @@ import Interaction from '../interaction/Interaction.js'; * @param {olx.interaction.KeyboardPanOptions=} opt_options Options. * @api */ -var KeyboardPan = function(opt_options) { +const KeyboardPan = function(opt_options) { Interaction.call(this, { handleEvent: KeyboardPan.handleEvent }); - var options = opt_options || {}; + const options = opt_options || {}; /** * @private @@ -77,19 +77,19 @@ inherits(KeyboardPan, Interaction); * @api */ KeyboardPan.handleEvent = function(mapBrowserEvent) { - var stopEvent = false; + let stopEvent = false; if (mapBrowserEvent.type == EventType.KEYDOWN) { - var keyEvent = mapBrowserEvent.originalEvent; - var keyCode = keyEvent.keyCode; + const keyEvent = mapBrowserEvent.originalEvent; + const keyCode = keyEvent.keyCode; if (this.condition_(mapBrowserEvent) && (keyCode == _ol_events_KeyCode_.DOWN || keyCode == _ol_events_KeyCode_.LEFT || keyCode == _ol_events_KeyCode_.RIGHT || keyCode == _ol_events_KeyCode_.UP)) { - var map = mapBrowserEvent.map; - var view = map.getView(); - var mapUnitsDelta = view.getResolution() * this.pixelDelta_; - var deltaX = 0, deltaY = 0; + const map = mapBrowserEvent.map; + const view = map.getView(); + const mapUnitsDelta = view.getResolution() * this.pixelDelta_; + let deltaX = 0, deltaY = 0; if (keyCode == _ol_events_KeyCode_.DOWN) { deltaY = -mapUnitsDelta; } else if (keyCode == _ol_events_KeyCode_.LEFT) { @@ -99,7 +99,7 @@ KeyboardPan.handleEvent = function(mapBrowserEvent) { } else { deltaY = mapUnitsDelta; } - var delta = [deltaX, deltaY]; + const delta = [deltaX, deltaY]; _ol_coordinate_.rotate(delta, view.getRotation()); Interaction.pan(view, delta, this.duration_); mapBrowserEvent.preventDefault(); diff --git a/src/ol/interaction/KeyboardZoom.js b/src/ol/interaction/KeyboardZoom.js index 889a27ddfe..1e88eb6990 100644 --- a/src/ol/interaction/KeyboardZoom.js +++ b/src/ol/interaction/KeyboardZoom.js @@ -23,13 +23,13 @@ import Interaction from '../interaction/Interaction.js'; * @extends {ol.interaction.Interaction} * @api */ -var KeyboardZoom = function(opt_options) { +const KeyboardZoom = function(opt_options) { Interaction.call(this, { handleEvent: KeyboardZoom.handleEvent }); - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @private @@ -65,18 +65,18 @@ inherits(KeyboardZoom, Interaction); * @api */ KeyboardZoom.handleEvent = function(mapBrowserEvent) { - var stopEvent = false; + let stopEvent = false; if (mapBrowserEvent.type == EventType.KEYDOWN || mapBrowserEvent.type == EventType.KEYPRESS) { - var keyEvent = mapBrowserEvent.originalEvent; - var charCode = keyEvent.charCode; + const keyEvent = mapBrowserEvent.originalEvent; + const charCode = keyEvent.charCode; if (this.condition_(mapBrowserEvent) && (charCode == '+'.charCodeAt(0) || charCode == '-'.charCodeAt(0))) { - var map = mapBrowserEvent.map; - var delta = (charCode == '+'.charCodeAt(0)) ? this.delta_ : -this.delta_; - var view = map.getView(); + const map = mapBrowserEvent.map; + const delta = (charCode == '+'.charCodeAt(0)) ? this.delta_ : -this.delta_; + const view = map.getView(); Interaction.zoomByDelta( - view, delta, undefined, this.duration_); + view, delta, undefined, this.duration_); mapBrowserEvent.preventDefault(); stopEvent = true; } diff --git a/src/ol/interaction/Modify.js b/src/ol/interaction/Modify.js index f8ceae718d..56e778d454 100644 --- a/src/ol/interaction/Modify.js +++ b/src/ol/interaction/Modify.js @@ -43,7 +43,7 @@ import Style from '../style/Style.js'; * @fires ol.interaction.Modify.Event * @api */ -var Modify = function(options) { +const Modify = function(options) { PointerInteraction.call(this, { handleDownEvent: Modify.handleDownEvent_, @@ -192,14 +192,14 @@ var Modify = function(options) { */ this.source_ = null; - var features; + let features; if (options.source) { this.source_ = options.source; features = new Collection(this.source_.getFeatures()); _ol_events_.listen(this.source_, VectorEventType.ADDFEATURE, - this.handleSourceAdd_, this); + this.handleSourceAdd_, this); _ol_events_.listen(this.source_, VectorEventType.REMOVEFEATURE, - this.handleSourceRemove_, this); + this.handleSourceRemove_, this); } else { features = options.features; } @@ -215,9 +215,9 @@ var Modify = function(options) { this.features_.forEach(this.addFeature_.bind(this)); _ol_events_.listen(this.features_, CollectionEventType.ADD, - this.handleFeatureAdd_, this); + this.handleFeatureAdd_, this); _ol_events_.listen(this.features_, CollectionEventType.REMOVE, - this.handleFeatureRemove_, this); + this.handleFeatureRemove_, this); /** * @type {ol.MapBrowserPointerEvent} @@ -248,16 +248,16 @@ Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX = 1; * @private */ Modify.prototype.addFeature_ = function(feature) { - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); if (geometry && geometry.getType() in this.SEGMENT_WRITERS_) { this.SEGMENT_WRITERS_[geometry.getType()].call(this, feature, geometry); } - var map = this.getMap(); + const map = this.getMap(); if (map && map.isRendered() && this.getActive()) { this.handlePointerAtPixel_(this.lastPixel_, map); } _ol_events_.listen(feature, EventType.CHANGE, - this.handleFeatureChange_, this); + this.handleFeatureChange_, this); }; @@ -269,7 +269,7 @@ Modify.prototype.willModifyFeatures_ = function(evt) { if (!this.modified_) { this.modified_ = true; this.dispatchEvent(new Modify.Event( - ModifyEventType.MODIFYSTART, this.features_, evt)); + ModifyEventType.MODIFYSTART, this.features_, evt)); } }; @@ -287,7 +287,7 @@ Modify.prototype.removeFeature_ = function(feature) { this.vertexFeature_ = null; } _ol_events_.unlisten(feature, EventType.CHANGE, - this.handleFeatureChange_, this); + this.handleFeatureChange_, this); }; @@ -296,18 +296,18 @@ Modify.prototype.removeFeature_ = function(feature) { * @private */ Modify.prototype.removeFeatureSegmentData_ = function(feature) { - var rBush = this.rBush_; - var /** @type {Array.} */ nodesToRemove = []; + const rBush = this.rBush_; + const /** @type {Array.} */ nodesToRemove = []; rBush.forEach( - /** + /** * @param {ol.ModifySegmentDataType} node RTree node. */ - function(node) { - if (feature === node.feature) { - nodesToRemove.push(node); - } - }); - for (var i = nodesToRemove.length - 1; i >= 0; --i) { + function(node) { + if (feature === node.feature) { + nodesToRemove.push(node); + } + }); + for (let i = nodesToRemove.length - 1; i >= 0; --i) { rBush.remove(nodesToRemove[i]); } }; @@ -371,7 +371,7 @@ Modify.prototype.handleFeatureAdd_ = function(evt) { */ Modify.prototype.handleFeatureChange_ = function(evt) { if (!this.changingFeature_) { - var feature = /** @type {ol.Feature} */ (evt.target); + const feature = /** @type {ol.Feature} */ (evt.target); this.removeFeature_(feature); this.addFeature_(feature); } @@ -383,7 +383,7 @@ Modify.prototype.handleFeatureChange_ = function(evt) { * @private */ Modify.prototype.handleFeatureRemove_ = function(evt) { - var feature = /** @type {ol.Feature} */ (evt.element); + const feature = /** @type {ol.Feature} */ (evt.element); this.removeFeature_(feature); }; @@ -394,8 +394,8 @@ Modify.prototype.handleFeatureRemove_ = function(evt) { * @private */ Modify.prototype.writePointGeometry_ = function(feature, geometry) { - var coordinates = geometry.getCoordinates(); - var segmentData = /** @type {ol.ModifySegmentDataType} */ ({ + const coordinates = geometry.getCoordinates(); + const segmentData = /** @type {ol.ModifySegmentDataType} */ ({ feature: feature, geometry: geometry, segment: [coordinates, coordinates] @@ -410,8 +410,8 @@ Modify.prototype.writePointGeometry_ = function(feature, geometry) { * @private */ Modify.prototype.writeMultiPointGeometry_ = function(feature, geometry) { - var points = geometry.getCoordinates(); - var coordinates, i, ii, segmentData; + const points = geometry.getCoordinates(); + let coordinates, i, ii, segmentData; for (i = 0, ii = points.length; i < ii; ++i) { coordinates = points[i]; segmentData = /** @type {ol.ModifySegmentDataType} */ ({ @@ -432,8 +432,8 @@ Modify.prototype.writeMultiPointGeometry_ = function(feature, geometry) { * @private */ Modify.prototype.writeLineStringGeometry_ = function(feature, geometry) { - var coordinates = geometry.getCoordinates(); - var i, ii, segment, segmentData; + const coordinates = geometry.getCoordinates(); + let i, ii, segment, segmentData; for (i = 0, ii = coordinates.length - 1; i < ii; ++i) { segment = coordinates.slice(i, i + 2); segmentData = /** @type {ol.ModifySegmentDataType} */ ({ @@ -453,8 +453,8 @@ Modify.prototype.writeLineStringGeometry_ = function(feature, geometry) { * @private */ Modify.prototype.writeMultiLineStringGeometry_ = function(feature, geometry) { - var lines = geometry.getCoordinates(); - var coordinates, i, ii, j, jj, segment, segmentData; + const lines = geometry.getCoordinates(); + let coordinates, i, ii, j, jj, segment, segmentData; for (j = 0, jj = lines.length; j < jj; ++j) { coordinates = lines[j]; for (i = 0, ii = coordinates.length - 1; i < ii; ++i) { @@ -478,8 +478,8 @@ Modify.prototype.writeMultiLineStringGeometry_ = function(feature, geometry) { * @private */ Modify.prototype.writePolygonGeometry_ = function(feature, geometry) { - var rings = geometry.getCoordinates(); - var coordinates, i, ii, j, jj, segment, segmentData; + const rings = geometry.getCoordinates(); + let coordinates, i, ii, j, jj, segment, segmentData; for (j = 0, jj = rings.length; j < jj; ++j) { coordinates = rings[j]; for (i = 0, ii = coordinates.length - 1; i < ii; ++i) { @@ -503,8 +503,8 @@ Modify.prototype.writePolygonGeometry_ = function(feature, geometry) { * @private */ Modify.prototype.writeMultiPolygonGeometry_ = function(feature, geometry) { - var polygons = geometry.getCoordinates(); - var coordinates, i, ii, j, jj, k, kk, rings, segment, segmentData; + const polygons = geometry.getCoordinates(); + let coordinates, i, ii, j, jj, k, kk, rings, segment, segmentData; for (k = 0, kk = polygons.length; k < kk; ++k) { rings = polygons[k]; for (j = 0, jj = rings.length; j < jj; ++j) { @@ -537,20 +537,20 @@ Modify.prototype.writeMultiPolygonGeometry_ = function(feature, geometry) { * @private */ Modify.prototype.writeCircleGeometry_ = function(feature, geometry) { - var coordinates = geometry.getCenter(); - var centerSegmentData = /** @type {ol.ModifySegmentDataType} */ ({ + const coordinates = geometry.getCenter(); + const centerSegmentData = /** @type {ol.ModifySegmentDataType} */ ({ feature: feature, geometry: geometry, index: Modify.MODIFY_SEGMENT_CIRCLE_CENTER_INDEX, segment: [coordinates, coordinates] }); - var circumferenceSegmentData = /** @type {ol.ModifySegmentDataType} */ ({ + const circumferenceSegmentData = /** @type {ol.ModifySegmentDataType} */ ({ feature: feature, geometry: geometry, index: Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX, segment: [coordinates, coordinates] }); - var featureSegments = [centerSegmentData, circumferenceSegmentData]; + const featureSegments = [centerSegmentData, circumferenceSegmentData]; centerSegmentData.featureSegments = circumferenceSegmentData.featureSegments = featureSegments; this.rBush_.insert(createOrUpdateFromCoordinate(coordinates), centerSegmentData); this.rBush_.insert(geometry.getExtent(), circumferenceSegmentData); @@ -563,10 +563,10 @@ Modify.prototype.writeCircleGeometry_ = function(feature, geometry) { * @private */ Modify.prototype.writeGeometryCollectionGeometry_ = function(feature, geometry) { - var i, geometries = geometry.getGeometriesArray(); - for (i = 0; i < geometries.length; ++i) { + const geometries = geometry.getGeometriesArray(); + for (let i = 0; i < geometries.length; ++i) { this.SEGMENT_WRITERS_[geometries[i].getType()].call( - this, feature, geometries[i]); + this, feature, geometries[i]); } }; @@ -577,13 +577,13 @@ Modify.prototype.writeGeometryCollectionGeometry_ = function(feature, geometry) * @private */ Modify.prototype.createOrUpdateVertexFeature_ = function(coordinates) { - var vertexFeature = this.vertexFeature_; + let vertexFeature = this.vertexFeature_; if (!vertexFeature) { vertexFeature = new Feature(new Point(coordinates)); this.vertexFeature_ = vertexFeature; this.overlay_.getSource().addFeature(vertexFeature); } else { - var geometry = /** @type {ol.geom.Point} */ (vertexFeature.getGeometry()); + const geometry = /** @type {ol.geom.Point} */ (vertexFeature.getGeometry()); geometry.setCoordinates(coordinates); } return vertexFeature; @@ -612,23 +612,23 @@ Modify.handleDownEvent_ = function(evt) { return false; } this.handlePointerAtPixel_(evt.pixel, evt.map); - var pixelCoordinate = evt.map.getCoordinateFromPixel(evt.pixel); + const pixelCoordinate = evt.map.getCoordinateFromPixel(evt.pixel); this.dragSegments_.length = 0; this.modified_ = false; - var vertexFeature = this.vertexFeature_; + const vertexFeature = this.vertexFeature_; if (vertexFeature) { - var insertVertices = []; - var geometry = /** @type {ol.geom.Point} */ (vertexFeature.getGeometry()); - var vertex = geometry.getCoordinates(); - var vertexExtent = boundingExtent([vertex]); - var segmentDataMatches = this.rBush_.getInExtent(vertexExtent); - var componentSegments = {}; + const insertVertices = []; + const geometry = /** @type {ol.geom.Point} */ (vertexFeature.getGeometry()); + const vertex = geometry.getCoordinates(); + const vertexExtent = boundingExtent([vertex]); + const segmentDataMatches = this.rBush_.getInExtent(vertexExtent); + const componentSegments = {}; segmentDataMatches.sort(Modify.compareIndexes_); - for (var i = 0, ii = segmentDataMatches.length; i < ii; ++i) { - var segmentDataMatch = segmentDataMatches[i]; - var segment = segmentDataMatch.segment; - var uid = getUid(segmentDataMatch.feature); - var depth = segmentDataMatch.depth; + for (let i = 0, ii = segmentDataMatches.length; i < ii; ++i) { + const segmentDataMatch = segmentDataMatches[i]; + const segment = segmentDataMatch.segment; + let uid = getUid(segmentDataMatch.feature); + const depth = segmentDataMatch.depth; if (depth) { uid += '-' + depth.join('-'); // separate feature components } @@ -638,7 +638,7 @@ Modify.handleDownEvent_ = function(evt) { if (segmentDataMatch.geometry.getType() === GeometryType.CIRCLE && segmentDataMatch.index === Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX) { - var closestVertex = Modify.closestOnSegmentData_(pixelCoordinate, segmentDataMatch); + const closestVertex = Modify.closestOnSegmentData_(pixelCoordinate, segmentDataMatch); if (_ol_coordinate_.equals(closestVertex, vertex) && !componentSegments[uid][0]) { this.dragSegments_.push([segmentDataMatch, 0]); componentSegments[uid][0] = segmentDataMatch; @@ -670,7 +670,7 @@ Modify.handleDownEvent_ = function(evt) { if (insertVertices.length) { this.willModifyFeatures_(evt); } - for (var j = insertVertices.length - 1; j >= 0; --j) { + for (let j = insertVertices.length - 1; j >= 0; --j) { this.insertVertex_.apply(this, insertVertices[j]); } } @@ -687,15 +687,15 @@ Modify.handleDragEvent_ = function(evt) { this.ignoreNextSingleClick_ = false; this.willModifyFeatures_(evt); - var vertex = evt.coordinate; - for (var i = 0, ii = this.dragSegments_.length; i < ii; ++i) { - var dragSegment = this.dragSegments_[i]; - var segmentData = dragSegment[0]; - var depth = segmentData.depth; - var geometry = segmentData.geometry; - var coordinates; - var segment = segmentData.segment; - var index = dragSegment[1]; + const vertex = evt.coordinate; + for (let i = 0, ii = this.dragSegments_.length; i < ii; ++i) { + const dragSegment = this.dragSegments_[i]; + const segmentData = dragSegment[0]; + const depth = segmentData.depth; + const geometry = segmentData.geometry; + let coordinates; + const segment = segmentData.segment; + const index = dragSegment[1]; while (vertex.length < geometry.getStride()) { vertex.push(segment[index][vertex.length]); @@ -762,28 +762,28 @@ Modify.handleDragEvent_ = function(evt) { * @private */ Modify.handleUpEvent_ = function(evt) { - var segmentData; - var geometry; - for (var i = this.dragSegments_.length - 1; i >= 0; --i) { + let segmentData; + let geometry; + for (let i = this.dragSegments_.length - 1; i >= 0; --i) { segmentData = this.dragSegments_[i][0]; geometry = segmentData.geometry; if (geometry.getType() === GeometryType.CIRCLE) { // Update a circle object in the R* bush: - var coordinates = geometry.getCenter(); - var centerSegmentData = segmentData.featureSegments[0]; - var circumferenceSegmentData = segmentData.featureSegments[1]; + const coordinates = geometry.getCenter(); + const centerSegmentData = segmentData.featureSegments[0]; + const circumferenceSegmentData = segmentData.featureSegments[1]; centerSegmentData.segment[0] = centerSegmentData.segment[1] = coordinates; circumferenceSegmentData.segment[0] = circumferenceSegmentData.segment[1] = coordinates; this.rBush_.update(createOrUpdateFromCoordinate(coordinates), centerSegmentData); this.rBush_.update(geometry.getExtent(), circumferenceSegmentData); } else { this.rBush_.update(boundingExtent(segmentData.segment), - segmentData); + segmentData); } } if (this.modified_) { this.dispatchEvent(new Modify.Event( - ModifyEventType.MODIFYEND, this.features_, evt)); + ModifyEventType.MODIFYEND, this.features_, evt)); this.modified_ = false; } return false; @@ -804,7 +804,7 @@ Modify.handleEvent = function(mapBrowserEvent) { } this.lastPointerEvent_ = mapBrowserEvent; - var handled; + let handled; if (!mapBrowserEvent.map.getView().getInteracting() && mapBrowserEvent.type == MapBrowserEventType.POINTERMOVE && !this.handlingDownUpSequence) { @@ -844,26 +844,26 @@ Modify.prototype.handlePointerMove_ = function(evt) { * @private */ Modify.prototype.handlePointerAtPixel_ = function(pixel, map) { - var pixelCoordinate = map.getCoordinateFromPixel(pixel); - var sortByDistance = function(a, b) { + const pixelCoordinate = map.getCoordinateFromPixel(pixel); + const sortByDistance = function(a, b) { return Modify.pointDistanceToSegmentDataSquared_(pixelCoordinate, a) - Modify.pointDistanceToSegmentDataSquared_(pixelCoordinate, b); }; - var box = buffer(createOrUpdateFromCoordinate(pixelCoordinate), - map.getView().getResolution() * this.pixelTolerance_); + const box = buffer(createOrUpdateFromCoordinate(pixelCoordinate), + map.getView().getResolution() * this.pixelTolerance_); - var rBush = this.rBush_; - var nodes = rBush.getInExtent(box); + const rBush = this.rBush_; + const nodes = rBush.getInExtent(box); if (nodes.length > 0) { nodes.sort(sortByDistance); - var node = nodes[0]; - var closestSegment = node.segment; - var vertex = Modify.closestOnSegmentData_(pixelCoordinate, node); - var vertexPixel = map.getPixelFromCoordinate(vertex); - var dist = _ol_coordinate_.distance(pixel, vertexPixel); + const node = nodes[0]; + const closestSegment = node.segment; + let vertex = Modify.closestOnSegmentData_(pixelCoordinate, node); + const vertexPixel = map.getPixelFromCoordinate(vertex); + let dist = _ol_coordinate_.distance(pixel, vertexPixel); if (dist <= this.pixelTolerance_) { - var vertexSegments = {}; + const vertexSegments = {}; if (node.geometry.getType() === GeometryType.CIRCLE && node.index === Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX) { @@ -871,10 +871,10 @@ Modify.prototype.handlePointerAtPixel_ = function(pixel, map) { this.snappedToVertex_ = true; this.createOrUpdateVertexFeature_(vertex); } else { - var pixel1 = map.getPixelFromCoordinate(closestSegment[0]); - var pixel2 = map.getPixelFromCoordinate(closestSegment[1]); - var squaredDist1 = _ol_coordinate_.squaredDistance(vertexPixel, pixel1); - var squaredDist2 = _ol_coordinate_.squaredDistance(vertexPixel, pixel2); + const pixel1 = map.getPixelFromCoordinate(closestSegment[0]); + const pixel2 = map.getPixelFromCoordinate(closestSegment[1]); + const squaredDist1 = _ol_coordinate_.squaredDistance(vertexPixel, pixel1); + const squaredDist2 = _ol_coordinate_.squaredDistance(vertexPixel, pixel2); dist = Math.sqrt(Math.min(squaredDist1, squaredDist2)); this.snappedToVertex_ = dist <= this.pixelTolerance_; if (this.snappedToVertex_) { @@ -882,8 +882,8 @@ Modify.prototype.handlePointerAtPixel_ = function(pixel, map) { closestSegment[1] : closestSegment[0]; } this.createOrUpdateVertexFeature_(vertex); - var segment; - for (var i = 1, ii = nodes.length; i < ii; ++i) { + let segment; + for (let i = 1, ii = nodes.length; i < ii; ++i) { segment = nodes[i].segment; if ((_ol_coordinate_.equals(closestSegment[0], segment[0]) && _ol_coordinate_.equals(closestSegment[1], segment[1]) || @@ -918,15 +918,15 @@ Modify.prototype.handlePointerAtPixel_ = function(pixel, map) { * @return {number} The square of the distance between a point and a line segment. */ Modify.pointDistanceToSegmentDataSquared_ = function(pointCoordinates, segmentData) { - var geometry = segmentData.geometry; + const geometry = segmentData.geometry; if (geometry.getType() === GeometryType.CIRCLE) { - var circleGeometry = /** @type {ol.geom.Circle} */ (geometry); + const circleGeometry = /** @type {ol.geom.Circle} */ (geometry); if (segmentData.index === Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX) { - var distanceToCenterSquared = + const distanceToCenterSquared = _ol_coordinate_.squaredDistance(circleGeometry.getCenter(), pointCoordinates); - var distanceToCircumference = + const distanceToCircumference = Math.sqrt(distanceToCenterSquared) - circleGeometry.getRadius(); return distanceToCircumference * distanceToCircumference; } @@ -944,7 +944,7 @@ Modify.pointDistanceToSegmentDataSquared_ = function(pointCoordinates, segmentDa * @return {ol.Coordinate} The point closest to the specified line segment. */ Modify.closestOnSegmentData_ = function(pointCoordinates, segmentData) { - var geometry = segmentData.geometry; + const geometry = segmentData.geometry; if (geometry.getType() === GeometryType.CIRCLE && segmentData.index === Modify.MODIFY_SEGMENT_CIRCLE_CIRCUMFERENCE_INDEX) { @@ -960,12 +960,12 @@ Modify.closestOnSegmentData_ = function(pointCoordinates, segmentData) { * @private */ Modify.prototype.insertVertex_ = function(segmentData, vertex) { - var segment = segmentData.segment; - var feature = segmentData.feature; - var geometry = segmentData.geometry; - var depth = segmentData.depth; - var index = /** @type {number} */ (segmentData.index); - var coordinates; + const segment = segmentData.segment; + const feature = segmentData.feature; + const geometry = segmentData.geometry; + const depth = segmentData.depth; + const index = /** @type {number} */ (segmentData.index); + let coordinates; while (vertex.length < geometry.getStride()) { vertex.push(0); @@ -993,10 +993,10 @@ Modify.prototype.insertVertex_ = function(segmentData, vertex) { } this.setGeometryCoordinates_(geometry, coordinates); - var rTree = this.rBush_; + const rTree = this.rBush_; rTree.remove(segmentData); this.updateSegmentIndices_(geometry, index, depth, 1); - var newSegmentData = /** @type {ol.ModifySegmentDataType} */ ({ + const newSegmentData = /** @type {ol.ModifySegmentDataType} */ ({ segment: [segment[0], vertex], feature: feature, geometry: geometry, @@ -1004,10 +1004,10 @@ Modify.prototype.insertVertex_ = function(segmentData, vertex) { index: index }); rTree.insert(boundingExtent(newSegmentData.segment), - newSegmentData); + newSegmentData); this.dragSegments_.push([newSegmentData, 1]); - var newSegmentData2 = /** @type {ol.ModifySegmentDataType} */ ({ + const newSegmentData2 = /** @type {ol.ModifySegmentDataType} */ ({ segment: [vertex, segment[1]], feature: feature, geometry: geometry, @@ -1015,7 +1015,7 @@ Modify.prototype.insertVertex_ = function(segmentData, vertex) { index: index + 1 }); rTree.insert(boundingExtent(newSegmentData2.segment), - newSegmentData2); + newSegmentData2); this.dragSegments_.push([newSegmentData2, 0]); this.ignoreNextSingleClick_ = true; }; @@ -1027,11 +1027,11 @@ Modify.prototype.insertVertex_ = function(segmentData, vertex) { */ Modify.prototype.removePoint = function() { if (this.lastPointerEvent_ && this.lastPointerEvent_.type != MapBrowserEventType.POINTERDRAG) { - var evt = this.lastPointerEvent_; + const evt = this.lastPointerEvent_; this.willModifyFeatures_(evt); this.removeVertex_(); this.dispatchEvent(new Modify.Event( - ModifyEventType.MODIFYEND, this.features_, evt)); + ModifyEventType.MODIFYEND, this.features_, evt)); this.modified_ = false; return true; } @@ -1044,11 +1044,11 @@ Modify.prototype.removePoint = function() { * @private */ Modify.prototype.removeVertex_ = function() { - var dragSegments = this.dragSegments_; - var segmentsByFeature = {}; - var deleted = false; - var component, coordinates, dragSegment, geometry, i, index, left; - var newIndex, right, segmentData, uid; + const dragSegments = this.dragSegments_; + const segmentsByFeature = {}; + let deleted = false; + let component, coordinates, dragSegment, geometry, i, index, left; + let newIndex, right, segmentData, uid; for (i = dragSegments.length - 1; i >= 0; --i) { dragSegment = dragSegments[i]; segmentData = dragSegment[0]; @@ -1124,7 +1124,7 @@ Modify.prototype.removeVertex_ = function() { if (deleted) { this.setGeometryCoordinates_(geometry, coordinates); - var segments = []; + const segments = []; if (left !== undefined) { this.rBush_.remove(left); segments.push(left.segment[0]); @@ -1134,7 +1134,7 @@ Modify.prototype.removeVertex_ = function() { segments.push(right.segment[1]); } if (left !== undefined && right !== undefined) { - var newSegmentData = /** @type {ol.ModifySegmentDataType} */ ({ + const newSegmentData = /** @type {ol.ModifySegmentDataType} */ ({ depth: segmentData.depth, feature: segmentData.feature, geometry: segmentData.geometry, @@ -1142,7 +1142,7 @@ Modify.prototype.removeVertex_ = function() { segment: segments }); this.rBush_.insert(boundingExtent(newSegmentData.segment), - newSegmentData); + newSegmentData); } this.updateSegmentIndices_(geometry, index, segmentData.depth, -1); if (this.vertexFeature_) { @@ -1177,7 +1177,7 @@ Modify.prototype.setGeometryCoordinates_ = function(geometry, coordinates) { * @private */ Modify.prototype.updateSegmentIndices_ = function( - geometry, index, depth, delta) { + geometry, index, depth, delta) { this.rBush_.forEachInExtent(geometry.getExtent(), function(segmentDataMatch) { if (segmentDataMatch.geometry === geometry && (depth === undefined || segmentDataMatch.depth === undefined || @@ -1193,7 +1193,7 @@ Modify.prototype.updateSegmentIndices_ = function( * @return {ol.StyleFunction} Styles. */ Modify.getDefaultStyleFunction = function() { - var style = Style.createDefaultEditing(); + const style = Style.createDefaultEditing(); return function(feature, resolution) { return style[GeometryType.POINT]; }; diff --git a/src/ol/interaction/MouseWheelZoom.js b/src/ol/interaction/MouseWheelZoom.js index f0c771d3a0..020b5a29fc 100644 --- a/src/ol/interaction/MouseWheelZoom.js +++ b/src/ol/interaction/MouseWheelZoom.js @@ -14,7 +14,7 @@ import {clamp} from '../math.js'; /** * @type {number} Maximum mouse wheel delta. */ -var MAX_DELTA = 1; +const MAX_DELTA = 1; /** @@ -26,13 +26,13 @@ var MAX_DELTA = 1; * @param {olx.interaction.MouseWheelZoomOptions=} opt_options Options. * @api */ -var MouseWheelZoom = function(opt_options) { +const MouseWheelZoom = function(opt_options) { Interaction.call(this, { handleEvent: MouseWheelZoom.handleEvent }); - var options = opt_options || {}; + const options = opt_options || {}; /** * @private @@ -137,15 +137,15 @@ MouseWheelZoom.handleEvent = function(mapBrowserEvent) { if (!this.condition_(mapBrowserEvent)) { return true; } - var type = mapBrowserEvent.type; + const type = mapBrowserEvent.type; if (type !== EventType.WHEEL && type !== EventType.MOUSEWHEEL) { return true; } mapBrowserEvent.preventDefault(); - var map = mapBrowserEvent.map; - var wheelEvent = /** @type {WheelEvent} */ (mapBrowserEvent.originalEvent); + const map = mapBrowserEvent.map; + const wheelEvent = /** @type {WheelEvent} */ (mapBrowserEvent.originalEvent); if (this.useAnchor_) { this.lastAnchor_ = mapBrowserEvent.coordinate; @@ -153,7 +153,7 @@ MouseWheelZoom.handleEvent = function(mapBrowserEvent) { // Delta normalisation inspired by // https://github.com/mapbox/mapbox-gl-js/blob/001c7b9/js/ui/handler/scroll_zoom.js - var delta; + let delta; if (mapBrowserEvent.type == EventType.WHEEL) { delta = wheelEvent.deltaY; if (_ol_has_.FIREFOX && @@ -174,7 +174,7 @@ MouseWheelZoom.handleEvent = function(mapBrowserEvent) { return false; } - var now = Date.now(); + const now = Date.now(); if (this.startTime_ === undefined) { this.startTime_ = now; @@ -187,17 +187,17 @@ MouseWheelZoom.handleEvent = function(mapBrowserEvent) { } if (this.mode_ === MouseWheelZoom.Mode_.TRACKPAD) { - var view = map.getView(); + const view = map.getView(); if (this.trackpadTimeoutId_) { clearTimeout(this.trackpadTimeoutId_); } else { view.setHint(ViewHint.INTERACTING, 1); } this.trackpadTimeoutId_ = setTimeout(this.decrementInteractingHint_.bind(this), this.trackpadEventGap_); - var resolution = view.getResolution() * Math.pow(2, delta / this.trackpadDeltaPerZoom_); - var minResolution = view.getMinResolution(); - var maxResolution = view.getMaxResolution(); - var rebound = 0; + let resolution = view.getResolution() * Math.pow(2, delta / this.trackpadDeltaPerZoom_); + const minResolution = view.getMinResolution(); + const maxResolution = view.getMaxResolution(); + let rebound = 0; if (resolution < minResolution) { resolution = Math.max(resolution, minResolution / this.trackpadZoomBuffer_); rebound = 1; @@ -206,7 +206,7 @@ MouseWheelZoom.handleEvent = function(mapBrowserEvent) { rebound = -1; } if (this.lastAnchor_) { - var center = view.calculateCenterZoom(resolution, this.lastAnchor_); + const center = view.calculateCenterZoom(resolution, this.lastAnchor_); view.setCenter(view.constrainCenter(center)); } view.setResolution(resolution); @@ -241,7 +241,7 @@ MouseWheelZoom.handleEvent = function(mapBrowserEvent) { this.delta_ += delta; - var timeLeft = Math.max(this.timeout_ - (now - this.startTime_), 0); + const timeLeft = Math.max(this.timeout_ - (now - this.startTime_), 0); clearTimeout(this.timeoutId_); this.timeoutId_ = setTimeout(this.handleWheelZoom_.bind(this, map), timeLeft); @@ -255,7 +255,7 @@ MouseWheelZoom.handleEvent = function(mapBrowserEvent) { */ MouseWheelZoom.prototype.decrementInteractingHint_ = function() { this.trackpadTimeoutId_ = undefined; - var view = this.getMap().getView(); + const view = this.getMap().getView(); view.setHint(ViewHint.INTERACTING, -1); }; @@ -265,14 +265,14 @@ MouseWheelZoom.prototype.decrementInteractingHint_ = function() { * @param {ol.PluggableMap} map Map. */ MouseWheelZoom.prototype.handleWheelZoom_ = function(map) { - var view = map.getView(); + const view = map.getView(); if (view.getAnimating()) { view.cancelAnimations(); } - var maxDelta = MAX_DELTA; - var delta = clamp(this.delta_, -maxDelta, maxDelta); + const maxDelta = MAX_DELTA; + const delta = clamp(this.delta_, -maxDelta, maxDelta); Interaction.zoomByDelta(view, -delta, this.lastAnchor_, - this.duration_); + this.duration_); this.mode_ = undefined; this.delta_ = 0; this.lastAnchor_ = null; diff --git a/src/ol/interaction/PinchRotate.js b/src/ol/interaction/PinchRotate.js index e9ae3c6c48..83803c0e41 100644 --- a/src/ol/interaction/PinchRotate.js +++ b/src/ol/interaction/PinchRotate.js @@ -18,7 +18,7 @@ import RotationConstraint from '../RotationConstraint.js'; * @param {olx.interaction.PinchRotateOptions=} opt_options Options. * @api */ -var PinchRotate = function(opt_options) { +const PinchRotate = function(opt_options) { PointerInteraction.call(this, { handleDownEvent: PinchRotate.handleDownEvent_, @@ -26,7 +26,7 @@ var PinchRotate = function(opt_options) { handleUpEvent: PinchRotate.handleUpEvent_ }); - var options = opt_options || {}; + const options = opt_options || {}; /** * @private @@ -75,18 +75,18 @@ inherits(PinchRotate, PointerInteraction); * @private */ PinchRotate.handleDragEvent_ = function(mapBrowserEvent) { - var rotationDelta = 0.0; + let rotationDelta = 0.0; - var touch0 = this.targetPointers[0]; - var touch1 = this.targetPointers[1]; + const touch0 = this.targetPointers[0]; + const touch1 = this.targetPointers[1]; // angle between touches - var angle = Math.atan2( - touch1.clientY - touch0.clientY, - touch1.clientX - touch0.clientX); + const angle = Math.atan2( + touch1.clientY - touch0.clientY, + touch1.clientX - touch0.clientX); if (this.lastAngle_ !== undefined) { - var delta = angle - this.lastAngle_; + const delta = angle - this.lastAngle_; this.rotationDelta_ += delta; if (!this.rotating_ && Math.abs(this.rotationDelta_) > this.threshold_) { @@ -96,8 +96,8 @@ PinchRotate.handleDragEvent_ = function(mapBrowserEvent) { } this.lastAngle_ = angle; - var map = mapBrowserEvent.map; - var view = map.getView(); + const map = mapBrowserEvent.map; + const view = map.getView(); if (view.getConstraints().rotation === RotationConstraint.disable) { return; } @@ -105,18 +105,18 @@ PinchRotate.handleDragEvent_ = function(mapBrowserEvent) { // rotate anchor point. // FIXME: should be the intersection point between the lines: // touch0,touch1 and previousTouch0,previousTouch1 - var viewportPosition = map.getViewport().getBoundingClientRect(); - var centroid = PointerInteraction.centroid(this.targetPointers); + const viewportPosition = map.getViewport().getBoundingClientRect(); + const centroid = PointerInteraction.centroid(this.targetPointers); centroid[0] -= viewportPosition.left; centroid[1] -= viewportPosition.top; this.anchor_ = map.getCoordinateFromPixel(centroid); // rotate if (this.rotating_) { - var rotation = view.getRotation(); + const rotation = view.getRotation(); map.render(); Interaction.rotateWithoutConstraints(view, - rotation + rotationDelta, this.anchor_); + rotation + rotationDelta, this.anchor_); } }; @@ -129,13 +129,13 @@ PinchRotate.handleDragEvent_ = function(mapBrowserEvent) { */ PinchRotate.handleUpEvent_ = function(mapBrowserEvent) { if (this.targetPointers.length < 2) { - var map = mapBrowserEvent.map; - var view = map.getView(); + const map = mapBrowserEvent.map; + const view = map.getView(); view.setHint(ViewHint.INTERACTING, -1); if (this.rotating_) { - var rotation = view.getRotation(); + const rotation = view.getRotation(); Interaction.rotate( - view, rotation, this.anchor_, this.duration_); + view, rotation, this.anchor_, this.duration_); } return false; } else { @@ -152,7 +152,7 @@ PinchRotate.handleUpEvent_ = function(mapBrowserEvent) { */ PinchRotate.handleDownEvent_ = function(mapBrowserEvent) { if (this.targetPointers.length >= 2) { - var map = mapBrowserEvent.map; + const map = mapBrowserEvent.map; this.anchor_ = null; this.lastAngle_ = undefined; this.rotating_ = false; diff --git a/src/ol/interaction/PinchZoom.js b/src/ol/interaction/PinchZoom.js index 9d75905918..12b3c8a19d 100644 --- a/src/ol/interaction/PinchZoom.js +++ b/src/ol/interaction/PinchZoom.js @@ -17,7 +17,7 @@ import PointerInteraction from '../interaction/Pointer.js'; * @param {olx.interaction.PinchZoomOptions=} opt_options Options. * @api */ -var PinchZoom = function(opt_options) { +const PinchZoom = function(opt_options) { PointerInteraction.call(this, { handleDownEvent: PinchZoom.handleDownEvent_, @@ -25,7 +25,7 @@ var PinchZoom = function(opt_options) { handleUpEvent: PinchZoom.handleUpEvent_ }); - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @private @@ -68,15 +68,15 @@ inherits(PinchZoom, PointerInteraction); * @private */ PinchZoom.handleDragEvent_ = function(mapBrowserEvent) { - var scaleDelta = 1.0; + let scaleDelta = 1.0; - var touch0 = this.targetPointers[0]; - var touch1 = this.targetPointers[1]; - var dx = touch0.clientX - touch1.clientX; - var dy = touch0.clientY - touch1.clientY; + const touch0 = this.targetPointers[0]; + const touch1 = this.targetPointers[1]; + const dx = touch0.clientX - touch1.clientX; + const dy = touch0.clientY - touch1.clientY; // distance between touches - var distance = Math.sqrt(dx * dx + dy * dy); + const distance = Math.sqrt(dx * dx + dy * dy); if (this.lastDistance_ !== undefined) { scaleDelta = this.lastDistance_ / distance; @@ -84,12 +84,12 @@ PinchZoom.handleDragEvent_ = function(mapBrowserEvent) { this.lastDistance_ = distance; - var map = mapBrowserEvent.map; - var view = map.getView(); - var resolution = view.getResolution(); - var maxResolution = view.getMaxResolution(); - var minResolution = view.getMinResolution(); - var newResolution = resolution * scaleDelta; + const map = mapBrowserEvent.map; + const view = map.getView(); + const resolution = view.getResolution(); + const maxResolution = view.getMaxResolution(); + const minResolution = view.getMinResolution(); + let newResolution = resolution * scaleDelta; if (newResolution > maxResolution) { scaleDelta = maxResolution / resolution; newResolution = maxResolution; @@ -103,8 +103,8 @@ PinchZoom.handleDragEvent_ = function(mapBrowserEvent) { } // scale anchor point. - var viewportPosition = map.getViewport().getBoundingClientRect(); - var centroid = PointerInteraction.centroid(this.targetPointers); + const viewportPosition = map.getViewport().getBoundingClientRect(); + const centroid = PointerInteraction.centroid(this.targetPointers); centroid[0] -= viewportPosition.left; centroid[1] -= viewportPosition.top; this.anchor_ = map.getCoordinateFromPixel(centroid); @@ -123,19 +123,19 @@ PinchZoom.handleDragEvent_ = function(mapBrowserEvent) { */ PinchZoom.handleUpEvent_ = function(mapBrowserEvent) { if (this.targetPointers.length < 2) { - var map = mapBrowserEvent.map; - var view = map.getView(); + const map = mapBrowserEvent.map; + const view = map.getView(); view.setHint(ViewHint.INTERACTING, -1); - var resolution = view.getResolution(); + const resolution = view.getResolution(); if (this.constrainResolution_ || resolution < view.getMinResolution() || resolution > view.getMaxResolution()) { // Zoom to final resolution, with an animation, and provide a // direction not to zoom out/in if user was pinching in/out. // Direction is > 0 if pinching out, and < 0 if pinching in. - var direction = this.lastScaleDelta_ - 1; + const direction = this.lastScaleDelta_ - 1; Interaction.zoom(view, resolution, - this.anchor_, this.duration_, direction); + this.anchor_, this.duration_, direction); } return false; } else { @@ -152,7 +152,7 @@ PinchZoom.handleUpEvent_ = function(mapBrowserEvent) { */ PinchZoom.handleDownEvent_ = function(mapBrowserEvent) { if (this.targetPointers.length >= 2) { - var map = mapBrowserEvent.map; + const map = mapBrowserEvent.map; this.anchor_ = null; this.lastDistance_ = undefined; this.lastScaleDelta_ = 1; diff --git a/src/ol/interaction/Pointer.js b/src/ol/interaction/Pointer.js index 12782bd0bb..93e3abf9ac 100644 --- a/src/ol/interaction/Pointer.js +++ b/src/ol/interaction/Pointer.js @@ -23,11 +23,11 @@ import _ol_obj_ from '../obj.js'; * @extends {ol.interaction.Interaction} * @api */ -var PointerInteraction = function(opt_options) { +const PointerInteraction = function(opt_options) { - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; - var handleEvent = options.handleEvent ? + const handleEvent = options.handleEvent ? options.handleEvent : PointerInteraction.handleEvent; Interaction.call(this, { @@ -90,10 +90,10 @@ inherits(PointerInteraction, Interaction); * @return {ol.Pixel} Centroid pixel. */ PointerInteraction.centroid = function(pointerEvents) { - var length = pointerEvents.length; - var clientX = 0; - var clientY = 0; - for (var i = 0; i < length; i++) { + const length = pointerEvents.length; + let clientX = 0; + let clientY = 0; + for (let i = 0; i < length; i++) { clientX += pointerEvents[i].clientX; clientY += pointerEvents[i].clientY; } @@ -108,7 +108,7 @@ PointerInteraction.centroid = function(pointerEvents) { * @private */ PointerInteraction.prototype.isPointerDraggingEvent_ = function(mapBrowserEvent) { - var type = mapBrowserEvent.type; + const type = mapBrowserEvent.type; return type === MapBrowserEventType.POINTERDOWN || type === MapBrowserEventType.POINTERDRAG || type === MapBrowserEventType.POINTERUP; @@ -121,9 +121,9 @@ PointerInteraction.prototype.isPointerDraggingEvent_ = function(mapBrowserEvent) */ PointerInteraction.prototype.updateTrackedPointers_ = function(mapBrowserEvent) { if (this.isPointerDraggingEvent_(mapBrowserEvent)) { - var event = mapBrowserEvent.pointerEvent; + const event = mapBrowserEvent.pointerEvent; - var id = event.pointerId.toString(); + const id = event.pointerId.toString(); if (mapBrowserEvent.type == MapBrowserEventType.POINTERUP) { delete this.trackedPointers_[id]; } else if (mapBrowserEvent.type == @@ -182,18 +182,18 @@ PointerInteraction.handleEvent = function(mapBrowserEvent) { return true; } - var stopEvent = false; + let stopEvent = false; this.updateTrackedPointers_(mapBrowserEvent); if (this.handlingDownUpSequence) { if (mapBrowserEvent.type == MapBrowserEventType.POINTERDRAG) { this.handleDragEvent_(mapBrowserEvent); } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERUP) { - var handledUp = this.handleUpEvent_(mapBrowserEvent); + const handledUp = this.handleUpEvent_(mapBrowserEvent); this.handlingDownUpSequence = handledUp && this.targetPointers.length > 0; } } else { if (mapBrowserEvent.type == MapBrowserEventType.POINTERDOWN) { - var handled = this.handleDownEvent_(mapBrowserEvent); + const handled = this.handleDownEvent_(mapBrowserEvent); this.handlingDownUpSequence = handled; stopEvent = this.shouldStopEvent(handled); } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERMOVE) { diff --git a/src/ol/interaction/Select.js b/src/ol/interaction/Select.js index 2cd9d10a5f..041283a962 100644 --- a/src/ol/interaction/Select.js +++ b/src/ol/interaction/Select.js @@ -33,13 +33,13 @@ import Style from '../style/Style.js'; * @fires ol.interaction.Select.Event * @api */ -var Select = function(opt_options) { +const Select = function(opt_options) { Interaction.call(this, { handleEvent: Select.handleEvent }); - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @private @@ -87,7 +87,7 @@ var Select = function(opt_options) { */ this.hitTolerance_ = options.hitTolerance ? options.hitTolerance : 0; - var featureOverlay = new VectorLayer({ + const featureOverlay = new VectorLayer({ source: new VectorSource({ useSpatialIndex: false, features: options.features, @@ -106,12 +106,12 @@ var Select = function(opt_options) { this.featureOverlay_ = featureOverlay; /** @type {function(ol.layer.Layer): boolean} */ - var layerFilter; + let layerFilter; if (options.layers) { if (typeof options.layers === 'function') { layerFilter = options.layers; } else { - var layers = options.layers; + const layers = options.layers; layerFilter = function(layer) { return includes(layers, layer); }; @@ -134,11 +134,11 @@ var Select = function(opt_options) { */ this.featureLayerAssociation_ = {}; - var features = this.featureOverlay_.getSource().getFeaturesCollection(); + const features = this.featureOverlay_.getSource().getFeaturesCollection(); _ol_events_.listen(features, CollectionEventType.ADD, - this.addFeature_, this); + this.addFeature_, this); _ol_events_.listen(features, CollectionEventType.REMOVE, - this.removeFeature_, this); + this.removeFeature_, this); }; @@ -151,7 +151,7 @@ inherits(Select, Interaction); * @private */ Select.prototype.addFeatureLayerAssociation_ = function(feature, layer) { - var key = getUid(feature); + const key = getUid(feature); this.featureLayerAssociation_[key] = layer; }; @@ -186,7 +186,7 @@ Select.prototype.getHitTolerance = function() { * @api */ Select.prototype.getLayer = function(feature) { - var key = getUid(feature); + const key = getUid(feature); return /** @type {ol.layer.Vector} */ (this.featureLayerAssociation_[key]); }; @@ -203,40 +203,40 @@ Select.handleEvent = function(mapBrowserEvent) { if (!this.condition_(mapBrowserEvent)) { return true; } - var add = this.addCondition_(mapBrowserEvent); - var remove = this.removeCondition_(mapBrowserEvent); - var toggle = this.toggleCondition_(mapBrowserEvent); - var set = !add && !remove && !toggle; - var map = mapBrowserEvent.map; - var features = this.featureOverlay_.getSource().getFeaturesCollection(); - var deselected = []; - var selected = []; + const add = this.addCondition_(mapBrowserEvent); + const remove = this.removeCondition_(mapBrowserEvent); + const toggle = this.toggleCondition_(mapBrowserEvent); + const set = !add && !remove && !toggle; + const map = mapBrowserEvent.map; + const features = this.featureOverlay_.getSource().getFeaturesCollection(); + const deselected = []; + const selected = []; if (set) { // Replace the currently selected feature(s) with the feature(s) at the // pixel, or clear the selected feature(s) if there is no feature at // the pixel. _ol_obj_.clear(this.featureLayerAssociation_); map.forEachFeatureAtPixel(mapBrowserEvent.pixel, - ( - /** + ( + /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @param {ol.layer.Layer} layer Layer. * @return {boolean|undefined} Continue to iterate over the features. */ - function(feature, layer) { - if (this.filter_(feature, layer)) { - selected.push(feature); - this.addFeatureLayerAssociation_(feature, layer); - return !this.multi_; - } - }).bind(this), { - layerFilter: this.layerFilter_, - hitTolerance: this.hitTolerance_ - }); - var i; + function(feature, layer) { + if (this.filter_(feature, layer)) { + selected.push(feature); + this.addFeatureLayerAssociation_(feature, layer); + return !this.multi_; + } + }).bind(this), { + layerFilter: this.layerFilter_, + hitTolerance: this.hitTolerance_ + }); + let i; for (i = features.getLength() - 1; i >= 0; --i) { - var feature = features.item(i); - var index = selected.indexOf(feature); + const feature = features.item(i); + const index = selected.indexOf(feature); if (index > -1) { // feature is already selected selected.splice(index, 1); @@ -251,28 +251,28 @@ Select.handleEvent = function(mapBrowserEvent) { } else { // Modify the currently selected feature(s). map.forEachFeatureAtPixel(mapBrowserEvent.pixel, - ( - /** + ( + /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @param {ol.layer.Layer} layer Layer. * @return {boolean|undefined} Continue to iterate over the features. */ - function(feature, layer) { - if (this.filter_(feature, layer)) { - if ((add || toggle) && !includes(features.getArray(), feature)) { - selected.push(feature); - this.addFeatureLayerAssociation_(feature, layer); - } else if ((remove || toggle) && includes(features.getArray(), feature)) { - deselected.push(feature); - this.removeFeatureLayerAssociation_(feature); - } - return !this.multi_; + function(feature, layer) { + if (this.filter_(feature, layer)) { + if ((add || toggle) && !includes(features.getArray(), feature)) { + selected.push(feature); + this.addFeatureLayerAssociation_(feature, layer); + } else if ((remove || toggle) && includes(features.getArray(), feature)) { + deselected.push(feature); + this.removeFeatureLayerAssociation_(feature); } - }).bind(this), { - layerFilter: this.layerFilter_, - hitTolerance: this.hitTolerance_ - }); - var j; + return !this.multi_; + } + }).bind(this), { + layerFilter: this.layerFilter_, + hitTolerance: this.hitTolerance_ + }); + let j; for (j = deselected.length - 1; j >= 0; --j) { features.remove(deselected[j]); } @@ -280,8 +280,8 @@ Select.handleEvent = function(mapBrowserEvent) { } if (selected.length > 0 || deselected.length > 0) { this.dispatchEvent( - new Select.Event(Select.EventType_.SELECT, - selected, deselected, mapBrowserEvent)); + new Select.Event(Select.EventType_.SELECT, + selected, deselected, mapBrowserEvent)); } return _ol_events_condition_.pointerMove(mapBrowserEvent); }; @@ -307,8 +307,8 @@ Select.prototype.setHitTolerance = function(hitTolerance) { * @api */ Select.prototype.setMap = function(map) { - var currentMap = this.getMap(); - var selectedFeatures = + const currentMap = this.getMap(); + const selectedFeatures = this.featureOverlay_.getSource().getFeaturesCollection(); if (currentMap) { selectedFeatures.forEach(currentMap.unskipFeature.bind(currentMap)); @@ -325,7 +325,7 @@ Select.prototype.setMap = function(map) { * @return {ol.StyleFunction} Styles. */ Select.getDefaultStyleFunction = function() { - var styles = Style.createDefaultEditing(); + const styles = Style.createDefaultEditing(); extend(styles[GeometryType.POLYGON], styles[GeometryType.LINE_STRING]); extend(styles[GeometryType.GEOMETRY_COLLECTION], styles[GeometryType.LINE_STRING]); @@ -343,7 +343,7 @@ Select.getDefaultStyleFunction = function() { * @private */ Select.prototype.addFeature_ = function(evt) { - var map = this.getMap(); + const map = this.getMap(); if (map) { map.skipFeature(/** @type {ol.Feature} */ (evt.element)); } @@ -355,7 +355,7 @@ Select.prototype.addFeature_ = function(evt) { * @private */ Select.prototype.removeFeature_ = function(evt) { - var map = this.getMap(); + const map = this.getMap(); if (map) { map.unskipFeature(/** @type {ol.Feature} */ (evt.element)); } @@ -367,7 +367,7 @@ Select.prototype.removeFeature_ = function(evt) { * @private */ Select.prototype.removeFeatureLayerAssociation_ = function(feature) { - var key = getUid(feature); + const key = getUid(feature); delete this.featureLayerAssociation_[key]; }; diff --git a/src/ol/interaction/Snap.js b/src/ol/interaction/Snap.js index 19ea695606..aafdca67ae 100644 --- a/src/ol/interaction/Snap.js +++ b/src/ol/interaction/Snap.js @@ -39,7 +39,7 @@ import RBush from '../structs/RBush.js'; * @param {olx.interaction.SnapOptions=} opt_options Options. * @api */ -var Snap = function(opt_options) { +const Snap = function(opt_options) { PointerInteraction.call(this, { handleEvent: Snap.handleEvent_, @@ -47,7 +47,7 @@ var Snap = function(opt_options) { handleUpEvent: Snap.handleUpEvent_ }); - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * @type {ol.source.Vector} @@ -160,11 +160,11 @@ inherits(Snap, PointerInteraction); * @api */ Snap.prototype.addFeature = function(feature, opt_listen) { - var listen = opt_listen !== undefined ? opt_listen : true; - var feature_uid = getUid(feature); - var geometry = feature.getGeometry(); + const listen = opt_listen !== undefined ? opt_listen : true; + const feature_uid = getUid(feature); + const geometry = feature.getGeometry(); if (geometry) { - var segmentWriter = this.SEGMENT_WRITERS_[geometry.getType()]; + const segmentWriter = this.SEGMENT_WRITERS_[geometry.getType()]; if (segmentWriter) { this.indexedFeaturesExtents_[feature_uid] = geometry.getExtent(createEmpty()); segmentWriter.call(this, feature, geometry); @@ -173,9 +173,9 @@ Snap.prototype.addFeature = function(feature, opt_listen) { if (listen) { this.featureChangeListenerKeys_[feature_uid] = _ol_events_.listen( - feature, - EventType.CHANGE, - this.handleFeatureChange_, this); + feature, + EventType.CHANGE, + this.handleFeatureChange_, this); } }; @@ -203,7 +203,7 @@ Snap.prototype.forEachFeatureRemove_ = function(feature) { * @private */ Snap.prototype.getFeatures_ = function() { - var features; + let features; if (this.features_) { features = this.features_; } else if (this.source_) { @@ -218,7 +218,7 @@ Snap.prototype.getFeatures_ = function() { * @private */ Snap.prototype.handleFeatureAdd_ = function(evt) { - var feature; + let feature; if (evt instanceof VectorSource.Event) { feature = evt.feature; } else if (evt instanceof Collection.Event) { @@ -233,7 +233,7 @@ Snap.prototype.handleFeatureAdd_ = function(evt) { * @private */ Snap.prototype.handleFeatureRemove_ = function(evt) { - var feature; + let feature; if (evt instanceof VectorSource.Event) { feature = evt.feature; } else if (evt instanceof Collection.Event) { @@ -248,9 +248,9 @@ Snap.prototype.handleFeatureRemove_ = function(evt) { * @private */ Snap.prototype.handleFeatureChange_ = function(evt) { - var feature = /** @type {ol.Feature} */ (evt.target); + const feature = /** @type {ol.Feature} */ (evt.target); if (this.handlingDownUpSequence) { - var uid = getUid(feature); + const uid = getUid(feature); if (!(uid in this.pendingFeatures_)) { this.pendingFeatures_[uid] = feature; } @@ -268,18 +268,18 @@ Snap.prototype.handleFeatureChange_ = function(evt) { * @api */ Snap.prototype.removeFeature = function(feature, opt_unlisten) { - var unlisten = opt_unlisten !== undefined ? opt_unlisten : true; - var feature_uid = getUid(feature); - var extent = this.indexedFeaturesExtents_[feature_uid]; + const unlisten = opt_unlisten !== undefined ? opt_unlisten : true; + const feature_uid = getUid(feature); + const extent = this.indexedFeaturesExtents_[feature_uid]; if (extent) { - var rBush = this.rBush_; - var i, nodesToRemove = []; + const rBush = this.rBush_; + const nodesToRemove = []; rBush.forEachInExtent(extent, function(node) { if (feature === node.feature) { nodesToRemove.push(node); } }); - for (i = nodesToRemove.length - 1; i >= 0; --i) { + for (let i = nodesToRemove.length - 1; i >= 0; --i) { rBush.remove(nodesToRemove[i]); } } @@ -295,9 +295,9 @@ Snap.prototype.removeFeature = function(feature, opt_unlisten) { * @inheritDoc */ Snap.prototype.setMap = function(map) { - var currentMap = this.getMap(); - var keys = this.featuresListenerKeys_; - var features = this.getFeatures_(); + const currentMap = this.getMap(); + const keys = this.featuresListenerKeys_; + const features = this.getFeatures_(); if (currentMap) { keys.forEach(_ol_events_.unlistenByKey); @@ -309,17 +309,17 @@ Snap.prototype.setMap = function(map) { if (map) { if (this.features_) { keys.push( - _ol_events_.listen(this.features_, CollectionEventType.ADD, - this.handleFeatureAdd_, this), - _ol_events_.listen(this.features_, CollectionEventType.REMOVE, - this.handleFeatureRemove_, this) + _ol_events_.listen(this.features_, CollectionEventType.ADD, + this.handleFeatureAdd_, this), + _ol_events_.listen(this.features_, CollectionEventType.REMOVE, + this.handleFeatureRemove_, this) ); } else if (this.source_) { keys.push( - _ol_events_.listen(this.source_, VectorEventType.ADDFEATURE, - this.handleFeatureAdd_, this), - _ol_events_.listen(this.source_, VectorEventType.REMOVEFEATURE, - this.handleFeatureRemove_, this) + _ol_events_.listen(this.source_, VectorEventType.ADDFEATURE, + this.handleFeatureAdd_, this), + _ol_events_.listen(this.source_, VectorEventType.REMOVEFEATURE, + this.handleFeatureRemove_, this) ); } features.forEach(this.forEachFeatureAdd_.bind(this)); @@ -341,13 +341,13 @@ Snap.prototype.shouldStopEvent = FALSE; */ Snap.prototype.snapTo = function(pixel, pixelCoordinate, map) { - var lowerLeft = map.getCoordinateFromPixel( - [pixel[0] - this.pixelTolerance_, pixel[1] + this.pixelTolerance_]); - var upperRight = map.getCoordinateFromPixel( - [pixel[0] + this.pixelTolerance_, pixel[1] - this.pixelTolerance_]); - var box = boundingExtent([lowerLeft, upperRight]); + const lowerLeft = map.getCoordinateFromPixel( + [pixel[0] - this.pixelTolerance_, pixel[1] + this.pixelTolerance_]); + const upperRight = map.getCoordinateFromPixel( + [pixel[0] + this.pixelTolerance_, pixel[1] - this.pixelTolerance_]); + const box = boundingExtent([lowerLeft, upperRight]); - var segments = this.rBush_.getInExtent(box); + let segments = this.rBush_.getInExtent(box); // If snapping on vertices only, don't consider circles if (this.vertex_ && !this.edge_) { @@ -357,16 +357,16 @@ Snap.prototype.snapTo = function(pixel, pixelCoordinate, map) { }); } - var snappedToVertex = false; - var snapped = false; - var vertex = null; - var vertexPixel = null; - var dist, pixel1, pixel2, squaredDist1, squaredDist2; + let snappedToVertex = false; + let snapped = false; + let vertex = null; + let vertexPixel = null; + let dist, pixel1, pixel2, squaredDist1, squaredDist2; if (segments.length > 0) { this.pixelCoordinate_ = pixelCoordinate; segments.sort(this.sortByDistance_); - var closestSegment = segments[0].segment; - var isCircle = segments[0].feature.getGeometry().getType() === + const closestSegment = segments[0].segment; + const isCircle = segments[0].feature.getGeometry().getType() === GeometryType.CIRCLE; if (this.vertex_ && !this.edge_) { pixel1 = map.getPixelFromCoordinate(closestSegment[0]); @@ -384,10 +384,10 @@ Snap.prototype.snapTo = function(pixel, pixelCoordinate, map) { } else if (this.edge_) { if (isCircle) { vertex = _ol_coordinate_.closestOnCircle(pixelCoordinate, - /** @type {ol.geom.Circle} */ (segments[0].feature.getGeometry())); + /** @type {ol.geom.Circle} */ (segments[0].feature.getGeometry())); } else { vertex = (_ol_coordinate_.closestOnSegment(pixelCoordinate, - closestSegment)); + closestSegment)); } vertexPixel = map.getPixelFromCoordinate(vertex); if (_ol_coordinate_.distance(pixel, vertexPixel) <= this.pixelTolerance_) { @@ -435,9 +435,9 @@ Snap.prototype.updateFeature_ = function(feature) { * @private */ Snap.prototype.writeCircleGeometry_ = function(feature, geometry) { - var polygon = fromCircle(geometry); - var coordinates = polygon.getCoordinates()[0]; - var i, ii, segment, segmentData; + const polygon = fromCircle(geometry); + const coordinates = polygon.getCoordinates()[0]; + let i, ii, segment, segmentData; for (i = 0, ii = coordinates.length - 1; i < ii; ++i) { segment = coordinates.slice(i, i + 2); segmentData = /** @type {ol.SnapSegmentDataType} */ ({ @@ -455,9 +455,9 @@ Snap.prototype.writeCircleGeometry_ = function(feature, geometry) { * @private */ Snap.prototype.writeGeometryCollectionGeometry_ = function(feature, geometry) { - var i, geometries = geometry.getGeometriesArray(); - for (i = 0; i < geometries.length; ++i) { - var segmentWriter = this.SEGMENT_WRITERS_[geometries[i].getType()]; + const geometries = geometry.getGeometriesArray(); + for (let i = 0; i < geometries.length; ++i) { + const segmentWriter = this.SEGMENT_WRITERS_[geometries[i].getType()]; if (segmentWriter) { segmentWriter.call(this, feature, geometries[i]); } @@ -471,8 +471,8 @@ Snap.prototype.writeGeometryCollectionGeometry_ = function(feature, geometry) { * @private */ Snap.prototype.writeLineStringGeometry_ = function(feature, geometry) { - var coordinates = geometry.getCoordinates(); - var i, ii, segment, segmentData; + const coordinates = geometry.getCoordinates(); + let i, ii, segment, segmentData; for (i = 0, ii = coordinates.length - 1; i < ii; ++i) { segment = coordinates.slice(i, i + 2); segmentData = /** @type {ol.SnapSegmentDataType} */ ({ @@ -490,8 +490,8 @@ Snap.prototype.writeLineStringGeometry_ = function(feature, geometry) { * @private */ Snap.prototype.writeMultiLineStringGeometry_ = function(feature, geometry) { - var lines = geometry.getCoordinates(); - var coordinates, i, ii, j, jj, segment, segmentData; + const lines = geometry.getCoordinates(); + let coordinates, i, ii, j, jj, segment, segmentData; for (j = 0, jj = lines.length; j < jj; ++j) { coordinates = lines[j]; for (i = 0, ii = coordinates.length - 1; i < ii; ++i) { @@ -512,8 +512,8 @@ Snap.prototype.writeMultiLineStringGeometry_ = function(feature, geometry) { * @private */ Snap.prototype.writeMultiPointGeometry_ = function(feature, geometry) { - var points = geometry.getCoordinates(); - var coordinates, i, ii, segmentData; + const points = geometry.getCoordinates(); + let coordinates, i, ii, segmentData; for (i = 0, ii = points.length; i < ii; ++i) { coordinates = points[i]; segmentData = /** @type {ol.SnapSegmentDataType} */ ({ @@ -531,8 +531,8 @@ Snap.prototype.writeMultiPointGeometry_ = function(feature, geometry) { * @private */ Snap.prototype.writeMultiPolygonGeometry_ = function(feature, geometry) { - var polygons = geometry.getCoordinates(); - var coordinates, i, ii, j, jj, k, kk, rings, segment, segmentData; + const polygons = geometry.getCoordinates(); + let coordinates, i, ii, j, jj, k, kk, rings, segment, segmentData; for (k = 0, kk = polygons.length; k < kk; ++k) { rings = polygons[k]; for (j = 0, jj = rings.length; j < jj; ++j) { @@ -556,8 +556,8 @@ Snap.prototype.writeMultiPolygonGeometry_ = function(feature, geometry) { * @private */ Snap.prototype.writePointGeometry_ = function(feature, geometry) { - var coordinates = geometry.getCoordinates(); - var segmentData = /** @type {ol.SnapSegmentDataType} */ ({ + const coordinates = geometry.getCoordinates(); + const segmentData = /** @type {ol.SnapSegmentDataType} */ ({ feature: feature, segment: [coordinates, coordinates] }); @@ -571,8 +571,8 @@ Snap.prototype.writePointGeometry_ = function(feature, geometry) { * @private */ Snap.prototype.writePolygonGeometry_ = function(feature, geometry) { - var rings = geometry.getCoordinates(); - var coordinates, i, ii, j, jj, segment, segmentData; + const rings = geometry.getCoordinates(); + let coordinates, i, ii, j, jj, segment, segmentData; for (j = 0, jj = rings.length; j < jj; ++j) { coordinates = rings[j]; for (i = 0, ii = coordinates.length - 1; i < ii; ++i) { @@ -595,7 +595,7 @@ Snap.prototype.writePolygonGeometry_ = function(feature, geometry) { * @private */ Snap.handleEvent_ = function(evt) { - var result = this.snapTo(evt.pixel, evt.coordinate, evt.map); + const result = this.snapTo(evt.pixel, evt.coordinate, evt.map); if (result.snapped) { evt.coordinate = result.vertex.slice(0, 2); evt.pixel = result.vertexPixel; @@ -611,7 +611,7 @@ Snap.handleEvent_ = function(evt) { * @private */ Snap.handleUpEvent_ = function(evt) { - var featuresToUpdate = _ol_obj_.getValues(this.pendingFeatures_); + const featuresToUpdate = _ol_obj_.getValues(this.pendingFeatures_); if (featuresToUpdate.length) { featuresToUpdate.forEach(this.updateFeature_.bind(this)); this.pendingFeatures_ = {}; @@ -629,8 +629,8 @@ Snap.handleUpEvent_ = function(evt) { */ Snap.sortByDistance = function(a, b) { return _ol_coordinate_.squaredDistanceToSegment( - this.pixelCoordinate_, a.segment) - + this.pixelCoordinate_, a.segment) - _ol_coordinate_.squaredDistanceToSegment( - this.pixelCoordinate_, b.segment); + this.pixelCoordinate_, b.segment); }; export default Snap; diff --git a/src/ol/interaction/Translate.js b/src/ol/interaction/Translate.js index 40cd77c48f..7003ec1d7b 100644 --- a/src/ol/interaction/Translate.js +++ b/src/ol/interaction/Translate.js @@ -22,7 +22,7 @@ import TranslateEventType from '../interaction/TranslateEventType.js'; * @param {olx.interaction.TranslateOptions=} opt_options Options. * @api */ -var _ol_interaction_Translate_ = function(opt_options) { +const _ol_interaction_Translate_ = function(opt_options) { PointerInteraction.call(this, { handleDownEvent: _ol_interaction_Translate_.handleDownEvent_, handleDragEvent: _ol_interaction_Translate_.handleDragEvent_, @@ -30,7 +30,7 @@ var _ol_interaction_Translate_ = function(opt_options) { handleUpEvent: _ol_interaction_Translate_.handleUpEvent_ }); - var options = opt_options ? opt_options : {}; + const options = opt_options ? opt_options : {}; /** * The last position we translated to. @@ -47,12 +47,12 @@ var _ol_interaction_Translate_ = function(opt_options) { this.features_ = options.features !== undefined ? options.features : null; /** @type {function(ol.layer.Layer): boolean} */ - var layerFilter; + let layerFilter; if (options.layers) { if (typeof options.layers === 'function') { layerFilter = options.layers; } else { - var layers = options.layers; + const layers = options.layers; layerFilter = function(layer) { return includes(layers, layer); }; @@ -80,8 +80,8 @@ var _ol_interaction_Translate_ = function(opt_options) { this.lastFeature_ = null; _ol_events_.listen(this, - BaseObject.getChangeEventType(InteractionProperty.ACTIVE), - this.handleActiveChanged_, this); + BaseObject.getChangeEventType(InteractionProperty.ACTIVE), + this.handleActiveChanged_, this); }; @@ -100,12 +100,12 @@ _ol_interaction_Translate_.handleDownEvent_ = function(event) { this.lastCoordinate_ = event.coordinate; _ol_interaction_Translate_.handleMoveEvent_.call(this, event); - var features = this.features_ || new Collection([this.lastFeature_]); + const features = this.features_ || new Collection([this.lastFeature_]); this.dispatchEvent( - new _ol_interaction_Translate_.Event( - TranslateEventType.TRANSLATESTART, features, - event.coordinate)); + new _ol_interaction_Translate_.Event( + TranslateEventType.TRANSLATESTART, features, + event.coordinate)); return true; } return false; @@ -123,12 +123,12 @@ _ol_interaction_Translate_.handleUpEvent_ = function(event) { this.lastCoordinate_ = null; _ol_interaction_Translate_.handleMoveEvent_.call(this, event); - var features = this.features_ || new Collection([this.lastFeature_]); + const features = this.features_ || new Collection([this.lastFeature_]); this.dispatchEvent( - new _ol_interaction_Translate_.Event( - TranslateEventType.TRANSLATEEND, features, - event.coordinate)); + new _ol_interaction_Translate_.Event( + TranslateEventType.TRANSLATEEND, features, + event.coordinate)); return true; } return false; @@ -142,23 +142,23 @@ _ol_interaction_Translate_.handleUpEvent_ = function(event) { */ _ol_interaction_Translate_.handleDragEvent_ = function(event) { if (this.lastCoordinate_) { - var newCoordinate = event.coordinate; - var deltaX = newCoordinate[0] - this.lastCoordinate_[0]; - var deltaY = newCoordinate[1] - this.lastCoordinate_[1]; + const newCoordinate = event.coordinate; + const deltaX = newCoordinate[0] - this.lastCoordinate_[0]; + const deltaY = newCoordinate[1] - this.lastCoordinate_[1]; - var features = this.features_ || new Collection([this.lastFeature_]); + const features = this.features_ || new Collection([this.lastFeature_]); features.forEach(function(feature) { - var geom = feature.getGeometry(); + const geom = feature.getGeometry(); geom.translate(deltaX, deltaY); feature.setGeometry(geom); }); this.lastCoordinate_ = newCoordinate; this.dispatchEvent( - new _ol_interaction_Translate_.Event( - TranslateEventType.TRANSLATING, features, - newCoordinate)); + new _ol_interaction_Translate_.Event( + TranslateEventType.TRANSLATING, features, + newCoordinate)); } }; @@ -169,7 +169,7 @@ _ol_interaction_Translate_.handleDragEvent_ = function(event) { * @private */ _ol_interaction_Translate_.handleMoveEvent_ = function(event) { - var elem = event.map.getViewport(); + const elem = event.map.getViewport(); // Change the cursor to grab/grabbing if hovering any of the features managed // by the interaction @@ -193,14 +193,14 @@ _ol_interaction_Translate_.handleMoveEvent_ = function(event) { */ _ol_interaction_Translate_.prototype.featuresAtPixel_ = function(pixel, map) { return map.forEachFeatureAtPixel(pixel, - function(feature) { - if (!this.features_ || includes(this.features_.getArray(), feature)) { - return feature; - } - }.bind(this), { - layerFilter: this.layerFilter_, - hitTolerance: this.hitTolerance_ - }); + function(feature) { + if (!this.features_ || includes(this.features_.getArray(), feature)) { + return feature; + } + }.bind(this), { + layerFilter: this.layerFilter_, + hitTolerance: this.hitTolerance_ + }); }; @@ -230,7 +230,7 @@ _ol_interaction_Translate_.prototype.setHitTolerance = function(hitTolerance) { * @inheritDoc */ _ol_interaction_Translate_.prototype.setMap = function(map) { - var oldMap = this.getMap(); + const oldMap = this.getMap(); PointerInteraction.prototype.setMap.call(this, map); this.updateState_(oldMap); }; @@ -249,12 +249,12 @@ _ol_interaction_Translate_.prototype.handleActiveChanged_ = function() { * @private */ _ol_interaction_Translate_.prototype.updateState_ = function(oldMap) { - var map = this.getMap(); - var active = this.getActive(); + let map = this.getMap(); + const active = this.getActive(); if (!map || !active) { map = map || oldMap; if (map) { - var elem = map.getViewport(); + const elem = map.getViewport(); elem.classList.remove('ol-grab', 'ol-grabbing'); } } diff --git a/src/ol/layer/Base.js b/src/ol/layer/Base.js index 5506892def..1879cd3952 100644 --- a/src/ol/layer/Base.js +++ b/src/ol/layer/Base.js @@ -21,14 +21,14 @@ import _ol_obj_ from '../obj.js'; * @param {olx.layer.BaseOptions} options Layer options. * @api */ -var BaseLayer = function(options) { +const BaseLayer = function(options) { BaseObject.call(this); /** * @type {Object.} */ - var properties = _ol_obj_.assign({}, options); + const properties = _ol_obj_.assign({}, options); properties[LayerProperty.OPACITY] = options.opacity !== undefined ? options.opacity : 1; properties[LayerProperty.VISIBLE] = diff --git a/src/ol/layer/Group.js b/src/ol/layer/Group.js index a977c49a20..3711d554d7 100644 --- a/src/ol/layer/Group.js +++ b/src/ol/layer/Group.js @@ -19,7 +19,7 @@ import SourceState from '../source/State.js'; * @enum {string} * @private */ -var Property = { +const Property = { LAYERS: 'layers' }; @@ -35,14 +35,14 @@ var Property = { * @param {olx.layer.GroupOptions=} opt_options Layer options. * @api */ -var LayerGroup = function(opt_options) { +const LayerGroup = function(opt_options) { - var options = opt_options || {}; - var baseOptions = /** @type {olx.layer.GroupOptions} */ + const options = opt_options || {}; + const baseOptions = /** @type {olx.layer.GroupOptions} */ (_ol_obj_.assign({}, options)); delete baseOptions.layers; - var layers = options.layers; + let layers = options.layers; BaseLayer.call(this, baseOptions); @@ -59,15 +59,15 @@ var LayerGroup = function(opt_options) { this.listenerKeys_ = {}; _ol_events_.listen(this, - BaseObject.getChangeEventType(Property.LAYERS), - this.handleLayersChanged_, this); + BaseObject.getChangeEventType(Property.LAYERS), + this.handleLayersChanged_, this); if (layers) { if (Array.isArray(layers)) { layers = new Collection(layers.slice(), {unique: true}); } else { assert(layers instanceof Collection, - 43); // Expected `layers` to be an array or an `ol.Collection` + 43); // Expected `layers` to be an array or an `ol.Collection` layers = layers; } } else { @@ -97,27 +97,27 @@ LayerGroup.prototype.handleLayersChanged_ = function(event) { this.layersListenerKeys_.forEach(_ol_events_.unlistenByKey); this.layersListenerKeys_.length = 0; - var layers = this.getLayers(); + const layers = this.getLayers(); this.layersListenerKeys_.push( - _ol_events_.listen(layers, CollectionEventType.ADD, - this.handleLayersAdd_, this), - _ol_events_.listen(layers, CollectionEventType.REMOVE, - this.handleLayersRemove_, this)); + _ol_events_.listen(layers, CollectionEventType.ADD, + this.handleLayersAdd_, this), + _ol_events_.listen(layers, CollectionEventType.REMOVE, + this.handleLayersRemove_, this)); - for (var id in this.listenerKeys_) { + for (const id in this.listenerKeys_) { this.listenerKeys_[id].forEach(_ol_events_.unlistenByKey); } _ol_obj_.clear(this.listenerKeys_); - var layersArray = layers.getArray(); - var i, ii, layer; + const layersArray = layers.getArray(); + let i, ii, layer; for (i = 0, ii = layersArray.length; i < ii; i++) { layer = layersArray[i]; this.listenerKeys_[getUid(layer).toString()] = [ _ol_events_.listen(layer, ObjectEventType.PROPERTYCHANGE, - this.handleLayerChange_, this), + this.handleLayerChange_, this), _ol_events_.listen(layer, EventType.CHANGE, - this.handleLayerChange_, this) + this.handleLayerChange_, this) ]; } @@ -130,13 +130,13 @@ LayerGroup.prototype.handleLayersChanged_ = function(event) { * @private */ LayerGroup.prototype.handleLayersAdd_ = function(collectionEvent) { - var layer = /** @type {ol.layer.Base} */ (collectionEvent.element); - var key = getUid(layer).toString(); + const layer = /** @type {ol.layer.Base} */ (collectionEvent.element); + const key = getUid(layer).toString(); this.listenerKeys_[key] = [ _ol_events_.listen(layer, ObjectEventType.PROPERTYCHANGE, - this.handleLayerChange_, this), + this.handleLayerChange_, this), _ol_events_.listen(layer, EventType.CHANGE, - this.handleLayerChange_, this) + this.handleLayerChange_, this) ]; this.changed(); }; @@ -147,8 +147,8 @@ LayerGroup.prototype.handleLayersAdd_ = function(collectionEvent) { * @private */ LayerGroup.prototype.handleLayersRemove_ = function(collectionEvent) { - var layer = /** @type {ol.layer.Base} */ (collectionEvent.element); - var key = getUid(layer).toString(); + const layer = /** @type {ol.layer.Base} */ (collectionEvent.element); + const key = getUid(layer).toString(); this.listenerKeys_[key].forEach(_ol_events_.unlistenByKey); delete this.listenerKeys_[key]; this.changed(); @@ -185,7 +185,7 @@ LayerGroup.prototype.setLayers = function(layers) { * @inheritDoc */ LayerGroup.prototype.getLayersArray = function(opt_array) { - var array = opt_array !== undefined ? opt_array : []; + const array = opt_array !== undefined ? opt_array : []; this.getLayers().forEach(function(layer) { layer.getLayersArray(array); }); @@ -197,24 +197,24 @@ LayerGroup.prototype.getLayersArray = function(opt_array) { * @inheritDoc */ LayerGroup.prototype.getLayerStatesArray = function(opt_states) { - var states = opt_states !== undefined ? opt_states : []; + const states = opt_states !== undefined ? opt_states : []; - var pos = states.length; + const pos = states.length; this.getLayers().forEach(function(layer) { layer.getLayerStatesArray(states); }); - var ownLayerState = this.getLayerState(); - var i, ii, layerState; + const ownLayerState = this.getLayerState(); + let i, ii, layerState; for (i = pos, ii = states.length; i < ii; i++) { layerState = states[i]; layerState.opacity *= ownLayerState.opacity; layerState.visible = layerState.visible && ownLayerState.visible; layerState.maxResolution = Math.min( - layerState.maxResolution, ownLayerState.maxResolution); + layerState.maxResolution, ownLayerState.maxResolution); layerState.minResolution = Math.max( - layerState.minResolution, ownLayerState.minResolution); + layerState.minResolution, ownLayerState.minResolution); if (ownLayerState.extent !== undefined) { if (layerState.extent !== undefined) { layerState.extent = getIntersection(layerState.extent, ownLayerState.extent); diff --git a/src/ol/layer/Heatmap.js b/src/ol/layer/Heatmap.js index d60e405139..0972668981 100644 --- a/src/ol/layer/Heatmap.js +++ b/src/ol/layer/Heatmap.js @@ -17,7 +17,7 @@ import Style from '../style/Style.js'; * @enum {string} * @private */ -var Property = { +const Property = { BLUR: 'blur', GRADIENT: 'gradient', RADIUS: 'radius' @@ -28,7 +28,7 @@ var Property = { * @const * @type {Array.} */ -var DEFAULT_GRADIENT = ['#00f', '#0ff', '#0f0', '#ff0', '#f00']; +const DEFAULT_GRADIENT = ['#00f', '#0ff', '#0f0', '#ff0', '#f00']; /** @@ -44,10 +44,10 @@ var DEFAULT_GRADIENT = ['#00f', '#0ff', '#0f0', '#ff0', '#f00']; * @param {olx.layer.HeatmapOptions=} opt_options Options. * @api */ -var Heatmap = function(opt_options) { - var options = opt_options ? opt_options : {}; +const Heatmap = function(opt_options) { + const options = opt_options ? opt_options : {}; - var baseOptions = _ol_obj_.assign({}, options); + const baseOptions = _ol_obj_.assign({}, options); delete baseOptions.gradient; delete baseOptions.radius; @@ -81,8 +81,8 @@ var Heatmap = function(opt_options) { this.styleCache_ = null; _ol_events_.listen(this, - BaseObject.getChangeEventType(Property.GRADIENT), - this.handleGradientChanged_, this); + BaseObject.getChangeEventType(Property.GRADIENT), + this.handleGradientChanged_, this); this.setGradient(options.gradient ? options.gradient : DEFAULT_GRADIENT); @@ -91,16 +91,16 @@ var Heatmap = function(opt_options) { this.setRadius(options.radius !== undefined ? options.radius : 8); _ol_events_.listen(this, - BaseObject.getChangeEventType(Property.BLUR), - this.handleStyleChanged_, this); + BaseObject.getChangeEventType(Property.BLUR), + this.handleStyleChanged_, this); _ol_events_.listen(this, - BaseObject.getChangeEventType(Property.RADIUS), - this.handleStyleChanged_, this); + BaseObject.getChangeEventType(Property.RADIUS), + this.handleStyleChanged_, this); this.handleStyleChanged_(); - var weight = options.weight ? options.weight : 'weight'; - var weightFunction; + const weight = options.weight ? options.weight : 'weight'; + let weightFunction; if (typeof weight === 'string') { weightFunction = function(feature) { return feature.get(weight); @@ -110,11 +110,11 @@ var Heatmap = function(opt_options) { } this.setStyle(function(feature, resolution) { - var weight = weightFunction(feature); - var opacity = weight !== undefined ? clamp(weight, 0, 1) : 1; + const weight = weightFunction(feature); + const opacity = weight !== undefined ? clamp(weight, 0, 1) : 1; // cast to 8 bits - var index = (255 * opacity) | 0; - var style = this.styleCache_[index]; + const index = (255 * opacity) | 0; + let style = this.styleCache_[index]; if (!style) { style = [ new Style({ @@ -144,14 +144,14 @@ inherits(Heatmap, VectorLayer); * @return {Uint8ClampedArray} An array. * @private */ -var createGradient = function(colors) { - var width = 1; - var height = 256; - var context = createCanvasContext2D(width, height); +const createGradient = function(colors) { + const width = 1; + const height = 256; + const context = createCanvasContext2D(width, height); - var gradient = context.createLinearGradient(0, 0, width, height); - var step = 1 / (colors.length - 1); - for (var i = 0, ii = colors.length; i < ii; ++i) { + const gradient = context.createLinearGradient(0, 0, width, height); + const step = 1 / (colors.length - 1); + for (let i = 0, ii = colors.length; i < ii; ++i) { gradient.addColorStop(i * step, colors[i]); } @@ -167,16 +167,16 @@ var createGradient = function(colors) { * @private */ Heatmap.prototype.createCircle_ = function() { - var radius = this.getRadius(); - var blur = this.getBlur(); - var halfSize = radius + blur + 1; - var size = 2 * halfSize; - var context = createCanvasContext2D(size, size); + const radius = this.getRadius(); + const blur = this.getBlur(); + const halfSize = radius + blur + 1; + const size = 2 * halfSize; + const context = createCanvasContext2D(size, size); context.shadowOffsetX = context.shadowOffsetY = this.shadow_; context.shadowBlur = blur; context.shadowColor = '#000'; context.beginPath(); - var center = halfSize - this.shadow_; + const center = halfSize - this.shadow_; context.arc(center, center, radius, 0, Math.PI * 2, true); context.fill(); return context.canvas.toDataURL(); @@ -239,11 +239,11 @@ Heatmap.prototype.handleStyleChanged_ = function() { * @private */ Heatmap.prototype.handleRender_ = function(event) { - var context = event.context; - var canvas = context.canvas; - var image = context.getImageData(0, 0, canvas.width, canvas.height); - var view8 = image.data; - var i, ii, alpha; + const context = event.context; + const canvas = context.canvas; + const image = context.getImageData(0, 0, canvas.width, canvas.height); + const view8 = image.data; + let i, ii, alpha; for (i = 0, ii = view8.length; i < ii; i += 4) { alpha = view8[i + 3] * 4; if (alpha) { diff --git a/src/ol/layer/Image.js b/src/ol/layer/Image.js index 7477b585c7..782a5c3639 100644 --- a/src/ol/layer/Image.js +++ b/src/ol/layer/Image.js @@ -19,8 +19,8 @@ import Layer from '../layer/Layer.js'; * @param {olx.layer.ImageOptions=} opt_options Layer options. * @api */ -var ImageLayer = function(opt_options) { - var options = opt_options ? opt_options : {}; +const ImageLayer = function(opt_options) { + const options = opt_options ? opt_options : {}; Layer.call(this, /** @type {olx.layer.LayerOptions} */ (options)); /** diff --git a/src/ol/layer/Layer.js b/src/ol/layer/Layer.js index 99e37a2254..db938ed941 100644 --- a/src/ol/layer/Layer.js +++ b/src/ol/layer/Layer.js @@ -33,9 +33,9 @@ import SourceState from '../source/State.js'; * @param {olx.layer.LayerOptions} options Layer options. * @api */ -var Layer = function(options) { +const Layer = function(options) { - var baseOptions = _ol_obj_.assign({}, options); + const baseOptions = _ol_obj_.assign({}, options); delete baseOptions.source; BaseLayer.call(this, /** @type {olx.layer.BaseOptions} */ (baseOptions)); @@ -63,10 +63,10 @@ var Layer = function(options) { } _ol_events_.listen(this, - BaseObject.getChangeEventType(LayerProperty.SOURCE), - this.handleSourcePropertyChange_, this); + BaseObject.getChangeEventType(LayerProperty.SOURCE), + this.handleSourcePropertyChange_, this); - var source = options.source ? options.source : null; + const source = options.source ? options.source : null; this.setSource(source); }; @@ -91,7 +91,7 @@ Layer.visibleAtResolution = function(layerState, resolution) { * @inheritDoc */ Layer.prototype.getLayersArray = function(opt_array) { - var array = opt_array ? opt_array : []; + const array = opt_array ? opt_array : []; array.push(this); return array; }; @@ -101,7 +101,7 @@ Layer.prototype.getLayersArray = function(opt_array) { * @inheritDoc */ Layer.prototype.getLayerStatesArray = function(opt_states) { - var states = opt_states ? opt_states : []; + const states = opt_states ? opt_states : []; states.push(this.getLayerState()); return states; }; @@ -114,7 +114,7 @@ Layer.prototype.getLayerStatesArray = function(opt_states) { * @api */ Layer.prototype.getSource = function() { - var source = this.get(LayerProperty.SOURCE); + const source = this.get(LayerProperty.SOURCE); return /** @type {ol.source.Source} */ (source) || null; }; @@ -123,7 +123,7 @@ Layer.prototype.getSource = function() { * @inheritDoc */ Layer.prototype.getSourceState = function() { - var source = this.getSource(); + const source = this.getSource(); return !source ? SourceState.UNDEFINED : source.getState(); }; @@ -144,10 +144,10 @@ Layer.prototype.handleSourcePropertyChange_ = function() { _ol_events_.unlistenByKey(this.sourceChangeKey_); this.sourceChangeKey_ = null; } - var source = this.getSource(); + const source = this.getSource(); if (source) { this.sourceChangeKey_ = _ol_events_.listen(source, - EventType.CHANGE, this.handleSourceChange_, this); + EventType.CHANGE, this.handleSourceChange_, this); } this.changed(); }; @@ -179,15 +179,15 @@ Layer.prototype.setMap = function(map) { } if (map) { this.mapPrecomposeKey_ = _ol_events_.listen( - map, RenderEventType.PRECOMPOSE, function(evt) { - var layerState = this.getLayerState(); - layerState.managed = false; - layerState.zIndex = Infinity; - evt.frameState.layerStatesArray.push(layerState); - evt.frameState.layerStates[getUid(this)] = layerState; - }, this); + map, RenderEventType.PRECOMPOSE, function(evt) { + const layerState = this.getLayerState(); + layerState.managed = false; + layerState.zIndex = Infinity; + evt.frameState.layerStatesArray.push(layerState); + evt.frameState.layerStates[getUid(this)] = layerState; + }, this); this.mapRenderKey_ = _ol_events_.listen( - this, EventType.CHANGE, map.render, map); + this, EventType.CHANGE, map.render, map); this.changed(); } }; diff --git a/src/ol/layer/Tile.js b/src/ol/layer/Tile.js index 4846832420..1ff1a4860f 100644 --- a/src/ol/layer/Tile.js +++ b/src/ol/layer/Tile.js @@ -21,10 +21,10 @@ import _ol_obj_ from '../obj.js'; * @param {olx.layer.TileOptions=} opt_options Tile layer options. * @api */ -var TileLayer = function(opt_options) { - var options = opt_options ? opt_options : {}; +const TileLayer = function(opt_options) { + const options = opt_options ? opt_options : {}; - var baseOptions = _ol_obj_.assign({}, options); + const baseOptions = _ol_obj_.assign({}, options); delete baseOptions.preload; delete baseOptions.useInterimTilesOnError; @@ -100,6 +100,6 @@ TileLayer.prototype.getUseInterimTilesOnError = function() { */ TileLayer.prototype.setUseInterimTilesOnError = function(useInterimTilesOnError) { this.set( - _ol_layer_TileProperty_.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError); + _ol_layer_TileProperty_.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError); }; export default TileLayer; diff --git a/src/ol/layer/Vector.js b/src/ol/layer/Vector.js index ea94399be8..cd3febfd96 100644 --- a/src/ol/layer/Vector.js +++ b/src/ol/layer/Vector.js @@ -13,7 +13,7 @@ import Style from '../style/Style.js'; * @enum {string} * @private */ -var Property = { +const Property = { RENDER_ORDER: 'renderOrder' }; @@ -31,11 +31,11 @@ var Property = { * @param {olx.layer.VectorOptions=} opt_options Options. * @api */ -var VectorLayer = function(opt_options) { - var options = opt_options ? +const VectorLayer = function(opt_options) { + const options = opt_options ? opt_options : /** @type {olx.layer.VectorOptions} */ ({}); - var baseOptions = _ol_obj_.assign({}, options); + const baseOptions = _ol_obj_.assign({}, options); delete baseOptions.style; delete baseOptions.renderBuffer; diff --git a/src/ol/layer/VectorTile.js b/src/ol/layer/VectorTile.js index e6abe832ca..44a4b28c81 100644 --- a/src/ol/layer/VectorTile.js +++ b/src/ol/layer/VectorTile.js @@ -21,10 +21,10 @@ import _ol_obj_ from '../obj.js'; * @param {olx.layer.VectorTileOptions=} opt_options Options. * @api */ -var VectorTileLayer = function(opt_options) { - var options = opt_options ? opt_options : {}; +const VectorTileLayer = function(opt_options) { + const options = opt_options ? opt_options : {}; - var renderMode = options.renderMode || _ol_layer_VectorTileRenderType_.HYBRID; + let renderMode = options.renderMode || _ol_layer_VectorTileRenderType_.HYBRID; assert(renderMode == undefined || renderMode == _ol_layer_VectorTileRenderType_.IMAGE || renderMode == _ol_layer_VectorTileRenderType_.HYBRID || @@ -35,7 +35,7 @@ var VectorTileLayer = function(opt_options) { } options.renderMode = renderMode; - var baseOptions = _ol_obj_.assign({}, options); + const baseOptions = _ol_obj_.assign({}, options); delete baseOptions.preload; delete baseOptions.useInterimTilesOnError; @@ -102,7 +102,7 @@ VectorTileLayer.prototype.setPreload = function(preload) { */ VectorTileLayer.prototype.setUseInterimTilesOnError = function(useInterimTilesOnError) { this.set( - _ol_layer_TileProperty_.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError); + _ol_layer_TileProperty_.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError); }; diff --git a/src/ol/loadingstrategy.js b/src/ol/loadingstrategy.js index 5ff4dddef7..cc31834dfe 100644 --- a/src/ol/loadingstrategy.js +++ b/src/ol/loadingstrategy.js @@ -1,7 +1,7 @@ /** * @module ol/loadingstrategy */ -var _ol_loadingstrategy_ = {}; +const _ol_loadingstrategy_ = {}; /** @@ -43,12 +43,12 @@ _ol_loadingstrategy_.tile = function(tileGrid) { * @return {Array.} Extents. */ function(extent, resolution) { - var z = tileGrid.getZForResolution(resolution); - var tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z); + const z = tileGrid.getZForResolution(resolution); + const tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z); /** @type {Array.} */ - var extents = []; + const extents = []; /** @type {ol.TileCoord} */ - var tileCoord = [z, 0, 0]; + const tileCoord = [z, 0, 0]; for (tileCoord[1] = tileRange.minX; tileCoord[1] <= tileRange.maxX; ++tileCoord[1]) { for (tileCoord[2] = tileRange.minY; tileCoord[2] <= tileRange.maxY; diff --git a/src/ol/math.js b/src/ol/math.js index a7da325e44..9c85eaa961 100644 --- a/src/ol/math.js +++ b/src/ol/math.js @@ -25,17 +25,17 @@ export function clamp(value, min, max) { * @param {number} x X. * @return {number} Hyperbolic cosine of x. */ -export var cosh = (function() { +export const cosh = (function() { // Wrapped in a iife, to save the overhead of checking for the native // implementation on every invocation. - var cosh; + let cosh; if ('cosh' in Math) { // The environment supports the native Math.cosh function, use it… cosh = Math.cosh; } else { // … else, use the reference implementation of MDN: cosh = function(x) { - var y = Math.exp(x); + const y = Math.exp(x); return (y + 1 / y) / 2; }; } @@ -65,10 +65,10 @@ export function roundUpToPowerOfTwo(x) { * @return {number} Squared distance. */ export function squaredSegmentDistance(x, y, x1, y1, x2, y2) { - var dx = x2 - x1; - var dy = y2 - y1; + const dx = x2 - x1; + const dy = y2 - y1; if (dx !== 0 || dy !== 0) { - var t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy); + const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy); if (t > 1) { x1 = x2; y1 = y2; @@ -90,8 +90,8 @@ export function squaredSegmentDistance(x, y, x1, y1, x2, y2) { * @return {number} Squared distance. */ export function squaredDistance(x1, y1, x2, y2) { - var dx = x2 - x1; - var dy = y2 - y1; + const dx = x2 - x1; + const dy = y2 - y1; return dx * dx + dy * dy; } @@ -104,14 +104,14 @@ export function squaredDistance(x1, y1, x2, y2) { * @return {Array.} The resulting vector. */ export function solveLinearSystem(mat) { - var n = mat.length; + const n = mat.length; - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { // Find max in the i-th column (ignoring i - 1 first rows) - var maxRow = i; - var maxEl = Math.abs(mat[i][i]); - for (var r = i + 1; r < n; r++) { - var absValue = Math.abs(mat[r][i]); + let maxRow = i; + let maxEl = Math.abs(mat[i][i]); + for (let r = i + 1; r < n; r++) { + const absValue = Math.abs(mat[r][i]); if (absValue > maxEl) { maxEl = absValue; maxRow = r; @@ -123,14 +123,14 @@ export function solveLinearSystem(mat) { } // Swap max row with i-th (current) row - var tmp = mat[maxRow]; + const tmp = mat[maxRow]; mat[maxRow] = mat[i]; mat[i] = tmp; // Subtract the i-th row to make all the remaining rows 0 in the i-th column - for (var j = i + 1; j < n; j++) { - var coef = -mat[j][i] / mat[i][i]; - for (var k = i; k < n + 1; k++) { + for (let j = i + 1; j < n; j++) { + const coef = -mat[j][i] / mat[i][i]; + for (let k = i; k < n + 1; k++) { if (i == k) { mat[j][k] = 0; } else { @@ -141,10 +141,10 @@ export function solveLinearSystem(mat) { } // Solve Ax=b for upper triangular matrix A (mat) - var x = new Array(n); - for (var l = n - 1; l >= 0; l--) { + const x = new Array(n); + for (let l = n - 1; l >= 0; l--) { x[l] = mat[l][n] / mat[l][l]; - for (var m = l - 1; m >= 0; m--) { + for (let m = l - 1; m >= 0; m--) { mat[m][n] -= mat[m][l] * x[l]; } } @@ -181,7 +181,7 @@ export function toRadians(angleInDegrees) { * @return {number} Modulo. */ export function modulo(a, b) { - var r = a % b; + const r = a % b; return r * b < 0 ? r + b : r; } diff --git a/src/ol/net.js b/src/ol/net.js index 10ff5b40d7..f36a3fff10 100644 --- a/src/ol/net.js +++ b/src/ol/net.js @@ -2,7 +2,7 @@ * @module ol/net */ import {getUid} from './index.js'; -var _ol_net_ = {}; +const _ol_net_ = {}; /** @@ -17,8 +17,8 @@ var _ol_net_ = {}; * callback. Default is 'callback'. */ _ol_net_.jsonp = function(url, callback, opt_errback, opt_callbackParam) { - var script = document.createElement('script'); - var key = 'olc_' + getUid(callback); + const script = document.createElement('script'); + const key = 'olc_' + getUid(callback); function cleanup() { delete window[key]; script.parentNode.removeChild(script); @@ -26,7 +26,7 @@ _ol_net_.jsonp = function(url, callback, opt_errback, opt_callbackParam) { script.async = true; script.src = url + (url.indexOf('?') == -1 ? '?' : '&') + (opt_callbackParam || 'callback') + '=' + key; - var timer = setTimeout(function() { + const timer = setTimeout(function() { cleanup(); if (opt_errback) { opt_errback(); diff --git a/src/ol/obj.js b/src/ol/obj.js index 0099dfe816..2b5c0ec970 100644 --- a/src/ol/obj.js +++ b/src/ol/obj.js @@ -1,7 +1,7 @@ /** * @module ol/obj */ -var _ol_obj_ = {}; +const _ol_obj_ = {}; /** @@ -18,11 +18,11 @@ _ol_obj_.assign = (typeof Object.assign === 'function') ? Object.assign : functi throw new TypeError('Cannot convert undefined or null to object'); } - var output = Object(target); - for (var i = 1, ii = arguments.length; i < ii; ++i) { - var source = arguments[i]; + const output = Object(target); + for (let i = 1, ii = arguments.length; i < ii; ++i) { + const source = arguments[i]; if (source !== undefined && source !== null) { - for (var key in source) { + for (const key in source) { if (source.hasOwnProperty(key)) { output[key] = source[key]; } @@ -38,7 +38,7 @@ _ol_obj_.assign = (typeof Object.assign === 'function') ? Object.assign : functi * @param {Object} object The object to clear. */ _ol_obj_.clear = function(object) { - for (var property in object) { + for (const property in object) { delete object[property]; } }; @@ -51,8 +51,8 @@ _ol_obj_.clear = function(object) { * @template K,V */ _ol_obj_.getValues = function(object) { - var values = []; - for (var property in object) { + const values = []; + for (const property in object) { values.push(object[property]); } return values; @@ -65,7 +65,7 @@ _ol_obj_.getValues = function(object) { * @return {boolean} The object is empty. */ _ol_obj_.isEmpty = function(object) { - var property; + let property; for (property in object) { return false; } diff --git a/src/ol/plugins.js b/src/ol/plugins.js index a77bc782a7..35e05f24e6 100644 --- a/src/ol/plugins.js +++ b/src/ol/plugins.js @@ -8,7 +8,7 @@ import PluginType from './PluginType.js'; * @type {Array} * @private */ -var mapRendererPlugins = []; +const mapRendererPlugins = []; /** @@ -25,7 +25,7 @@ export function getMapRendererPlugins() { * @type {Array} * @private */ -var layerRendererPlugins = []; +const layerRendererPlugins = []; /** @@ -43,7 +43,7 @@ export function getLayerRendererPlugins() { * @param {*} plugin The plugin. */ export function register(type, plugin) { - var plugins; + let plugins; switch (type) { case PluginType.MAP_RENDERER: { plugins = mapRendererPlugins; @@ -68,7 +68,7 @@ export function register(type, plugin) { * @param {Array} plugins The plugins. */ export function registerMultiple(type, plugins) { - for (var i = 0, ii = plugins.length; i < ii; ++i) { + for (let i = 0, ii = plugins.length; i < ii; ++i) { register(type, plugins[i]); } } diff --git a/src/ol/pointer/EventSource.js b/src/ol/pointer/EventSource.js index 444b0c3d64..0606214b58 100644 --- a/src/ol/pointer/EventSource.js +++ b/src/ol/pointer/EventSource.js @@ -7,7 +7,7 @@ * mapping. * @constructor */ -var _ol_pointer_EventSource_ = function(dispatcher, mapping) { +const _ol_pointer_EventSource_ = function(dispatcher, mapping) { /** * @type {ol.pointer.PointerEventHandler} */ diff --git a/src/ol/pointer/MouseSource.js b/src/ol/pointer/MouseSource.js index e9be05264d..68c51c4024 100644 --- a/src/ol/pointer/MouseSource.js +++ b/src/ol/pointer/MouseSource.js @@ -39,8 +39,8 @@ import _ol_pointer_EventSource_ from '../pointer/EventSource.js'; * @constructor * @extends {ol.pointer.EventSource} */ -var _ol_pointer_MouseSource_ = function(dispatcher) { - var mapping = { +const _ol_pointer_MouseSource_ = function(dispatcher) { + const mapping = { 'mousedown': this.mousedown, 'mousemove': this.mousemove, 'mouseup': this.mouseup, @@ -113,11 +113,13 @@ _ol_pointer_MouseSource_.DEDUP_DIST = 25; * @return {boolean} True, if the event was generated by a touch. */ _ol_pointer_MouseSource_.prototype.isEventSimulatedFromTouch_ = function(inEvent) { - var lts = this.lastTouches; - var x = inEvent.clientX, y = inEvent.clientY; - for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) { + const lts = this.lastTouches; + const x = inEvent.clientX; + const y = inEvent.clientY; + for (let i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) { // simulated mouse events will be swallowed near a primary touchend - var dx = Math.abs(x - t[0]), dy = Math.abs(y - t[1]); + const dx = Math.abs(x - t[0]); + const dy = Math.abs(y - t[1]); if (dx <= _ol_pointer_MouseSource_.DEDUP_DIST && dy <= _ol_pointer_MouseSource_.DEDUP_DIST) { return true; @@ -136,10 +138,10 @@ _ol_pointer_MouseSource_.prototype.isEventSimulatedFromTouch_ = function(inEvent * @return {Object} The copied event. */ _ol_pointer_MouseSource_.prepareEvent = function(inEvent, dispatcher) { - var e = dispatcher.cloneEvent(inEvent, inEvent); + const e = dispatcher.cloneEvent(inEvent, inEvent); // forward mouse preventDefault - var pd = e.preventDefault; + const pd = e.preventDefault; e.preventDefault = function() { inEvent.preventDefault(); pd(); @@ -165,7 +167,7 @@ _ol_pointer_MouseSource_.prototype.mousedown = function(inEvent) { if (_ol_pointer_MouseSource_.POINTER_ID.toString() in this.pointerMap) { this.cancel(inEvent); } - var e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); + const e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); this.pointerMap[_ol_pointer_MouseSource_.POINTER_ID.toString()] = inEvent; this.dispatcher.down(e, inEvent); } @@ -179,7 +181,7 @@ _ol_pointer_MouseSource_.prototype.mousedown = function(inEvent) { */ _ol_pointer_MouseSource_.prototype.mousemove = function(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { - var e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); + const e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); this.dispatcher.move(e, inEvent); } }; @@ -192,10 +194,10 @@ _ol_pointer_MouseSource_.prototype.mousemove = function(inEvent) { */ _ol_pointer_MouseSource_.prototype.mouseup = function(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { - var p = this.pointerMap[_ol_pointer_MouseSource_.POINTER_ID.toString()]; + const p = this.pointerMap[_ol_pointer_MouseSource_.POINTER_ID.toString()]; if (p && p.button === inEvent.button) { - var e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); + const e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); this.dispatcher.up(e, inEvent); this.cleanupMouse(); } @@ -210,7 +212,7 @@ _ol_pointer_MouseSource_.prototype.mouseup = function(inEvent) { */ _ol_pointer_MouseSource_.prototype.mouseover = function(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { - var e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); + const e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); this.dispatcher.enterOver(e, inEvent); } }; @@ -223,7 +225,7 @@ _ol_pointer_MouseSource_.prototype.mouseover = function(inEvent) { */ _ol_pointer_MouseSource_.prototype.mouseout = function(inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { - var e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); + const e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); this.dispatcher.leaveOut(e, inEvent); } }; @@ -235,7 +237,7 @@ _ol_pointer_MouseSource_.prototype.mouseout = function(inEvent) { * @param {Event} inEvent The in event. */ _ol_pointer_MouseSource_.prototype.cancel = function(inEvent) { - var e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); + const e = _ol_pointer_MouseSource_.prepareEvent(inEvent, this.dispatcher); this.dispatcher.cancel(e, inEvent); this.cleanupMouse(); }; diff --git a/src/ol/pointer/MsSource.js b/src/ol/pointer/MsSource.js index fce9a24849..a06d511dcf 100644 --- a/src/ol/pointer/MsSource.js +++ b/src/ol/pointer/MsSource.js @@ -39,8 +39,8 @@ import _ol_pointer_EventSource_ from '../pointer/EventSource.js'; * @constructor * @extends {ol.pointer.EventSource} */ -var _ol_pointer_MsSource_ = function(dispatcher) { - var mapping = { +const _ol_pointer_MsSource_ = function(dispatcher) { + const mapping = { 'MSPointerDown': this.msPointerDown, 'MSPointerMove': this.msPointerMove, 'MSPointerUp': this.msPointerUp, @@ -83,7 +83,7 @@ inherits(_ol_pointer_MsSource_, _ol_pointer_EventSource_); * @return {Object} The copied event. */ _ol_pointer_MsSource_.prototype.prepareEvent_ = function(inEvent) { - var e = inEvent; + let e = inEvent; if (typeof inEvent.pointerType === 'number') { e = this.dispatcher.cloneEvent(inEvent, inEvent); e.pointerType = this.POINTER_TYPES[inEvent.pointerType]; @@ -109,7 +109,7 @@ _ol_pointer_MsSource_.prototype.cleanup = function(pointerId) { */ _ol_pointer_MsSource_.prototype.msPointerDown = function(inEvent) { this.pointerMap[inEvent.pointerId.toString()] = inEvent; - var e = this.prepareEvent_(inEvent); + const e = this.prepareEvent_(inEvent); this.dispatcher.down(e, inEvent); }; @@ -120,7 +120,7 @@ _ol_pointer_MsSource_.prototype.msPointerDown = function(inEvent) { * @param {Event} inEvent The in event. */ _ol_pointer_MsSource_.prototype.msPointerMove = function(inEvent) { - var e = this.prepareEvent_(inEvent); + const e = this.prepareEvent_(inEvent); this.dispatcher.move(e, inEvent); }; @@ -131,7 +131,7 @@ _ol_pointer_MsSource_.prototype.msPointerMove = function(inEvent) { * @param {Event} inEvent The in event. */ _ol_pointer_MsSource_.prototype.msPointerUp = function(inEvent) { - var e = this.prepareEvent_(inEvent); + const e = this.prepareEvent_(inEvent); this.dispatcher.up(e, inEvent); this.cleanup(inEvent.pointerId); }; @@ -143,7 +143,7 @@ _ol_pointer_MsSource_.prototype.msPointerUp = function(inEvent) { * @param {Event} inEvent The in event. */ _ol_pointer_MsSource_.prototype.msPointerOut = function(inEvent) { - var e = this.prepareEvent_(inEvent); + const e = this.prepareEvent_(inEvent); this.dispatcher.leaveOut(e, inEvent); }; @@ -154,7 +154,7 @@ _ol_pointer_MsSource_.prototype.msPointerOut = function(inEvent) { * @param {Event} inEvent The in event. */ _ol_pointer_MsSource_.prototype.msPointerOver = function(inEvent) { - var e = this.prepareEvent_(inEvent); + const e = this.prepareEvent_(inEvent); this.dispatcher.enterOver(e, inEvent); }; @@ -165,7 +165,7 @@ _ol_pointer_MsSource_.prototype.msPointerOver = function(inEvent) { * @param {Event} inEvent The in event. */ _ol_pointer_MsSource_.prototype.msPointerCancel = function(inEvent) { - var e = this.prepareEvent_(inEvent); + const e = this.prepareEvent_(inEvent); this.dispatcher.cancel(e, inEvent); this.cleanup(inEvent.pointerId); }; @@ -177,8 +177,8 @@ _ol_pointer_MsSource_.prototype.msPointerCancel = function(inEvent) { * @param {Event} inEvent The in event. */ _ol_pointer_MsSource_.prototype.msLostPointerCapture = function(inEvent) { - var e = this.dispatcher.makeEvent('lostpointercapture', - inEvent, inEvent); + const e = this.dispatcher.makeEvent('lostpointercapture', + inEvent, inEvent); this.dispatcher.dispatchEvent(e); }; @@ -189,8 +189,8 @@ _ol_pointer_MsSource_.prototype.msLostPointerCapture = function(inEvent) { * @param {Event} inEvent The in event. */ _ol_pointer_MsSource_.prototype.msGotPointerCapture = function(inEvent) { - var e = this.dispatcher.makeEvent('gotpointercapture', - inEvent, inEvent); + const e = this.dispatcher.makeEvent('gotpointercapture', + inEvent, inEvent); this.dispatcher.dispatchEvent(e); }; export default _ol_pointer_MsSource_; diff --git a/src/ol/pointer/NativeSource.js b/src/ol/pointer/NativeSource.js index 60d234d975..05949efd9e 100644 --- a/src/ol/pointer/NativeSource.js +++ b/src/ol/pointer/NativeSource.js @@ -39,8 +39,8 @@ import _ol_pointer_EventSource_ from '../pointer/EventSource.js'; * @constructor * @extends {ol.pointer.EventSource} */ -var _ol_pointer_NativeSource_ = function(dispatcher) { - var mapping = { +const _ol_pointer_NativeSource_ = function(dispatcher) { + const mapping = { 'pointerdown': this.pointerDown, 'pointermove': this.pointerMove, 'pointerup': this.pointerUp, diff --git a/src/ol/pointer/PointerEvent.js b/src/ol/pointer/PointerEvent.js index 24f87971c3..721957bced 100644 --- a/src/ol/pointer/PointerEvent.js +++ b/src/ol/pointer/PointerEvent.js @@ -47,7 +47,7 @@ import Event from '../events/Event.js'; * @param {Object.=} opt_eventDict An optional dictionary of * initial event properties. */ -var PointerEvent = function(type, originalEvent, opt_eventDict) { +const PointerEvent = function(type, originalEvent, opt_eventDict) { Event.call(this, type); /** @@ -56,7 +56,7 @@ var PointerEvent = function(type, originalEvent, opt_eventDict) { */ this.originalEvent = originalEvent; - var eventDict = opt_eventDict ? opt_eventDict : {}; + const eventDict = opt_eventDict ? opt_eventDict : {}; /** * @type {number} @@ -222,7 +222,7 @@ PointerEvent.prototype.getButtons_ = function(eventDict) { // is to call initMouseEvent with a buttonArg value of -1. // // This is fixed with DOM Level 4's use of buttons - var buttons; + let buttons; if (eventDict.buttons || PointerEvent.HAS_BUTTONS) { buttons = eventDict.buttons; } else { @@ -246,7 +246,7 @@ PointerEvent.prototype.getButtons_ = function(eventDict) { PointerEvent.prototype.getPressure_ = function(eventDict, buttons) { // Spec requires that pointers without pressure specified use 0.5 for down // state and 0 for up state. - var pressure = 0; + let pressure = 0; if (eventDict.pressure) { pressure = eventDict.pressure; } else { @@ -268,7 +268,7 @@ PointerEvent.HAS_BUTTONS = false; */ (function() { try { - var ev = new MouseEvent('click', {buttons: 1}); + const ev = new MouseEvent('click', {buttons: 1}); PointerEvent.HAS_BUTTONS = ev.buttons === 1; } catch (e) { // pass diff --git a/src/ol/pointer/PointerEventHandler.js b/src/ol/pointer/PointerEventHandler.js index fd585837a0..f72b1e4432 100644 --- a/src/ol/pointer/PointerEventHandler.js +++ b/src/ol/pointer/PointerEventHandler.js @@ -47,7 +47,7 @@ import _ol_pointer_TouchSource_ from '../pointer/TouchSource.js'; * @extends {ol.events.EventTarget} * @param {Element|HTMLDocument} element Viewport element. */ -var PointerEventHandler = function(element) { +const PointerEventHandler = function(element) { EventTarget.call(this); /** @@ -91,12 +91,12 @@ PointerEventHandler.prototype.registerSources = function() { } else if (_ol_has_.MSPOINTER) { this.registerSource('ms', new _ol_pointer_MsSource_(this)); } else { - var mouseSource = new _ol_pointer_MouseSource_(this); + const mouseSource = new _ol_pointer_MouseSource_(this); this.registerSource('mouse', mouseSource); if (_ol_has_.TOUCH) { this.registerSource('touch', - new _ol_pointer_TouchSource_(this, mouseSource)); + new _ol_pointer_TouchSource_(this, mouseSource)); } } @@ -112,12 +112,12 @@ PointerEventHandler.prototype.registerSources = function() { * @param {ol.pointer.EventSource} source The source event. */ PointerEventHandler.prototype.registerSource = function(name, source) { - var s = source; - var newEvents = s.getEvents(); + const s = source; + const newEvents = s.getEvents(); if (newEvents) { newEvents.forEach(function(e) { - var handler = s.getHandlerForEvent(e); + const handler = s.getHandlerForEvent(e); if (handler) { this.eventMap_[e] = handler.bind(s); @@ -133,9 +133,9 @@ PointerEventHandler.prototype.registerSource = function(name, source) { * @private */ PointerEventHandler.prototype.register_ = function() { - var l = this.eventSourceList_.length; - var eventSource; - for (var i = 0; i < l; i++) { + const l = this.eventSourceList_.length; + let eventSource; + for (let i = 0; i < l; i++) { eventSource = this.eventSourceList_[i]; this.addEvents_(eventSource.getEvents()); } @@ -147,9 +147,9 @@ PointerEventHandler.prototype.register_ = function() { * @private */ PointerEventHandler.prototype.unregister_ = function() { - var l = this.eventSourceList_.length; - var eventSource; - for (var i = 0; i < l; i++) { + const l = this.eventSourceList_.length; + let eventSource; + for (let i = 0; i < l; i++) { eventSource = this.eventSourceList_[i]; this.removeEvents_(eventSource.getEvents()); } @@ -162,8 +162,8 @@ PointerEventHandler.prototype.unregister_ = function() { * @param {Event} inEvent Browser event. */ PointerEventHandler.prototype.eventHandler_ = function(inEvent) { - var type = inEvent.type; - var handler = this.eventMap_[type]; + const type = inEvent.type; + const handler = this.eventMap_[type]; if (handler) { handler(inEvent); } @@ -204,9 +204,9 @@ PointerEventHandler.prototype.removeEvents_ = function(events) { * `inEvent`'s properties. */ PointerEventHandler.prototype.cloneEvent = function(event, inEvent) { - var eventCopy = {}, p; - for (var i = 0, ii = PointerEventHandler.CLONE_PROPS.length; i < ii; i++) { - p = PointerEventHandler.CLONE_PROPS[i][0]; + const eventCopy = {}; + for (let i = 0, ii = PointerEventHandler.CLONE_PROPS.length; i < ii; i++) { + const p = PointerEventHandler.CLONE_PROPS[i][0]; eventCopy[p] = event[p] || inEvent[p] || PointerEventHandler.CLONE_PROPS[i][1]; } @@ -364,7 +364,7 @@ PointerEventHandler.prototype.makeEvent = function(inType, data, event) { * @param {Event} event The event. */ PointerEventHandler.prototype.fireEvent = function(inType, data, event) { - var e = this.makeEvent(inType, data, event); + const e = this.makeEvent(inType, data, event); this.dispatchEvent(e); }; @@ -375,7 +375,7 @@ PointerEventHandler.prototype.fireEvent = function(inType, data, event) { * @param {Event} event A platform event with a target. */ PointerEventHandler.prototype.fireNativeEvent = function(event) { - var e = this.makeEvent(event.type, event, event); + const e = this.makeEvent(event.type, event, event); this.dispatchEvent(e); }; @@ -388,8 +388,8 @@ PointerEventHandler.prototype.fireNativeEvent = function(event) { * @return {ol.pointer.PointerEvent} The wrapped event. */ PointerEventHandler.prototype.wrapMouseEvent = function(eventType, event) { - var pointerEvent = this.makeEvent( - eventType, _ol_pointer_MouseSource_.prepareEvent(event, this), event); + const pointerEvent = this.makeEvent( + eventType, _ol_pointer_MouseSource_.prepareEvent(event, this), event); return pointerEvent; }; diff --git a/src/ol/pointer/TouchSource.js b/src/ol/pointer/TouchSource.js index 9b33516698..80f3bf7267 100644 --- a/src/ol/pointer/TouchSource.js +++ b/src/ol/pointer/TouchSource.js @@ -42,8 +42,8 @@ import _ol_pointer_MouseSource_ from '../pointer/MouseSource.js'; * @param {ol.pointer.MouseSource} mouseSource Mouse source. * @extends {ol.pointer.EventSource} */ -var _ol_pointer_TouchSource_ = function(dispatcher, mouseSource) { - var mapping = { +const _ol_pointer_TouchSource_ = function(dispatcher, mouseSource) { + const mapping = { 'touchstart': this.touchstart, 'touchmove': this.touchmove, 'touchend': this.touchend, @@ -124,7 +124,7 @@ _ol_pointer_TouchSource_.prototype.isPrimaryTouch_ = function(inTouch) { * @private */ _ol_pointer_TouchSource_.prototype.setPrimaryTouch_ = function(inTouch) { - var count = Object.keys(this.pointerMap).length; + const count = Object.keys(this.pointerMap).length; if (count === 0 || (count === 1 && _ol_pointer_MouseSource_.POINTER_ID.toString() in this.pointerMap)) { this.firstTouchId_ = inTouch.identifier; @@ -150,8 +150,8 @@ _ol_pointer_TouchSource_.prototype.removePrimaryPointer_ = function(inPointer) { */ _ol_pointer_TouchSource_.prototype.resetClickCount_ = function() { this.resetId_ = setTimeout( - this.resetClickCountHandler_.bind(this), - _ol_pointer_TouchSource_.CLICK_COUNT_TIMEOUT); + this.resetClickCountHandler_.bind(this), + _ol_pointer_TouchSource_.CLICK_COUNT_TIMEOUT); }; @@ -181,7 +181,7 @@ _ol_pointer_TouchSource_.prototype.cancelResetClickCount_ = function() { * @return {Object} A pointer object. */ _ol_pointer_TouchSource_.prototype.touchToPointer_ = function(browserEvent, inTouch) { - var e = this.dispatcher.cloneEvent(browserEvent, inTouch); + const e = this.dispatcher.cloneEvent(browserEvent, inTouch); // Spec specifies that pointerId 1 is reserved for Mouse. // Touch identifiers can start at 0. // Add 2 to the touch identifier for compatibility. @@ -216,13 +216,13 @@ _ol_pointer_TouchSource_.prototype.touchToPointer_ = function(browserEvent, inTo * @param {function(Event, Object)} inFunction In function. */ _ol_pointer_TouchSource_.prototype.processTouches_ = function(inEvent, inFunction) { - var touches = Array.prototype.slice.call( - inEvent.changedTouches); - var count = touches.length; + const touches = Array.prototype.slice.call( + inEvent.changedTouches); + const count = touches.length; function preventDefault() { inEvent.preventDefault(); } - var i, pointer; + let i, pointer; for (i = 0; i < count; ++i) { pointer = this.touchToPointer_(inEvent, touches[i]); // forward touch preventDefaults @@ -239,9 +239,9 @@ _ol_pointer_TouchSource_.prototype.processTouches_ = function(inEvent, inFunctio * @return {boolean} True, if the `Touch` with the given id is in the list. */ _ol_pointer_TouchSource_.prototype.findTouch_ = function(touchList, searchId) { - var l = touchList.length; - var touch; - for (var i = 0; i < l; i++) { + const l = touchList.length; + let touch; + for (let i = 0; i < l; i++) { touch = touchList[i]; if (touch.identifier === searchId) { return true; @@ -263,14 +263,14 @@ _ol_pointer_TouchSource_.prototype.findTouch_ = function(touchList, searchId) { * @param {Event} inEvent The in event. */ _ol_pointer_TouchSource_.prototype.vacuumTouches_ = function(inEvent) { - var touchList = inEvent.touches; + const touchList = inEvent.touches; // pointerMap.getCount() should be < touchList.length here, // as the touchstart has not been processed yet. - var keys = Object.keys(this.pointerMap); - var count = keys.length; + const keys = Object.keys(this.pointerMap); + const count = keys.length; if (count >= touchList.length) { - var d = []; - var i, key, value; + const d = []; + let i, key, value; for (i = 0; i < count; ++i) { key = keys[i]; value = this.pointerMap[key]; @@ -338,14 +338,14 @@ _ol_pointer_TouchSource_.prototype.touchmove = function(inEvent) { * @param {Object} inPointer The in pointer. */ _ol_pointer_TouchSource_.prototype.moveOverOut_ = function(browserEvent, inPointer) { - var event = inPointer; - var pointer = this.pointerMap[event.pointerId]; + const event = inPointer; + const pointer = this.pointerMap[event.pointerId]; // a finger drifted off the screen, ignore it if (!pointer) { return; } - var outEvent = pointer.out; - var outTarget = pointer.outTarget; + const outEvent = pointer.out; + const outTarget = pointer.outTarget; this.dispatcher.move(event, browserEvent); if (outEvent && outTarget !== event.target) { outEvent.relatedTarget = event.target; @@ -433,12 +433,12 @@ _ol_pointer_TouchSource_.prototype.cleanUpPointer_ = function(inPointer) { * @param {Event} inEvent The in event. */ _ol_pointer_TouchSource_.prototype.dedupSynthMouse_ = function(inEvent) { - var lts = this.mouseSource.lastTouches; - var t = inEvent.changedTouches[0]; + const lts = this.mouseSource.lastTouches; + const t = inEvent.changedTouches[0]; // only the primary finger will synth mouse events if (this.isPrimaryTouch_(t)) { // remember x/y of last touch - var lt = [t.clientX, t.clientY]; + const lt = [t.clientX, t.clientY]; lts.push(lt); setTimeout(function() { diff --git a/src/ol/proj.js b/src/ol/proj.js index 79ca1ddd9a..6b0d026e33 100644 --- a/src/ol/proj.js +++ b/src/ol/proj.js @@ -18,7 +18,7 @@ import {add as addTransformFunc, clear as clearTransformFuncs, get as getTransfo * @type {Object.} * @api */ -export var METERS_PER_UNIT = Units.METERS_PER_UNIT; +export const METERS_PER_UNIT = Units.METERS_PER_UNIT; /** @@ -29,9 +29,9 @@ export var METERS_PER_UNIT = Units.METERS_PER_UNIT; * values). */ export function cloneTransform(input, opt_output, opt_dimension) { - var output; + let output; if (opt_output !== undefined) { - for (var i = 0, ii = input.length; i < ii; ++i) { + for (let i = 0, ii = input.length; i < ii; ++i) { opt_output[i] = input[i]; } output = opt_output; @@ -50,7 +50,7 @@ export function cloneTransform(input, opt_output, opt_dimension) { */ export function identityTransform(input, opt_output, opt_dimension) { if (opt_output !== undefined && input !== opt_output) { - for (var i = 0, ii = input.length; i < ii; ++i) { + for (let i = 0, ii = input.length; i < ii; ++i) { opt_output[i] = input[i]; } input = opt_output; @@ -90,11 +90,11 @@ export function addProjections(projections) { * @api */ export function get(projectionLike) { - var projection = null; + let projection = null; if (projectionLike instanceof Projection) { projection = projectionLike; } else if (typeof projectionLike === 'string') { - var code = projectionLike; + const code = projectionLike; projection = _ol_proj_projections_.get(code); } return projection; @@ -123,30 +123,30 @@ export function get(projectionLike) { */ export function getPointResolution(projection, resolution, point, opt_units) { projection = get(projection); - var pointResolution; - var getter = projection.getPointResolutionFunc(); + let pointResolution; + const getter = projection.getPointResolutionFunc(); if (getter) { pointResolution = getter(resolution, point); } else { - var units = projection.getUnits(); + const units = projection.getUnits(); if (units == Units.DEGREES && !opt_units || opt_units == Units.DEGREES) { pointResolution = resolution; } else { // Estimate point resolution by transforming the center pixel to EPSG:4326, // measuring its width and height on the normal sphere, and taking the // average of the width and height. - var toEPSG4326 = getTransformFromProjections(projection, get('EPSG:4326')); - var vertices = [ + const toEPSG4326 = getTransformFromProjections(projection, get('EPSG:4326')); + let vertices = [ point[0] - resolution / 2, point[1], point[0] + resolution / 2, point[1], point[0], point[1] - resolution / 2, point[0], point[1] + resolution / 2 ]; vertices = toEPSG4326(vertices, vertices, 2); - var width = getDistance(vertices.slice(0, 2), vertices.slice(2, 4)); - var height = getDistance(vertices.slice(4, 6), vertices.slice(6, 8)); + const width = getDistance(vertices.slice(0, 2), vertices.slice(2, 4)); + const height = getDistance(vertices.slice(4, 6), vertices.slice(6, 8)); pointResolution = (width + height) / 2; - var metersPerUnit = opt_units ? + const metersPerUnit = opt_units ? Units.METERS_PER_UNIT[opt_units] : projection.getMetersPerUnit(); if (metersPerUnit !== undefined) { @@ -241,10 +241,10 @@ export function createTransformFromCoordinateTransform(coordTransform) { * @return {Array.} Output. */ function(input, opt_output, opt_dimension) { - var length = input.length; - var dimension = opt_dimension !== undefined ? opt_dimension : 2; - var output = opt_output !== undefined ? opt_output : new Array(length); - var point, i, j; + const length = input.length; + const dimension = opt_dimension !== undefined ? opt_dimension : 2; + const output = opt_output !== undefined ? opt_output : new Array(length); + let point, i, j; for (i = 0; i < length; i += dimension) { point = coordTransform([input[i], input[i + 1]]); output[i] = point[0]; @@ -278,8 +278,8 @@ export function createTransformFromCoordinateTransform(coordTransform) { * @api */ export function addCoordinateTransforms(source, destination, forward, inverse) { - var sourceProj = get(source); - var destProj = get(destination); + const sourceProj = get(source); + const destProj = get(destination); addTransformFunc(sourceProj, destProj, createTransformFromCoordinateTransform(forward)); addTransformFunc(destProj, sourceProj, createTransformFromCoordinateTransform(inverse)); } @@ -296,7 +296,7 @@ export function addCoordinateTransforms(source, destination, forward, inverse) { */ export function fromLonLat(coordinate, opt_projection) { return transform(coordinate, 'EPSG:4326', - opt_projection !== undefined ? opt_projection : 'EPSG:3857'); + opt_projection !== undefined ? opt_projection : 'EPSG:3857'); } @@ -310,9 +310,9 @@ export function fromLonLat(coordinate, opt_projection) { * @api */ export function toLonLat(coordinate, opt_projection) { - var lonLat = transform(coordinate, - opt_projection !== undefined ? opt_projection : 'EPSG:3857', 'EPSG:4326'); - var lon = lonLat[0]; + const lonLat = transform(coordinate, + opt_projection !== undefined ? opt_projection : 'EPSG:3857', 'EPSG:4326'); + const lon = lonLat[0]; if (lon < -180 || lon > 180) { lonLat[0] = modulo(lon + 180, 360) - 180; } @@ -334,11 +334,11 @@ export function equivalent(projection1, projection2) { if (projection1 === projection2) { return true; } - var equalUnits = projection1.getUnits() === projection2.getUnits(); + const equalUnits = projection1.getUnits() === projection2.getUnits(); if (projection1.getCode() === projection2.getCode()) { return equalUnits; } else { - var transformFunc = getTransformFromProjections(projection1, projection2); + const transformFunc = getTransformFromProjections(projection1, projection2); return transformFunc === cloneTransform && equalUnits; } } @@ -354,9 +354,9 @@ export function equivalent(projection1, projection2) { * @return {ol.TransformFunction} Transform function. */ export function getTransformFromProjections(sourceProjection, destinationProjection) { - var sourceCode = sourceProjection.getCode(); - var destinationCode = destinationProjection.getCode(); - var transformFunc = getTransformFunc(sourceCode, destinationCode); + const sourceCode = sourceProjection.getCode(); + const destinationCode = destinationProjection.getCode(); + let transformFunc = getTransformFunc(sourceCode, destinationCode); if (!transformFunc) { transformFunc = identityTransform; } @@ -375,10 +375,10 @@ export function getTransformFromProjections(sourceProjection, destinationProject * @api */ export function getTransform(source, destination) { - var sourceProjection = get(source); - var destinationProjection = get(destination); + const sourceProjection = get(source); + const destinationProjection = get(destination); return getTransformFromProjections( - sourceProjection, destinationProjection); + sourceProjection, destinationProjection); } @@ -397,7 +397,7 @@ export function getTransform(source, destination) { * @api */ export function transform(coordinate, source, destination) { - var transformFunc = getTransform(source, destination); + const transformFunc = getTransform(source, destination); return transformFunc(coordinate, undefined, coordinate.length); } @@ -413,7 +413,7 @@ export function transform(coordinate, source, destination) { * @api */ export function transformExtent(extent, source, destination) { - var transformFunc = getTransform(source, destination); + const transformFunc = getTransform(source, destination); return applyTransform(extent, transformFunc); } @@ -427,8 +427,8 @@ export function transformExtent(extent, source, destination) { * @return {ol.Coordinate} Point. */ export function transformWithProjections(point, sourceProjection, destinationProjection) { - var transformFunc = getTransformFromProjections( - sourceProjection, destinationProjection); + const transformFunc = getTransformFromProjections( + sourceProjection, destinationProjection); return transformFunc(point); } @@ -445,10 +445,10 @@ export function addCommon() { // Add transformations to convert EPSG:4326 like coordinates to EPSG:3857 like // coordinates and back. addEquivalentTransforms( - EPSG4326.PROJECTIONS, - EPSG3857.PROJECTIONS, - EPSG3857.fromEPSG4326, - EPSG3857.toEPSG4326); + EPSG4326.PROJECTIONS, + EPSG3857.PROJECTIONS, + EPSG3857.fromEPSG4326, + EPSG3857.toEPSG4326); } addCommon(); diff --git a/src/ol/proj/EPSG3857.js b/src/ol/proj/EPSG3857.js index e72398b3b7..a209fa210a 100644 --- a/src/ol/proj/EPSG3857.js +++ b/src/ol/proj/EPSG3857.js @@ -5,7 +5,7 @@ import {inherits} from '../index.js'; import {cosh} from '../math.js'; import Projection from '../proj/Projection.js'; import Units from '../proj/Units.js'; -var _ol_proj_EPSG3857_ = {}; +const _ol_proj_EPSG3857_ = {}; /** @@ -91,9 +91,9 @@ _ol_proj_EPSG3857_.PROJECTIONS = [ * @return {Array.} Output array of coordinate values. */ _ol_proj_EPSG3857_.fromEPSG4326 = function(input, opt_output, opt_dimension) { - var length = input.length, - dimension = opt_dimension > 1 ? opt_dimension : 2, - output = opt_output; + const length = input.length; + const dimension = opt_dimension > 1 ? opt_dimension : 2; + let output = opt_output; if (output === undefined) { if (dimension > 2) { // preserve values beyond second dimension @@ -102,10 +102,10 @@ _ol_proj_EPSG3857_.fromEPSG4326 = function(input, opt_output, opt_dimension) { output = new Array(length); } } - var halfSize = _ol_proj_EPSG3857_.HALF_SIZE; - for (var i = 0; i < length; i += dimension) { + const halfSize = _ol_proj_EPSG3857_.HALF_SIZE; + for (let i = 0; i < length; i += dimension) { output[i] = halfSize * input[i] / 180; - var y = _ol_proj_EPSG3857_.RADIUS * + let y = _ol_proj_EPSG3857_.RADIUS * Math.log(Math.tan(Math.PI * (input[i + 1] + 90) / 360)); if (y > halfSize) { y = halfSize; @@ -127,9 +127,9 @@ _ol_proj_EPSG3857_.fromEPSG4326 = function(input, opt_output, opt_dimension) { * @return {Array.} Output array of coordinate values. */ _ol_proj_EPSG3857_.toEPSG4326 = function(input, opt_output, opt_dimension) { - var length = input.length, - dimension = opt_dimension > 1 ? opt_dimension : 2, - output = opt_output; + const length = input.length; + const dimension = opt_dimension > 1 ? opt_dimension : 2; + let output = opt_output; if (output === undefined) { if (dimension > 2) { // preserve values beyond second dimension @@ -138,10 +138,10 @@ _ol_proj_EPSG3857_.toEPSG4326 = function(input, opt_output, opt_dimension) { output = new Array(length); } } - for (var i = 0; i < length; i += dimension) { + for (let i = 0; i < length; i += dimension) { output[i] = 180 * input[i] / _ol_proj_EPSG3857_.HALF_SIZE; output[i + 1] = 360 * Math.atan( - Math.exp(input[i + 1] / _ol_proj_EPSG3857_.RADIUS)) / Math.PI - 90; + Math.exp(input[i + 1] / _ol_proj_EPSG3857_.RADIUS)) / Math.PI - 90; } return output; }; diff --git a/src/ol/proj/EPSG4326.js b/src/ol/proj/EPSG4326.js index 645a3eb29c..19a71d1a4a 100644 --- a/src/ol/proj/EPSG4326.js +++ b/src/ol/proj/EPSG4326.js @@ -4,7 +4,7 @@ import {inherits} from '../index.js'; import Projection from '../proj/Projection.js'; import Units from '../proj/Units.js'; -var _ol_proj_EPSG4326_ = {}; +const _ol_proj_EPSG4326_ = {}; /** diff --git a/src/ol/proj/Projection.js b/src/ol/proj/Projection.js index 75b6a916d0..f1184a124c 100644 --- a/src/ol/proj/Projection.js +++ b/src/ol/proj/Projection.js @@ -33,7 +33,7 @@ import Units from '../proj/Units.js'; * @struct * @api */ -var Projection = function(options) { +const Projection = function(options) { /** * @private * @type {string} diff --git a/src/ol/proj/Units.js b/src/ol/proj/Units.js index 8004d54693..d41eb17de8 100644 --- a/src/ol/proj/Units.js +++ b/src/ol/proj/Units.js @@ -6,7 +6,7 @@ * `'us-ft'`. * @enum {string} */ -var Units = { +const Units = { DEGREES: 'degrees', FEET: 'ft', METERS: 'm', diff --git a/src/ol/proj/proj4.js b/src/ol/proj/proj4.js index 765c861d7f..f22f625fbc 100644 --- a/src/ol/proj/proj4.js +++ b/src/ol/proj/proj4.js @@ -17,13 +17,13 @@ import Projection from './Projection.js'; * @api */ export function register(proj4) { - var projCodes = Object.keys(proj4.defs); - var len = projCodes.length; - var i, j; + const projCodes = Object.keys(proj4.defs); + const len = projCodes.length; + let i, j; for (i = 0; i < len; ++i) { - var code = projCodes[i]; + const code = projCodes[i]; if (!get(code)) { - var def = proj4.defs(code); + const def = proj4.defs(code); addProjection(new Projection({ code: code, axisOrientation: def.axis, @@ -33,16 +33,16 @@ export function register(proj4) { } } for (i = 0; i < len; ++i) { - var code1 = projCodes[i]; - var proj1 = get(code1); + const code1 = projCodes[i]; + const proj1 = get(code1); for (j = 0; j < len; ++j) { - var code2 = projCodes[j]; - var proj2 = get(code2); + const code2 = projCodes[j]; + const proj2 = get(code2); if (!getTransform(code1, code2)) { if (proj4.defs[code1] === proj4.defs[code2]) { addEquivalentProjections([proj1, proj2]); } else { - var transform = proj4(code1, code2); + const transform = proj4(code1, code2); addCoordinateTransforms(proj1, proj2, transform.forward, transform.inverse); } } diff --git a/src/ol/proj/projections.js b/src/ol/proj/projections.js index b2148e95fb..218cee22bd 100644 --- a/src/ol/proj/projections.js +++ b/src/ol/proj/projections.js @@ -1,7 +1,7 @@ /** * @module ol/proj/projections */ -var _ol_proj_projections_ = {}; +const _ol_proj_projections_ = {}; /** @@ -25,7 +25,7 @@ _ol_proj_projections_.clear = function() { * @return {ol.proj.Projection} The projection (if cached). */ _ol_proj_projections_.get = function(code) { - var projections = _ol_proj_projections_.cache_; + const projections = _ol_proj_projections_.cache_; return projections[code] || null; }; @@ -36,7 +36,7 @@ _ol_proj_projections_.get = function(code) { * @param {ol.proj.Projection} projection The projection to cache. */ _ol_proj_projections_.add = function(code, projection) { - var projections = _ol_proj_projections_.cache_; + const projections = _ol_proj_projections_.cache_; projections[code] = projection; }; export default _ol_proj_projections_; diff --git a/src/ol/proj/transforms.js b/src/ol/proj/transforms.js index c54e3b93b2..8815d151f3 100644 --- a/src/ol/proj/transforms.js +++ b/src/ol/proj/transforms.js @@ -8,7 +8,7 @@ import _ol_obj_ from '../obj.js'; * @private * @type {Object.>} */ -var transforms = {}; +let transforms = {}; /** @@ -28,8 +28,8 @@ export function clear() { * @param {ol.TransformFunction} transformFn Transform. */ export function add(source, destination, transformFn) { - var sourceCode = source.getCode(); - var destinationCode = destination.getCode(); + const sourceCode = source.getCode(); + const destinationCode = destination.getCode(); if (!(sourceCode in transforms)) { transforms[sourceCode] = {}; } @@ -47,9 +47,9 @@ export function add(source, destination, transformFn) { * @return {ol.TransformFunction} transformFn The unregistered transform. */ export function remove(source, destination) { - var sourceCode = source.getCode(); - var destinationCode = destination.getCode(); - var transform = transforms[sourceCode][destinationCode]; + const sourceCode = source.getCode(); + const destinationCode = destination.getCode(); + const transform = transforms[sourceCode][destinationCode]; delete transforms[sourceCode][destinationCode]; if (_ol_obj_.isEmpty(transforms[sourceCode])) { delete transforms[sourceCode]; @@ -65,7 +65,7 @@ export function remove(source, destination) { * @return {ol.TransformFunction|undefined} The transform function (if found). */ export function get(sourceCode, destinationCode) { - var transform; + let transform; if (sourceCode in transforms && destinationCode in transforms[sourceCode]) { transform = transforms[sourceCode][destinationCode]; } diff --git a/src/ol/render.js b/src/ol/render.js index 7218cbe81a..b32ac483ef 100644 --- a/src/ol/render.js +++ b/src/ol/render.js @@ -4,7 +4,7 @@ import _ol_has_ from './has.js'; import _ol_transform_ from './transform.js'; import CanvasImmediateRenderer from './render/canvas/Immediate.js'; -var _ol_render_ = {}; +const _ol_render_ = {}; /** @@ -28,19 +28,19 @@ var _ol_render_ = {}; * @api */ _ol_render_.toContext = function(context, opt_options) { - var canvas = context.canvas; - var options = opt_options ? opt_options : {}; - var pixelRatio = options.pixelRatio || _ol_has_.DEVICE_PIXEL_RATIO; - var size = options.size; + const canvas = context.canvas; + const options = opt_options ? opt_options : {}; + const pixelRatio = options.pixelRatio || _ol_has_.DEVICE_PIXEL_RATIO; + const size = options.size; if (size) { canvas.width = size[0] * pixelRatio; canvas.height = size[1] * pixelRatio; canvas.style.width = size[0] + 'px'; canvas.style.height = size[1] + 'px'; } - var extent = [0, 0, canvas.width, canvas.height]; - var transform = _ol_transform_.scale(_ol_transform_.create(), pixelRatio, pixelRatio); + const extent = [0, 0, canvas.width, canvas.height]; + const transform = _ol_transform_.scale(_ol_transform_.create(), pixelRatio, pixelRatio); return new CanvasImmediateRenderer(context, pixelRatio, extent, transform, - 0); + 0); }; export default _ol_render_; diff --git a/src/ol/render/Box.js b/src/ol/render/Box.js index a58698770c..3fe787a1b8 100644 --- a/src/ol/render/Box.js +++ b/src/ol/render/Box.js @@ -12,7 +12,7 @@ import Polygon from '../geom/Polygon.js'; * @extends {ol.Disposable} * @param {string} className CSS class name. */ -var _ol_render_Box_ = function(className) { +const _ol_render_Box_ = function(className) { /** * @type {ol.geom.Polygon} @@ -63,10 +63,10 @@ _ol_render_Box_.prototype.disposeInternal = function() { * @private */ _ol_render_Box_.prototype.render_ = function() { - var startPixel = this.startPixel_; - var endPixel = this.endPixel_; - var px = 'px'; - var style = this.element_.style; + const startPixel = this.startPixel_; + const endPixel = this.endPixel_; + const px = 'px'; + const style = this.element_.style; style.left = Math.min(startPixel[0], endPixel[0]) + px; style.top = Math.min(startPixel[1], endPixel[1]) + px; style.width = Math.abs(endPixel[0] - startPixel[0]) + px; @@ -80,7 +80,7 @@ _ol_render_Box_.prototype.render_ = function() { _ol_render_Box_.prototype.setMap = function(map) { if (this.map_) { this.map_.getOverlayContainer().removeChild(this.element_); - var style = this.element_.style; + const style = this.element_.style; style.left = style.top = style.width = style.height = 'inherit'; } this.map_ = map; @@ -106,15 +106,15 @@ _ol_render_Box_.prototype.setPixels = function(startPixel, endPixel) { * Creates or updates the cached geometry. */ _ol_render_Box_.prototype.createOrUpdateGeometry = function() { - var startPixel = this.startPixel_; - var endPixel = this.endPixel_; - var pixels = [ + const startPixel = this.startPixel_; + const endPixel = this.endPixel_; + const pixels = [ startPixel, [startPixel[0], endPixel[1]], endPixel, [endPixel[0], startPixel[1]] ]; - var coordinates = pixels.map(this.map_.getCoordinateFromPixel, this.map_); + const coordinates = pixels.map(this.map_.getCoordinateFromPixel, this.map_); // close the polygon coordinates[4] = coordinates[0].slice(); if (!this.geometry_) { diff --git a/src/ol/render/Event.js b/src/ol/render/Event.js index ce8f075264..bcc026a067 100644 --- a/src/ol/render/Event.js +++ b/src/ol/render/Event.js @@ -14,9 +14,9 @@ import Event from '../events/Event.js'; * @param {?CanvasRenderingContext2D=} opt_context Context. * @param {?ol.webgl.Context=} opt_glContext WebGL Context. */ -var RenderEvent = function( - type, opt_vectorContext, opt_frameState, opt_context, - opt_glContext) { +const RenderEvent = function( + type, opt_vectorContext, opt_frameState, opt_context, + opt_glContext) { Event.call(this, type); diff --git a/src/ol/render/Feature.js b/src/ol/render/Feature.js index c129fa8653..8731d7455f 100644 --- a/src/ol/render/Feature.js +++ b/src/ol/render/Feature.js @@ -24,7 +24,7 @@ import _ol_transform_ from '../transform.js'; * @param {Object.} properties Properties. * @param {number|string|undefined} id Feature id. */ -var RenderFeature = function(type, flatCoordinates, ends, properties, id) { +const RenderFeature = function(type, flatCoordinates, ends, properties, id) { /** * @private * @type {ol.Extent|undefined} @@ -112,7 +112,7 @@ RenderFeature.prototype.getExtent = function() { this.extent_ = this.type_ === GeometryType.POINT ? createOrUpdateFromCoordinate(this.flatCoordinates_) : createOrUpdateFromFlatCoordinates( - this.flatCoordinates_, 0, this.flatCoordinates_.length, 2); + this.flatCoordinates_, 0, this.flatCoordinates_.length, 2); } return this.extent_; @@ -124,9 +124,9 @@ RenderFeature.prototype.getExtent = function() { */ RenderFeature.prototype.getFlatInteriorPoint = function() { if (!this.flatInteriorPoints_) { - var flatCenter = getCenter(this.getExtent()); + const flatCenter = getCenter(this.getExtent()); this.flatInteriorPoints_ = _ol_geom_flat_interiorpoint_.linearRings( - this.flatCoordinates_, 0, this.ends_, 2, flatCenter, 0); + this.flatCoordinates_, 0, this.ends_, 2, flatCenter, 0); } return this.flatInteriorPoints_; }; @@ -137,10 +137,10 @@ RenderFeature.prototype.getFlatInteriorPoint = function() { */ RenderFeature.prototype.getFlatInteriorPoints = function() { if (!this.flatInteriorPoints_) { - var flatCenters = _ol_geom_flat_center_.linearRingss( - this.flatCoordinates_, 0, this.ends_, 2); + const flatCenters = _ol_geom_flat_center_.linearRingss( + this.flatCoordinates_, 0, this.ends_, 2); this.flatInteriorPoints_ = _ol_geom_flat_interiorpoint_.linearRingss( - this.flatCoordinates_, 0, this.ends_, 2, flatCenters); + this.flatCoordinates_, 0, this.ends_, 2, flatCenters); } return this.flatInteriorPoints_; }; @@ -152,7 +152,7 @@ RenderFeature.prototype.getFlatInteriorPoints = function() { RenderFeature.prototype.getFlatMidpoint = function() { if (!this.flatMidpoints_) { this.flatMidpoints_ = _ol_geom_flat_interpolate_.lineString( - this.flatCoordinates_, 0, this.flatCoordinates_.length, 2, 0.5); + this.flatCoordinates_, 0, this.flatCoordinates_.length, 2, 0.5); } return this.flatMidpoints_; }; @@ -164,13 +164,13 @@ RenderFeature.prototype.getFlatMidpoint = function() { RenderFeature.prototype.getFlatMidpoints = function() { if (!this.flatMidpoints_) { this.flatMidpoints_ = []; - var flatCoordinates = this.flatCoordinates_; - var offset = 0; - var ends = this.ends_; - for (var i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; - var midpoint = _ol_geom_flat_interpolate_.lineString( - flatCoordinates, offset, end, 2, 0.5); + const flatCoordinates = this.flatCoordinates_; + let offset = 0; + const ends = this.ends_; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const midpoint = _ol_geom_flat_interpolate_.lineString( + flatCoordinates, offset, end, 2, 0.5); extend(this.flatMidpoints_, midpoint); offset = end; } @@ -264,15 +264,15 @@ RenderFeature.prototype.getType = function() { * @param {ol.ProjectionLike} destination The desired projection. */ RenderFeature.prototype.transform = function(source, destination) { - var pixelExtent = source.getExtent(); - var projectedExtent = source.getWorldExtent(); - var scale = getHeight(projectedExtent) / getHeight(pixelExtent); - var transform = this.tmpTransform_; + const pixelExtent = source.getExtent(); + const projectedExtent = source.getWorldExtent(); + const scale = getHeight(projectedExtent) / getHeight(pixelExtent); + const transform = this.tmpTransform_; _ol_transform_.compose(transform, - projectedExtent[0], projectedExtent[3], - scale, -scale, 0, - 0, 0); + projectedExtent[0], projectedExtent[3], + scale, -scale, 0, + 0, 0); _ol_geom_flat_transform_.transform2D(this.flatCoordinates_, 0, this.flatCoordinates_.length, 2, - transform, this.flatCoordinates_); + transform, this.flatCoordinates_); }; export default RenderFeature; diff --git a/src/ol/render/ReplayGroup.js b/src/ol/render/ReplayGroup.js index caf6e87350..20d461a21e 100644 --- a/src/ol/render/ReplayGroup.js +++ b/src/ol/render/ReplayGroup.js @@ -6,7 +6,7 @@ * @constructor * @abstract */ -var _ol_render_ReplayGroup_ = function() {}; +const _ol_render_ReplayGroup_ = function() {}; /** diff --git a/src/ol/render/VectorContext.js b/src/ol/render/VectorContext.js index 993c8d5896..61a4c4848a 100644 --- a/src/ol/render/VectorContext.js +++ b/src/ol/render/VectorContext.js @@ -9,7 +9,7 @@ * @struct * @api */ -var VectorContext = function() { +const VectorContext = function() { }; diff --git a/src/ol/render/canvas.js b/src/ol/render/canvas.js index 2448e127b2..9c8f8d8154 100644 --- a/src/ol/render/canvas.js +++ b/src/ol/render/canvas.js @@ -6,7 +6,7 @@ import {createCanvasContext2D} from '../dom.js'; import _ol_obj_ from '../obj.js'; import LRUCache from '../structs/LRUCache.js'; import _ol_transform_ from '../transform.js'; -var _ol_render_canvas_ = {}; +const _ol_render_canvas_ = {}; /** @@ -122,25 +122,25 @@ _ol_render_canvas_.textHeights_ = {}; * @param {string} fontSpec CSS font spec. */ _ol_render_canvas_.checkFont = (function() { - var retries = 60; - var checked = _ol_render_canvas_.checkedFonts_; - var labelCache = _ol_render_canvas_.labelCache; - var size = '32px '; - var referenceFonts = ['monospace', 'serif']; - var len = referenceFonts.length; - var text = 'wmytzilWMYTZIL@#/&?$%10'; - var interval, referenceWidth; + const retries = 60; + const checked = _ol_render_canvas_.checkedFonts_; + const labelCache = _ol_render_canvas_.labelCache; + const size = '32px '; + const referenceFonts = ['monospace', 'serif']; + const len = referenceFonts.length; + const text = 'wmytzilWMYTZIL@#/&?$%10'; + let interval, referenceWidth; function isAvailable(font) { - var context = _ol_render_canvas_.getMeasureContext(); - var available = true; - for (var i = 0; i < len; ++i) { - var referenceFont = referenceFonts[i]; + const context = _ol_render_canvas_.getMeasureContext(); + let available = true; + for (let i = 0; i < len; ++i) { + const referenceFont = referenceFonts[i]; context.font = size + referenceFont; referenceWidth = context.measureText(text).width; if (font != referenceFont) { context.font = size + font + ',' + referenceFont; - var width = context.measureText(text).width; + const width = context.measureText(text).width; // If width and referenceWidth are the same, then the fallback was used // instead of the font we wanted, so the font is not available. available = available && width != referenceWidth; @@ -150,8 +150,8 @@ _ol_render_canvas_.checkFont = (function() { } function check() { - var done = true; - for (var font in checked) { + let done = true; + for (const font in checked) { if (checked[font] < retries) { if (isAvailable(font)) { checked[font] = retries; @@ -172,12 +172,12 @@ _ol_render_canvas_.checkFont = (function() { } return function(fontSpec) { - var fontFamilies = getFontFamilies(fontSpec); + const fontFamilies = getFontFamilies(fontSpec); if (!fontFamilies) { return; } - for (var i = 0, ii = fontFamilies.length; i < ii; ++i) { - var fontFamily = fontFamilies[i]; + for (let i = 0, ii = fontFamilies.length; i < ii; ++i) { + const fontFamily = fontFamilies[i]; if (!(fontFamily in checked)) { checked[fontFamily] = retries; if (!isAvailable(fontFamily)) { @@ -196,7 +196,7 @@ _ol_render_canvas_.checkFont = (function() { * @return {CanvasRenderingContext2D} Measure context. */ _ol_render_canvas_.getMeasureContext = function() { - var context = _ol_render_canvas_.measureContext_; + let context = _ol_render_canvas_.measureContext_; if (!context) { context = _ol_render_canvas_.measureContext_ = createCanvasContext2D(1, 1); } @@ -209,10 +209,10 @@ _ol_render_canvas_.getMeasureContext = function() { * @return {ol.Size} Measurement. */ _ol_render_canvas_.measureTextHeight = (function() { - var span; - var heights = _ol_render_canvas_.textHeights_; + let span; + const heights = _ol_render_canvas_.textHeights_; return function(font) { - var height = heights[font]; + let height = heights[font]; if (height == undefined) { if (!span) { span = document.createElement('span'); @@ -237,7 +237,7 @@ _ol_render_canvas_.measureTextHeight = (function() { * @return {number} Width. */ _ol_render_canvas_.measureTextWidth = function(font, text) { - var measureContext = _ol_render_canvas_.getMeasureContext(); + const measureContext = _ol_render_canvas_.getMeasureContext(); if (font != measureContext.font) { measureContext.font = font; } @@ -277,8 +277,8 @@ _ol_render_canvas_.resetTransform_ = _ol_transform_.create(); * @param {number} scale Scale. */ _ol_render_canvas_.drawImage = function(context, - transform, opacity, image, originX, originY, w, h, x, y, scale) { - var alpha; + transform, opacity, image, originX, originY, w, h, x, y, scale) { + let alpha; if (opacity != 1) { alpha = context.globalAlpha; context.globalAlpha = alpha * opacity; diff --git a/src/ol/render/canvas/ImageReplay.js b/src/ol/render/canvas/ImageReplay.js index 1fcb869226..a0039f4d64 100644 --- a/src/ol/render/canvas/ImageReplay.js +++ b/src/ol/render/canvas/ImageReplay.js @@ -16,10 +16,10 @@ import _ol_render_canvas_Replay_ from '../canvas/Replay.js'; * @param {?} declutterTree Declutter tree. * @struct */ -var _ol_render_canvas_ImageReplay_ = function( - tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree) { +const _ol_render_canvas_ImageReplay_ = function( + tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree) { _ol_render_canvas_Replay_.call(this, - tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree); + tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree); /** * @private @@ -120,7 +120,7 @@ inherits(_ol_render_canvas_ImageReplay_, _ol_render_canvas_Replay_); */ _ol_render_canvas_ImageReplay_.prototype.drawCoordinates_ = function(flatCoordinates, offset, end, stride) { return this.appendFlatCoordinates( - flatCoordinates, offset, end, stride, false, false); + flatCoordinates, offset, end, stride, false, false); }; @@ -132,11 +132,11 @@ _ol_render_canvas_ImageReplay_.prototype.drawPoint = function(pointGeometry, fea return; } this.beginGeometry(pointGeometry, feature); - var flatCoordinates = pointGeometry.getFlatCoordinates(); - var stride = pointGeometry.getStride(); - var myBegin = this.coordinates.length; - var myEnd = this.drawCoordinates_( - flatCoordinates, 0, flatCoordinates.length, stride); + const flatCoordinates = pointGeometry.getFlatCoordinates(); + const stride = pointGeometry.getStride(); + const myBegin = this.coordinates.length; + const myEnd = this.drawCoordinates_( + flatCoordinates, 0, flatCoordinates.length, stride); this.instructions.push([ _ol_render_canvas_Instruction_.DRAW_IMAGE, myBegin, myEnd, this.image_, // Remaining arguments to DRAW_IMAGE are in alphabetical order @@ -164,11 +164,11 @@ _ol_render_canvas_ImageReplay_.prototype.drawMultiPoint = function(multiPointGeo return; } this.beginGeometry(multiPointGeometry, feature); - var flatCoordinates = multiPointGeometry.getFlatCoordinates(); - var stride = multiPointGeometry.getStride(); - var myBegin = this.coordinates.length; - var myEnd = this.drawCoordinates_( - flatCoordinates, 0, flatCoordinates.length, stride); + const flatCoordinates = multiPointGeometry.getFlatCoordinates(); + const stride = multiPointGeometry.getStride(); + const myBegin = this.coordinates.length; + const myEnd = this.drawCoordinates_( + flatCoordinates, 0, flatCoordinates.length, stride); this.instructions.push([ _ol_render_canvas_Instruction_.DRAW_IMAGE, myBegin, myEnd, this.image_, // Remaining arguments to DRAW_IMAGE are in alphabetical order @@ -214,11 +214,11 @@ _ol_render_canvas_ImageReplay_.prototype.finish = function() { * @inheritDoc */ _ol_render_canvas_ImageReplay_.prototype.setImageStyle = function(imageStyle, declutterGroup) { - var anchor = imageStyle.getAnchor(); - var size = imageStyle.getSize(); - var hitDetectionImage = imageStyle.getHitDetectionImage(1); - var image = imageStyle.getImage(1); - var origin = imageStyle.getOrigin(); + const anchor = imageStyle.getAnchor(); + const size = imageStyle.getSize(); + const hitDetectionImage = imageStyle.getHitDetectionImage(1); + const image = imageStyle.getImage(1); + const origin = imageStyle.getOrigin(); this.anchorX_ = anchor[0]; this.anchorY_ = anchor[1]; this.declutterGroup_ = /** @type {ol.DeclutterGroup} */ (declutterGroup); diff --git a/src/ol/render/canvas/Immediate.js b/src/ol/render/canvas/Immediate.js index 0bfea34b9e..af6416b908 100644 --- a/src/ol/render/canvas/Immediate.js +++ b/src/ol/render/canvas/Immediate.js @@ -35,7 +35,7 @@ import _ol_transform_ from '../../transform.js'; * @param {number} viewRotation View rotation. * @struct */ -var CanvasImmediateRenderer = function(context, pixelRatio, extent, transform, viewRotation) { +const CanvasImmediateRenderer = function(context, pixelRatio, extent, transform, viewRotation) { VectorContext.call(this); /** @@ -252,40 +252,40 @@ CanvasImmediateRenderer.prototype.drawImages_ = function(flatCoordinates, offset if (!this.image_) { return; } - var pixelCoordinates = _ol_geom_flat_transform_.transform2D( - flatCoordinates, offset, end, 2, this.transform_, - this.pixelCoordinates_); - var context = this.context_; - var localTransform = this.tmpLocalTransform_; - var alpha = context.globalAlpha; + const pixelCoordinates = _ol_geom_flat_transform_.transform2D( + flatCoordinates, offset, end, 2, this.transform_, + this.pixelCoordinates_); + const context = this.context_; + const localTransform = this.tmpLocalTransform_; + const alpha = context.globalAlpha; if (this.imageOpacity_ != 1) { context.globalAlpha = alpha * this.imageOpacity_; } - var rotation = this.imageRotation_; + let rotation = this.imageRotation_; if (this.imageRotateWithView_) { rotation += this.viewRotation_; } - var i, ii; + let i, ii; for (i = 0, ii = pixelCoordinates.length; i < ii; i += 2) { - var x = pixelCoordinates[i] - this.imageAnchorX_; - var y = pixelCoordinates[i + 1] - this.imageAnchorY_; + let x = pixelCoordinates[i] - this.imageAnchorX_; + let y = pixelCoordinates[i + 1] - this.imageAnchorY_; if (this.imageSnapToPixel_) { x = Math.round(x); y = Math.round(y); } if (rotation !== 0 || this.imageScale_ != 1) { - var centerX = x + this.imageAnchorX_; - var centerY = y + this.imageAnchorY_; + const centerX = x + this.imageAnchorX_; + const centerY = y + this.imageAnchorY_; _ol_transform_.compose(localTransform, - centerX, centerY, - this.imageScale_, this.imageScale_, - rotation, - -centerX, -centerY); + centerX, centerY, + this.imageScale_, this.imageScale_, + rotation, + -centerX, -centerY); context.setTransform.apply(context, localTransform); } context.drawImage(this.image_, this.imageOriginX_, this.imageOriginY_, - this.imageWidth_, this.imageHeight_, x, y, - this.imageWidth_, this.imageHeight_); + this.imageWidth_, this.imageHeight_, x, y, + this.imageWidth_, this.imageHeight_); } if (rotation !== 0 || this.imageScale_ != 1) { context.setTransform(1, 0, 0, 1, 0, 0); @@ -314,23 +314,23 @@ CanvasImmediateRenderer.prototype.drawText_ = function(flatCoordinates, offset, this.setContextStrokeState_(this.textStrokeState_); } this.setContextTextState_(this.textState_); - var pixelCoordinates = _ol_geom_flat_transform_.transform2D( - flatCoordinates, offset, end, stride, this.transform_, - this.pixelCoordinates_); - var context = this.context_; - var rotation = this.textRotation_; + const pixelCoordinates = _ol_geom_flat_transform_.transform2D( + flatCoordinates, offset, end, stride, this.transform_, + this.pixelCoordinates_); + const context = this.context_; + let rotation = this.textRotation_; if (this.textRotateWithView_) { rotation += this.viewRotation_; } for (; offset < end; offset += stride) { - var x = pixelCoordinates[offset] + this.textOffsetX_; - var y = pixelCoordinates[offset + 1] + this.textOffsetY_; + const x = pixelCoordinates[offset] + this.textOffsetX_; + const y = pixelCoordinates[offset + 1] + this.textOffsetY_; if (rotation !== 0 || this.textScale_ != 1) { - var localTransform = _ol_transform_.compose(this.tmpLocalTransform_, - x, y, - this.textScale_, this.textScale_, - rotation, - -x, -y); + const localTransform = _ol_transform_.compose(this.tmpLocalTransform_, + x, y, + this.textScale_, this.textScale_, + rotation, + -x, -y); context.setTransform.apply(context, localTransform); } if (this.textStrokeState_) { @@ -356,16 +356,16 @@ CanvasImmediateRenderer.prototype.drawText_ = function(flatCoordinates, offset, * @return {number} end End. */ CanvasImmediateRenderer.prototype.moveToLineTo_ = function(flatCoordinates, offset, end, stride, close) { - var context = this.context_; - var pixelCoordinates = _ol_geom_flat_transform_.transform2D( - flatCoordinates, offset, end, stride, this.transform_, - this.pixelCoordinates_); + const context = this.context_; + const pixelCoordinates = _ol_geom_flat_transform_.transform2D( + flatCoordinates, offset, end, stride, this.transform_, + this.pixelCoordinates_); context.moveTo(pixelCoordinates[0], pixelCoordinates[1]); - var length = pixelCoordinates.length; + let length = pixelCoordinates.length; if (close) { length -= 2; } - for (var i = 2; i < length; i += 2) { + for (let i = 2; i < length; i += 2) { context.lineTo(pixelCoordinates[i], pixelCoordinates[i + 1]); } if (close) { @@ -384,10 +384,10 @@ CanvasImmediateRenderer.prototype.moveToLineTo_ = function(flatCoordinates, offs * @return {number} End. */ CanvasImmediateRenderer.prototype.drawRings_ = function(flatCoordinates, offset, ends, stride) { - var i, ii; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { offset = this.moveToLineTo_( - flatCoordinates, offset, ends[i], stride, true); + flatCoordinates, offset, ends[i], stride, true); } return offset; }; @@ -412,15 +412,15 @@ CanvasImmediateRenderer.prototype.drawCircle = function(geometry) { if (this.strokeState_) { this.setContextStrokeState_(this.strokeState_); } - var pixelCoordinates = SimpleGeometry.transform2D( - geometry, this.transform_, this.pixelCoordinates_); - var dx = pixelCoordinates[2] - pixelCoordinates[0]; - var dy = pixelCoordinates[3] - pixelCoordinates[1]; - var radius = Math.sqrt(dx * dx + dy * dy); - var context = this.context_; + const pixelCoordinates = SimpleGeometry.transform2D( + geometry, this.transform_, this.pixelCoordinates_); + const dx = pixelCoordinates[2] - pixelCoordinates[0]; + const dy = pixelCoordinates[3] - pixelCoordinates[1]; + const radius = Math.sqrt(dx * dx + dy * dy); + const context = this.context_; context.beginPath(); context.arc( - pixelCoordinates[0], pixelCoordinates[1], radius, 0, 2 * Math.PI); + pixelCoordinates[0], pixelCoordinates[1], radius, 0, 2 * Math.PI); if (this.fillState_) { context.fill(); } @@ -458,7 +458,7 @@ CanvasImmediateRenderer.prototype.setStyle = function(style) { * @api */ CanvasImmediateRenderer.prototype.drawGeometry = function(geometry) { - var type = geometry.getType(); + const type = geometry.getType(); switch (type) { case GeometryType.POINT: this.drawPoint(/** @type {ol.geom.Point} */ (geometry)); @@ -501,7 +501,7 @@ CanvasImmediateRenderer.prototype.drawGeometry = function(geometry) { * @api */ CanvasImmediateRenderer.prototype.drawFeature = function(feature, style) { - var geometry = style.getGeometryFunction()(feature); + const geometry = style.getGeometryFunction()(feature); if (!geometry || !intersects(this.extent_, geometry.getExtent())) { return; } @@ -518,8 +518,8 @@ CanvasImmediateRenderer.prototype.drawFeature = function(feature, style) { * @override */ CanvasImmediateRenderer.prototype.drawGeometryCollection = function(geometry) { - var geometries = geometry.getGeometriesArray(); - var i, ii; + const geometries = geometry.getGeometriesArray(); + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { this.drawGeometry(geometries[i]); } @@ -534,8 +534,8 @@ CanvasImmediateRenderer.prototype.drawGeometryCollection = function(geometry) { * @override */ CanvasImmediateRenderer.prototype.drawPoint = function(geometry) { - var flatCoordinates = geometry.getFlatCoordinates(); - var stride = geometry.getStride(); + const flatCoordinates = geometry.getFlatCoordinates(); + const stride = geometry.getStride(); if (this.image_) { this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride); } @@ -553,8 +553,8 @@ CanvasImmediateRenderer.prototype.drawPoint = function(geometry) { * @override */ CanvasImmediateRenderer.prototype.drawMultiPoint = function(geometry) { - var flatCoordinates = geometry.getFlatCoordinates(); - var stride = geometry.getStride(); + const flatCoordinates = geometry.getFlatCoordinates(); + const stride = geometry.getStride(); if (this.image_) { this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride); } @@ -577,15 +577,15 @@ CanvasImmediateRenderer.prototype.drawLineString = function(geometry) { } if (this.strokeState_) { this.setContextStrokeState_(this.strokeState_); - var context = this.context_; - var flatCoordinates = geometry.getFlatCoordinates(); + const context = this.context_; + const flatCoordinates = geometry.getFlatCoordinates(); context.beginPath(); this.moveToLineTo_(flatCoordinates, 0, flatCoordinates.length, - geometry.getStride(), false); + geometry.getStride(), false); context.stroke(); } if (this.text_ !== '') { - var flatMidpoint = geometry.getFlatMidpoint(); + const flatMidpoint = geometry.getFlatMidpoint(); this.drawText_(flatMidpoint, 0, 2, 2); } }; @@ -600,27 +600,27 @@ CanvasImmediateRenderer.prototype.drawLineString = function(geometry) { * @override */ CanvasImmediateRenderer.prototype.drawMultiLineString = function(geometry) { - var geometryExtent = geometry.getExtent(); + const geometryExtent = geometry.getExtent(); if (!intersects(this.extent_, geometryExtent)) { return; } if (this.strokeState_) { this.setContextStrokeState_(this.strokeState_); - var context = this.context_; - var flatCoordinates = geometry.getFlatCoordinates(); - var offset = 0; - var ends = geometry.getEnds(); - var stride = geometry.getStride(); + const context = this.context_; + const flatCoordinates = geometry.getFlatCoordinates(); + let offset = 0; + const ends = geometry.getEnds(); + const stride = geometry.getStride(); context.beginPath(); - var i, ii; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { offset = this.moveToLineTo_( - flatCoordinates, offset, ends[i], stride, false); + flatCoordinates, offset, ends[i], stride, false); } context.stroke(); } if (this.text_ !== '') { - var flatMidpoints = geometry.getFlatMidpoints(); + const flatMidpoints = geometry.getFlatMidpoints(); this.drawText_(flatMidpoints, 0, flatMidpoints.length, 2); } }; @@ -644,10 +644,10 @@ CanvasImmediateRenderer.prototype.drawPolygon = function(geometry) { if (this.strokeState_) { this.setContextStrokeState_(this.strokeState_); } - var context = this.context_; + const context = this.context_; context.beginPath(); this.drawRings_(geometry.getOrientedFlatCoordinates(), - 0, geometry.getEnds(), geometry.getStride()); + 0, geometry.getEnds(), geometry.getStride()); if (this.fillState_) { context.fill(); } @@ -656,7 +656,7 @@ CanvasImmediateRenderer.prototype.drawPolygon = function(geometry) { } } if (this.text_ !== '') { - var flatInteriorPoint = geometry.getFlatInteriorPoint(); + const flatInteriorPoint = geometry.getFlatInteriorPoint(); this.drawText_(flatInteriorPoint, 0, 2, 2); } }; @@ -679,15 +679,15 @@ CanvasImmediateRenderer.prototype.drawMultiPolygon = function(geometry) { if (this.strokeState_) { this.setContextStrokeState_(this.strokeState_); } - var context = this.context_; - var flatCoordinates = geometry.getOrientedFlatCoordinates(); - var offset = 0; - var endss = geometry.getEndss(); - var stride = geometry.getStride(); - var i, ii; + const context = this.context_; + const flatCoordinates = geometry.getOrientedFlatCoordinates(); + let offset = 0; + const endss = geometry.getEndss(); + const stride = geometry.getStride(); + let i, ii; context.beginPath(); for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; + const ends = endss[i]; offset = this.drawRings_(flatCoordinates, offset, ends, stride); } if (this.fillState_) { @@ -698,7 +698,7 @@ CanvasImmediateRenderer.prototype.drawMultiPolygon = function(geometry) { } } if (this.text_ !== '') { - var flatInteriorPoints = geometry.getFlatInteriorPoints(); + const flatInteriorPoints = geometry.getFlatInteriorPoints(); this.drawText_(flatInteriorPoints, 0, flatInteriorPoints.length, 2); } }; @@ -709,8 +709,8 @@ CanvasImmediateRenderer.prototype.drawMultiPolygon = function(geometry) { * @private */ CanvasImmediateRenderer.prototype.setContextFillState_ = function(fillState) { - var context = this.context_; - var contextFillState = this.contextFillState_; + const context = this.context_; + const contextFillState = this.contextFillState_; if (!contextFillState) { context.fillStyle = fillState.fillStyle; this.contextFillState_ = { @@ -729,8 +729,8 @@ CanvasImmediateRenderer.prototype.setContextFillState_ = function(fillState) { * @private */ CanvasImmediateRenderer.prototype.setContextStrokeState_ = function(strokeState) { - var context = this.context_; - var contextStrokeState = this.contextStrokeState_; + const context = this.context_; + const contextStrokeState = this.contextStrokeState_; if (!contextStrokeState) { context.lineCap = strokeState.lineCap; if (_ol_has_.CANVAS_LINE_DASH) { @@ -786,9 +786,9 @@ CanvasImmediateRenderer.prototype.setContextStrokeState_ = function(strokeState) * @private */ CanvasImmediateRenderer.prototype.setContextTextState_ = function(textState) { - var context = this.context_; - var contextTextState = this.contextTextState_; - var textAlign = textState.textAlign ? + const context = this.context_; + const contextTextState = this.contextTextState_; + const textAlign = textState.textAlign ? textState.textAlign : _ol_render_canvas_.defaultTextAlign; if (!contextTextState) { context.font = textState.font; @@ -826,7 +826,7 @@ CanvasImmediateRenderer.prototype.setFillStrokeStyle = function(fillStyle, strok if (!fillStyle) { this.fillState_ = null; } else { - var fillStyleColor = fillStyle.getColor(); + const fillStyleColor = fillStyle.getColor(); this.fillState_ = { fillStyle: asColorLike(fillStyleColor ? fillStyleColor : _ol_render_canvas_.defaultFillStyle) @@ -835,13 +835,13 @@ CanvasImmediateRenderer.prototype.setFillStrokeStyle = function(fillStyle, strok if (!strokeStyle) { this.strokeState_ = null; } else { - var strokeStyleColor = strokeStyle.getColor(); - var strokeStyleLineCap = strokeStyle.getLineCap(); - var strokeStyleLineDash = strokeStyle.getLineDash(); - var strokeStyleLineDashOffset = strokeStyle.getLineDashOffset(); - var strokeStyleLineJoin = strokeStyle.getLineJoin(); - var strokeStyleWidth = strokeStyle.getWidth(); - var strokeStyleMiterLimit = strokeStyle.getMiterLimit(); + const strokeStyleColor = strokeStyle.getColor(); + const strokeStyleLineCap = strokeStyle.getLineCap(); + const strokeStyleLineDash = strokeStyle.getLineDash(); + const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset(); + const strokeStyleLineJoin = strokeStyle.getLineJoin(); + const strokeStyleWidth = strokeStyle.getWidth(); + const strokeStyleMiterLimit = strokeStyle.getMiterLimit(); this.strokeState_ = { lineCap: strokeStyleLineCap !== undefined ? strokeStyleLineCap : _ol_render_canvas_.defaultLineCap, @@ -873,11 +873,11 @@ CanvasImmediateRenderer.prototype.setImageStyle = function(imageStyle) { if (!imageStyle) { this.image_ = null; } else { - var imageAnchor = imageStyle.getAnchor(); + const imageAnchor = imageStyle.getAnchor(); // FIXME pixel ratio - var imageImage = imageStyle.getImage(1); - var imageOrigin = imageStyle.getOrigin(); - var imageSize = imageStyle.getSize(); + const imageImage = imageStyle.getImage(1); + const imageOrigin = imageStyle.getOrigin(); + const imageSize = imageStyle.getSize(); this.imageAnchorX_ = imageAnchor[0]; this.imageAnchorY_ = imageAnchor[1]; this.imageHeight_ = imageSize[1]; @@ -905,27 +905,27 @@ CanvasImmediateRenderer.prototype.setTextStyle = function(textStyle) { if (!textStyle) { this.text_ = ''; } else { - var textFillStyle = textStyle.getFill(); + const textFillStyle = textStyle.getFill(); if (!textFillStyle) { this.textFillState_ = null; } else { - var textFillStyleColor = textFillStyle.getColor(); + const textFillStyleColor = textFillStyle.getColor(); this.textFillState_ = { fillStyle: asColorLike(textFillStyleColor ? textFillStyleColor : _ol_render_canvas_.defaultFillStyle) }; } - var textStrokeStyle = textStyle.getStroke(); + const textStrokeStyle = textStyle.getStroke(); if (!textStrokeStyle) { this.textStrokeState_ = null; } else { - var textStrokeStyleColor = textStrokeStyle.getColor(); - var textStrokeStyleLineCap = textStrokeStyle.getLineCap(); - var textStrokeStyleLineDash = textStrokeStyle.getLineDash(); - var textStrokeStyleLineDashOffset = textStrokeStyle.getLineDashOffset(); - var textStrokeStyleLineJoin = textStrokeStyle.getLineJoin(); - var textStrokeStyleWidth = textStrokeStyle.getWidth(); - var textStrokeStyleMiterLimit = textStrokeStyle.getMiterLimit(); + const textStrokeStyleColor = textStrokeStyle.getColor(); + const textStrokeStyleLineCap = textStrokeStyle.getLineCap(); + const textStrokeStyleLineDash = textStrokeStyle.getLineDash(); + const textStrokeStyleLineDashOffset = textStrokeStyle.getLineDashOffset(); + const textStrokeStyleLineJoin = textStrokeStyle.getLineJoin(); + const textStrokeStyleWidth = textStrokeStyle.getWidth(); + const textStrokeStyleMiterLimit = textStrokeStyle.getMiterLimit(); this.textStrokeState_ = { lineCap: textStrokeStyleLineCap !== undefined ? textStrokeStyleLineCap : _ol_render_canvas_.defaultLineCap, @@ -943,15 +943,15 @@ CanvasImmediateRenderer.prototype.setTextStyle = function(textStyle) { textStrokeStyleColor : _ol_render_canvas_.defaultStrokeStyle) }; } - var textFont = textStyle.getFont(); - var textOffsetX = textStyle.getOffsetX(); - var textOffsetY = textStyle.getOffsetY(); - var textRotateWithView = textStyle.getRotateWithView(); - var textRotation = textStyle.getRotation(); - var textScale = textStyle.getScale(); - var textText = textStyle.getText(); - var textTextAlign = textStyle.getTextAlign(); - var textTextBaseline = textStyle.getTextBaseline(); + const textFont = textStyle.getFont(); + const textOffsetX = textStyle.getOffsetX(); + const textOffsetY = textStyle.getOffsetY(); + const textRotateWithView = textStyle.getRotateWithView(); + const textRotation = textStyle.getRotation(); + const textScale = textStyle.getScale(); + const textText = textStyle.getText(); + const textTextAlign = textStyle.getTextAlign(); + const textTextBaseline = textStyle.getTextBaseline(); this.textState_ = { font: textFont !== undefined ? textFont : _ol_render_canvas_.defaultFont, diff --git a/src/ol/render/canvas/LineStringReplay.js b/src/ol/render/canvas/LineStringReplay.js index 372965f5e6..df64e66931 100644 --- a/src/ol/render/canvas/LineStringReplay.js +++ b/src/ol/render/canvas/LineStringReplay.js @@ -16,10 +16,10 @@ import _ol_render_canvas_Replay_ from '../canvas/Replay.js'; * @param {?} declutterTree Declutter tree. * @struct */ -var _ol_render_canvas_LineStringReplay_ = function( - tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree) { +const _ol_render_canvas_LineStringReplay_ = function( + tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree) { _ol_render_canvas_Replay_.call(this, - tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree); + tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree); }; inherits(_ol_render_canvas_LineStringReplay_, _ol_render_canvas_Replay_); @@ -34,10 +34,10 @@ inherits(_ol_render_canvas_LineStringReplay_, _ol_render_canvas_Replay_); * @return {number} end. */ _ol_render_canvas_LineStringReplay_.prototype.drawFlatCoordinates_ = function(flatCoordinates, offset, end, stride) { - var myBegin = this.coordinates.length; - var myEnd = this.appendFlatCoordinates( - flatCoordinates, offset, end, stride, false, false); - var moveToLineToInstruction = + const myBegin = this.coordinates.length; + const myEnd = this.appendFlatCoordinates( + flatCoordinates, offset, end, stride, false, false); + const moveToLineToInstruction = [_ol_render_canvas_Instruction_.MOVE_TO_LINE_TO, myBegin, myEnd]; this.instructions.push(moveToLineToInstruction); this.hitDetectionInstructions.push(moveToLineToInstruction); @@ -49,9 +49,9 @@ _ol_render_canvas_LineStringReplay_.prototype.drawFlatCoordinates_ = function(fl * @inheritDoc */ _ol_render_canvas_LineStringReplay_.prototype.drawLineString = function(lineStringGeometry, feature) { - var state = this.state; - var strokeStyle = state.strokeStyle; - var lineWidth = state.lineWidth; + const state = this.state; + const strokeStyle = state.strokeStyle; + const lineWidth = state.lineWidth; if (strokeStyle === undefined || lineWidth === undefined) { return; } @@ -64,8 +64,8 @@ _ol_render_canvas_LineStringReplay_.prototype.drawLineString = function(lineStri ], [ _ol_render_canvas_Instruction_.BEGIN_PATH ]); - var flatCoordinates = lineStringGeometry.getFlatCoordinates(); - var stride = lineStringGeometry.getStride(); + const flatCoordinates = lineStringGeometry.getFlatCoordinates(); + const stride = lineStringGeometry.getStride(); this.drawFlatCoordinates_(flatCoordinates, 0, flatCoordinates.length, stride); this.hitDetectionInstructions.push([_ol_render_canvas_Instruction_.STROKE]); this.endGeometry(lineStringGeometry, feature); @@ -76,9 +76,9 @@ _ol_render_canvas_LineStringReplay_.prototype.drawLineString = function(lineStri * @inheritDoc */ _ol_render_canvas_LineStringReplay_.prototype.drawMultiLineString = function(multiLineStringGeometry, feature) { - var state = this.state; - var strokeStyle = state.strokeStyle; - var lineWidth = state.lineWidth; + const state = this.state; + const strokeStyle = state.strokeStyle; + const lineWidth = state.lineWidth; if (strokeStyle === undefined || lineWidth === undefined) { return; } @@ -91,14 +91,14 @@ _ol_render_canvas_LineStringReplay_.prototype.drawMultiLineString = function(mul ], [ _ol_render_canvas_Instruction_.BEGIN_PATH ]); - var ends = multiLineStringGeometry.getEnds(); - var flatCoordinates = multiLineStringGeometry.getFlatCoordinates(); - var stride = multiLineStringGeometry.getStride(); - var offset = 0; - var i, ii; + const ends = multiLineStringGeometry.getEnds(); + const flatCoordinates = multiLineStringGeometry.getFlatCoordinates(); + const stride = multiLineStringGeometry.getStride(); + let offset = 0; + let i, ii; for (i = 0, ii = ends.length; i < ii; ++i) { offset = this.drawFlatCoordinates_( - flatCoordinates, offset, ends[i], stride); + flatCoordinates, offset, ends[i], stride); } this.hitDetectionInstructions.push([_ol_render_canvas_Instruction_.STROKE]); this.endGeometry(multiLineStringGeometry, feature); @@ -109,7 +109,7 @@ _ol_render_canvas_LineStringReplay_.prototype.drawMultiLineString = function(mul * @inheritDoc */ _ol_render_canvas_LineStringReplay_.prototype.finish = function() { - var state = this.state; + const state = this.state; if (state.lastStroke != undefined && state.lastStroke != this.coordinates.length) { this.instructions.push([_ol_render_canvas_Instruction_.STROKE]); } diff --git a/src/ol/render/canvas/PolygonReplay.js b/src/ol/render/canvas/PolygonReplay.js index a1ee906790..501a7863a3 100644 --- a/src/ol/render/canvas/PolygonReplay.js +++ b/src/ol/render/canvas/PolygonReplay.js @@ -19,10 +19,10 @@ import _ol_render_canvas_Replay_ from '../canvas/Replay.js'; * @param {?} declutterTree Declutter tree. * @struct */ -var _ol_render_canvas_PolygonReplay_ = function( - tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree) { +const _ol_render_canvas_PolygonReplay_ = function( + tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree) { _ol_render_canvas_Replay_.call(this, - tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree); + tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree); }; inherits(_ol_render_canvas_PolygonReplay_, _ol_render_canvas_Replay_); @@ -37,38 +37,38 @@ inherits(_ol_render_canvas_PolygonReplay_, _ol_render_canvas_Replay_); * @return {number} End. */ _ol_render_canvas_PolygonReplay_.prototype.drawFlatCoordinatess_ = function(flatCoordinates, offset, ends, stride) { - var state = this.state; - var fill = state.fillStyle !== undefined; - var stroke = state.strokeStyle != undefined; - var numEnds = ends.length; - var beginPathInstruction = [_ol_render_canvas_Instruction_.BEGIN_PATH]; + const state = this.state; + const fill = state.fillStyle !== undefined; + const stroke = state.strokeStyle != undefined; + const numEnds = ends.length; + const beginPathInstruction = [_ol_render_canvas_Instruction_.BEGIN_PATH]; this.instructions.push(beginPathInstruction); this.hitDetectionInstructions.push(beginPathInstruction); - for (var i = 0; i < numEnds; ++i) { - var end = ends[i]; - var myBegin = this.coordinates.length; - var myEnd = this.appendFlatCoordinates( - flatCoordinates, offset, end, stride, true, !stroke); - var moveToLineToInstruction = + for (let i = 0; i < numEnds; ++i) { + const end = ends[i]; + const myBegin = this.coordinates.length; + const myEnd = this.appendFlatCoordinates( + flatCoordinates, offset, end, stride, true, !stroke); + const moveToLineToInstruction = [_ol_render_canvas_Instruction_.MOVE_TO_LINE_TO, myBegin, myEnd]; this.instructions.push(moveToLineToInstruction); this.hitDetectionInstructions.push(moveToLineToInstruction); if (stroke) { // Performance optimization: only call closePath() when we have a stroke. // Otherwise the ring is closed already (see appendFlatCoordinates above). - var closePathInstruction = [_ol_render_canvas_Instruction_.CLOSE_PATH]; + const closePathInstruction = [_ol_render_canvas_Instruction_.CLOSE_PATH]; this.instructions.push(closePathInstruction); this.hitDetectionInstructions.push(closePathInstruction); } offset = end; } - var fillInstruction = [_ol_render_canvas_Instruction_.FILL]; + const fillInstruction = [_ol_render_canvas_Instruction_.FILL]; this.hitDetectionInstructions.push(fillInstruction); if (fill) { this.instructions.push(fillInstruction); } if (stroke) { - var strokeInstruction = [_ol_render_canvas_Instruction_.STROKE]; + const strokeInstruction = [_ol_render_canvas_Instruction_.STROKE]; this.instructions.push(strokeInstruction); this.hitDetectionInstructions.push(strokeInstruction); } @@ -80,9 +80,9 @@ _ol_render_canvas_PolygonReplay_.prototype.drawFlatCoordinatess_ = function(flat * @inheritDoc */ _ol_render_canvas_PolygonReplay_.prototype.drawCircle = function(circleGeometry, feature) { - var state = this.state; - var fillStyle = state.fillStyle; - var strokeStyle = state.strokeStyle; + const state = this.state; + const fillStyle = state.fillStyle; + const strokeStyle = state.strokeStyle; if (fillStyle === undefined && strokeStyle === undefined) { return; } @@ -100,22 +100,22 @@ _ol_render_canvas_PolygonReplay_.prototype.drawCircle = function(circleGeometry, state.miterLimit, state.lineDash, state.lineDashOffset ]); } - var flatCoordinates = circleGeometry.getFlatCoordinates(); - var stride = circleGeometry.getStride(); - var myBegin = this.coordinates.length; + const flatCoordinates = circleGeometry.getFlatCoordinates(); + const stride = circleGeometry.getStride(); + const myBegin = this.coordinates.length; this.appendFlatCoordinates( - flatCoordinates, 0, flatCoordinates.length, stride, false, false); - var beginPathInstruction = [_ol_render_canvas_Instruction_.BEGIN_PATH]; - var circleInstruction = [_ol_render_canvas_Instruction_.CIRCLE, myBegin]; + flatCoordinates, 0, flatCoordinates.length, stride, false, false); + const beginPathInstruction = [_ol_render_canvas_Instruction_.BEGIN_PATH]; + const circleInstruction = [_ol_render_canvas_Instruction_.CIRCLE, myBegin]; this.instructions.push(beginPathInstruction, circleInstruction); this.hitDetectionInstructions.push(beginPathInstruction, circleInstruction); - var fillInstruction = [_ol_render_canvas_Instruction_.FILL]; + const fillInstruction = [_ol_render_canvas_Instruction_.FILL]; this.hitDetectionInstructions.push(fillInstruction); if (state.fillStyle !== undefined) { this.instructions.push(fillInstruction); } if (state.strokeStyle !== undefined) { - var strokeInstruction = [_ol_render_canvas_Instruction_.STROKE]; + const strokeInstruction = [_ol_render_canvas_Instruction_.STROKE]; this.instructions.push(strokeInstruction); this.hitDetectionInstructions.push(strokeInstruction); } @@ -127,7 +127,7 @@ _ol_render_canvas_PolygonReplay_.prototype.drawCircle = function(circleGeometry, * @inheritDoc */ _ol_render_canvas_PolygonReplay_.prototype.drawPolygon = function(polygonGeometry, feature) { - var state = this.state; + const state = this.state; this.setFillStrokeStyles_(polygonGeometry); this.beginGeometry(polygonGeometry, feature); // always fill the polygon for hit detection @@ -142,9 +142,9 @@ _ol_render_canvas_PolygonReplay_.prototype.drawPolygon = function(polygonGeometr state.miterLimit, state.lineDash, state.lineDashOffset ]); } - var ends = polygonGeometry.getEnds(); - var flatCoordinates = polygonGeometry.getOrientedFlatCoordinates(); - var stride = polygonGeometry.getStride(); + const ends = polygonGeometry.getEnds(); + const flatCoordinates = polygonGeometry.getOrientedFlatCoordinates(); + const stride = polygonGeometry.getStride(); this.drawFlatCoordinatess_(flatCoordinates, 0, ends, stride); this.endGeometry(polygonGeometry, feature); }; @@ -154,9 +154,9 @@ _ol_render_canvas_PolygonReplay_.prototype.drawPolygon = function(polygonGeometr * @inheritDoc */ _ol_render_canvas_PolygonReplay_.prototype.drawMultiPolygon = function(multiPolygonGeometry, feature) { - var state = this.state; - var fillStyle = state.fillStyle; - var strokeStyle = state.strokeStyle; + const state = this.state; + const fillStyle = state.fillStyle; + const strokeStyle = state.strokeStyle; if (fillStyle === undefined && strokeStyle === undefined) { return; } @@ -174,14 +174,14 @@ _ol_render_canvas_PolygonReplay_.prototype.drawMultiPolygon = function(multiPoly state.miterLimit, state.lineDash, state.lineDashOffset ]); } - var endss = multiPolygonGeometry.getEndss(); - var flatCoordinates = multiPolygonGeometry.getOrientedFlatCoordinates(); - var stride = multiPolygonGeometry.getStride(); - var offset = 0; - var i, ii; + const endss = multiPolygonGeometry.getEndss(); + const flatCoordinates = multiPolygonGeometry.getOrientedFlatCoordinates(); + const stride = multiPolygonGeometry.getStride(); + let offset = 0; + let i, ii; for (i = 0, ii = endss.length; i < ii; ++i) { offset = this.drawFlatCoordinatess_( - flatCoordinates, offset, endss[i], stride); + flatCoordinates, offset, endss[i], stride); } this.endGeometry(multiPolygonGeometry, feature); }; @@ -197,10 +197,10 @@ _ol_render_canvas_PolygonReplay_.prototype.finish = function() { // simplified using quantization and point elimination. However, we might // have received a mix of quantized and non-quantized geometries, so ensure // that all are quantized by quantizing all coordinates in the batch. - var tolerance = this.tolerance; + const tolerance = this.tolerance; if (tolerance !== 0) { - var coordinates = this.coordinates; - var i, ii; + const coordinates = this.coordinates; + let i, ii; for (i = 0, ii = coordinates.length; i < ii; ++i) { coordinates[i] = _ol_geom_flat_simplify_.snap(coordinates[i], tolerance); } @@ -213,8 +213,8 @@ _ol_render_canvas_PolygonReplay_.prototype.finish = function() { * @param {ol.geom.Geometry|ol.render.Feature} geometry Geometry. */ _ol_render_canvas_PolygonReplay_.prototype.setFillStrokeStyles_ = function(geometry) { - var state = this.state; - var fillStyle = state.fillStyle; + const state = this.state; + const fillStyle = state.fillStyle; if (fillStyle !== undefined) { this.updateFillStyle(state, this.createFill, geometry); } diff --git a/src/ol/render/canvas/Replay.js b/src/ol/render/canvas/Replay.js index c26cb50a9e..f2f61d361f 100644 --- a/src/ol/render/canvas/Replay.js +++ b/src/ol/render/canvas/Replay.js @@ -31,7 +31,7 @@ import _ol_transform_ from '../../transform.js'; * @param {?} declutterTree Declutter tree. * @struct */ -var _ol_render_canvas_Replay_ = function(tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree) { +const _ol_render_canvas_Replay_ = function(tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree) { VectorContext.call(this); /** @@ -181,7 +181,7 @@ inherits(_ol_render_canvas_Replay_, VectorContext); * @param {Array.<*>} strokeInstruction Stroke instruction. */ _ol_render_canvas_Replay_.prototype.replayTextBackground_ = function(context, p1, p2, p3, p4, - fillInstruction, strokeInstruction) { + fillInstruction, strokeInstruction) { context.beginPath(); context.moveTo.apply(context, p1); context.lineTo.apply(context, p2); @@ -220,31 +220,31 @@ _ol_render_canvas_Replay_.prototype.replayTextBackground_ = function(context, p1 * @param {Array.<*>} strokeInstruction Stroke instruction. */ _ol_render_canvas_Replay_.prototype.replayImage_ = function(context, x, y, image, - anchorX, anchorY, declutterGroup, height, opacity, originX, originY, - rotation, scale, snapToPixel, width, padding, fillInstruction, strokeInstruction) { - var fillStroke = fillInstruction || strokeInstruction; - var localTransform = this.tmpLocalTransform_; + anchorX, anchorY, declutterGroup, height, opacity, originX, originY, + rotation, scale, snapToPixel, width, padding, fillInstruction, strokeInstruction) { + const fillStroke = fillInstruction || strokeInstruction; + const localTransform = this.tmpLocalTransform_; anchorX *= scale; anchorY *= scale; x -= anchorX; y -= anchorY; - var w = (width + originX > image.width) ? image.width - originX : width; - var h = (height + originY > image.height) ? image.height - originY : height; - var box = this.tmpExtent_; - var boxW = padding[3] + w * scale + padding[1]; - var boxH = padding[0] + h * scale + padding[2]; - var boxX = x - padding[3]; - var boxY = y - padding[0]; + const w = (width + originX > image.width) ? image.width - originX : width; + const h = (height + originY > image.height) ? image.height - originY : height; + const box = this.tmpExtent_; + const boxW = padding[3] + w * scale + padding[1]; + const boxH = padding[0] + h * scale + padding[2]; + const boxX = x - padding[3]; + const boxY = y - padding[0]; /** @type {ol.Coordinate} */ - var p1; + let p1; /** @type {ol.Coordinate} */ - var p2; + let p2; /** @type {ol.Coordinate} */ - var p3; + let p3; /** @type {ol.Coordinate} */ - var p4; + let p4; if (fillStroke || rotation !== 0) { p1 = [boxX, boxY]; p2 = [boxX + boxW, boxY]; @@ -252,12 +252,12 @@ _ol_render_canvas_Replay_.prototype.replayImage_ = function(context, x, y, image p4 = [boxX, boxY + boxH]; } - var transform = null; + let transform = null; if (rotation !== 0) { - var centerX = x + anchorX; - var centerY = y + anchorY; + const centerX = x + anchorX; + const centerY = y + anchorY; transform = _ol_transform_.compose(localTransform, - centerX, centerY, 1, 1, rotation, -centerX, -centerY); + centerX, centerY, 1, 1, rotation, -centerX, -centerY); createOrUpdateEmpty(box); extendCoordinate(box, _ol_transform_.apply(localTransform, p1)); @@ -267,9 +267,9 @@ _ol_render_canvas_Replay_.prototype.replayImage_ = function(context, x, y, image } else { createOrUpdate(boxX, boxY, boxX + boxW, boxY + boxH, box); } - var canvas = context.canvas; - var strokePadding = strokeInstruction ? (strokeInstruction[2] * scale / 2) : 0; - var intersects = + const canvas = context.canvas; + const strokePadding = strokeInstruction ? (strokeInstruction[2] * scale / 2) : 0; + const intersects = box[0] - strokePadding <= canvas.width && box[2] + strokePadding >= 0 && box[1] - strokePadding <= canvas.height && box[3] + strokePadding >= 0; @@ -283,7 +283,7 @@ _ol_render_canvas_Replay_.prototype.replayImage_ = function(context, x, y, image return; } extend(declutterGroup, box); - var declutterArgs = intersects ? + const declutterArgs = intersects ? [context, transform ? transform.slice(0) : null, opacity, image, originX, originY, w, h, x, y, scale] : null; if (declutterArgs && fillStroke) { @@ -293,8 +293,8 @@ _ol_render_canvas_Replay_.prototype.replayImage_ = function(context, x, y, image } else if (intersects) { if (fillStroke) { this.replayTextBackground_(context, p1, p2, p3, p4, - /** @type {Array.<*>} */ (fillInstruction), - /** @type {Array.<*>} */ (strokeInstruction)); + /** @type {Array.<*>} */ (fillInstruction), + /** @type {Array.<*>} */ (strokeInstruction)); } _ol_render_canvas_.drawImage(context, transform, opacity, image, originX, originY, w, h, x, y, scale); } @@ -307,7 +307,7 @@ _ol_render_canvas_Replay_.prototype.replayImage_ = function(context, x, y, image * @return {Array.} Dash array with pixel ratio applied */ _ol_render_canvas_Replay_.prototype.applyPixelRatio = function(dashArray) { - var pixelRatio = this.pixelRatio; + const pixelRatio = this.pixelRatio; return pixelRatio == 1 ? dashArray : dashArray.map(function(dash) { return dash * pixelRatio; }); @@ -326,16 +326,16 @@ _ol_render_canvas_Replay_.prototype.applyPixelRatio = function(dashArray) { */ _ol_render_canvas_Replay_.prototype.appendFlatCoordinates = function(flatCoordinates, offset, end, stride, closed, skipFirst) { - var myEnd = this.coordinates.length; - var extent = this.getBufferedMaxExtent(); + let myEnd = this.coordinates.length; + const extent = this.getBufferedMaxExtent(); if (skipFirst) { offset += stride; } - var lastCoord = [flatCoordinates[offset], flatCoordinates[offset + 1]]; - var nextCoord = [NaN, NaN]; - var skipped = true; + const lastCoord = [flatCoordinates[offset], flatCoordinates[offset + 1]]; + const nextCoord = [NaN, NaN]; + let skipped = true; - var i, lastRel, nextRel; + let i, lastRel, nextRel; for (i = offset + stride; i < end; i += stride) { nextCoord[0] = flatCoordinates[i]; nextCoord[1] = flatCoordinates[i + 1]; @@ -378,9 +378,9 @@ _ol_render_canvas_Replay_.prototype.appendFlatCoordinates = function(flatCoordin * @return {number} Offset. */ _ol_render_canvas_Replay_.prototype.drawCustomCoordinates_ = function(flatCoordinates, offset, ends, stride, replayEnds) { - for (var i = 0, ii = ends.length; i < ii; ++i) { - var end = ends[i]; - var replayEnd = this.appendFlatCoordinates(flatCoordinates, offset, end, stride, false, false); + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const replayEnd = this.appendFlatCoordinates(flatCoordinates, offset, end, stride, false, false); replayEnds.push(replayEnd); offset = end; } @@ -393,19 +393,19 @@ _ol_render_canvas_Replay_.prototype.drawCustomCoordinates_ = function(flatCoordi */ _ol_render_canvas_Replay_.prototype.drawCustom = function(geometry, feature, renderer) { this.beginGeometry(geometry, feature); - var type = geometry.getType(); - var stride = geometry.getStride(); - var replayBegin = this.coordinates.length; - var flatCoordinates, replayEnd, replayEnds, replayEndss; - var offset; + const type = geometry.getType(); + const stride = geometry.getStride(); + const replayBegin = this.coordinates.length; + let flatCoordinates, replayEnd, replayEnds, replayEndss; + let offset; if (type == GeometryType.MULTI_POLYGON) { geometry = /** @type {ol.geom.MultiPolygon} */ (geometry); flatCoordinates = geometry.getOrientedFlatCoordinates(); replayEndss = []; - var endss = geometry.getEndss(); + const endss = geometry.getEndss(); offset = 0; - for (var i = 0, ii = endss.length; i < ii; ++i) { - var myEnds = []; + for (let i = 0, ii = endss.length; i < ii; ++i) { + const myEnds = []; offset = this.drawCustomCoordinates_(flatCoordinates, offset, endss[i], stride, myEnds); replayEndss.push(myEnds); } @@ -417,14 +417,14 @@ _ol_render_canvas_Replay_.prototype.drawCustom = function(geometry, feature, ren /** @type {ol.geom.Polygon} */ (geometry).getOrientedFlatCoordinates() : geometry.getFlatCoordinates(); offset = this.drawCustomCoordinates_(flatCoordinates, 0, - /** @type {ol.geom.Polygon|ol.geom.MultiLineString} */ (geometry).getEnds(), - stride, replayEnds); + /** @type {ol.geom.Polygon|ol.geom.MultiLineString} */ (geometry).getEnds(), + stride, replayEnds); this.instructions.push([_ol_render_canvas_Instruction_.CUSTOM, replayBegin, replayEnds, geometry, renderer, _ol_geom_flat_inflate_.coordinatess]); } else if (type == GeometryType.LINE_STRING || type == GeometryType.MULTI_POINT) { flatCoordinates = geometry.getFlatCoordinates(); replayEnd = this.appendFlatCoordinates( - flatCoordinates, 0, flatCoordinates.length, stride, false, false); + flatCoordinates, 0, flatCoordinates.length, stride, false, false); this.instructions.push([_ol_render_canvas_Instruction_.CUSTOM, replayBegin, replayEnd, geometry, renderer, _ol_geom_flat_inflate_.coordinates]); } else if (type == GeometryType.POINT) { @@ -459,7 +459,7 @@ _ol_render_canvas_Replay_.prototype.beginGeometry = function(geometry, feature) */ _ol_render_canvas_Replay_.prototype.fill_ = function(context) { if (this.fillOrigin_) { - var origin = _ol_transform_.apply(this.renderedTransform_, this.fillOrigin_.slice()); + const origin = _ol_transform_.apply(this.renderedTransform_, this.fillOrigin_.slice()); context.translate(origin[0], origin[1]); context.rotate(this.viewRotation_); } @@ -494,10 +494,10 @@ _ol_render_canvas_Replay_.prototype.setStrokeStyle_ = function(context, instruct */ _ol_render_canvas_Replay_.prototype.renderDeclutter_ = function(declutterGroup, feature) { if (declutterGroup && declutterGroup.length > 5) { - var groupCount = declutterGroup[4]; + const groupCount = declutterGroup[4]; if (groupCount == 1 || groupCount == declutterGroup.length - 5) { /** @type {ol.RBushEntry} */ - var box = { + const box = { minX: /** @type {number} */ (declutterGroup[0]), minY: /** @type {number} */ (declutterGroup[1]), maxX: /** @type {number} */ (declutterGroup[2]), @@ -506,14 +506,14 @@ _ol_render_canvas_Replay_.prototype.renderDeclutter_ = function(declutterGroup, }; if (!this.declutterTree.collides(box)) { this.declutterTree.insert(box); - var drawImage = _ol_render_canvas_.drawImage; - for (var j = 5, jj = declutterGroup.length; j < jj; ++j) { - var declutterData = /** @type {Array} */ (declutterGroup[j]); + const drawImage = _ol_render_canvas_.drawImage; + for (let j = 5, jj = declutterGroup.length; j < jj; ++j) { + const declutterData = /** @type {Array} */ (declutterGroup[j]); if (declutterData) { if (declutterData.length > 11) { this.replayTextBackground_(declutterData[0], - declutterData[13], declutterData[14], declutterData[15], declutterData[16], - declutterData[11], declutterData[12]); + declutterData[13], declutterData[14], declutterData[15], declutterData[16], + declutterData[11], declutterData[12]); } drawImage.apply(undefined, declutterData); } @@ -541,10 +541,10 @@ _ol_render_canvas_Replay_.prototype.renderDeclutter_ = function(declutterGroup, * @template T */ _ol_render_canvas_Replay_.prototype.replay_ = function( - context, transform, skippedFeaturesHash, - instructions, featureCallback, opt_hitExtent) { + context, transform, skippedFeaturesHash, + instructions, featureCallback, opt_hitExtent) { /** @type {Array.} */ - var pixelCoordinates; + let pixelCoordinates; if (this.pixelCoordinates_ && equals(transform, this.renderedTransform_)) { pixelCoordinates = this.pixelCoordinates_; } else { @@ -552,24 +552,24 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( this.pixelCoordinates_ = []; } pixelCoordinates = _ol_geom_flat_transform_.transform2D( - this.coordinates, 0, this.coordinates.length, 2, - transform, this.pixelCoordinates_); + this.coordinates, 0, this.coordinates.length, 2, + transform, this.pixelCoordinates_); _ol_transform_.setFromArray(this.renderedTransform_, transform); } - var skipFeatures = !_ol_obj_.isEmpty(skippedFeaturesHash); - var i = 0; // instruction index - var ii = instructions.length; // end of instructions - var d = 0; // data index - var dd; // end of per-instruction data - var anchorX, anchorY, prevX, prevY, roundX, roundY, declutterGroup, image; - var pendingFill = 0; - var pendingStroke = 0; - var lastFillInstruction = null; - var lastStrokeInstruction = null; - var coordinateCache = this.coordinateCache_; - var viewRotation = this.viewRotation_; + const skipFeatures = !_ol_obj_.isEmpty(skippedFeaturesHash); + let i = 0; // instruction index + const ii = instructions.length; // end of instructions + let d = 0; // data index + let dd; // end of per-instruction data + let anchorX, anchorY, prevX, prevY, roundX, roundY, declutterGroup, image; + let pendingFill = 0; + let pendingStroke = 0; + let lastFillInstruction = null; + let lastStrokeInstruction = null; + const coordinateCache = this.coordinateCache_; + const viewRotation = this.viewRotation_; - var state = /** @type {olx.render.State} */ ({ + const state = /** @type {olx.render.State} */ ({ context: context, pixelRatio: this.pixelRatio, resolution: this.resolution, @@ -578,12 +578,12 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( // When the batch size gets too big, performance decreases. 200 is a good // balance between batch size and number of fill/stroke instructions. - var batchSize = + const batchSize = this.instructions != instructions || this.overlaps ? 0 : 200; while (i < ii) { - var instruction = instructions[i]; - var type = /** @type {ol.render.canvas.Instruction} */ (instruction[0]); - var /** @type {ol.Feature|ol.render.Feature} */ feature, x, y; + const instruction = instructions[i]; + const type = /** @type {ol.render.canvas.Instruction} */ (instruction[0]); + let /** @type {ol.Feature|ol.render.Feature} */ feature, x, y; switch (type) { case _ol_render_canvas_Instruction_.BEGIN_GEOMETRY: feature = /** @type {ol.Feature|ol.render.Feature} */ (instruction[1]); @@ -592,7 +592,7 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( !feature.getGeometry()) { i = /** @type {number} */ (instruction[2]); } else if (opt_hitExtent !== undefined && !intersects( - opt_hitExtent, feature.getGeometry().getExtent())) { + opt_hitExtent, feature.getGeometry().getExtent())) { i = /** @type {number} */ (instruction[2]) + 1; } else { ++i; @@ -615,13 +615,13 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( break; case _ol_render_canvas_Instruction_.CIRCLE: d = /** @type {number} */ (instruction[1]); - var x1 = pixelCoordinates[d]; - var y1 = pixelCoordinates[d + 1]; - var x2 = pixelCoordinates[d + 2]; - var y2 = pixelCoordinates[d + 3]; - var dx = x2 - x1; - var dy = y2 - y1; - var r = Math.sqrt(dx * dx + dy * dy); + const x1 = pixelCoordinates[d]; + const y1 = pixelCoordinates[d + 1]; + const x2 = pixelCoordinates[d + 2]; + const y2 = pixelCoordinates[d + 3]; + const dx = x2 - x1; + const dy = y2 - y1; + const r = Math.sqrt(dx * dx + dy * dy); context.moveTo(x1 + r, y1); context.arc(x1, y1, r, 0, 2 * Math.PI, true); ++i; @@ -633,15 +633,15 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( case _ol_render_canvas_Instruction_.CUSTOM: d = /** @type {number} */ (instruction[1]); dd = instruction[2]; - var geometry = /** @type {ol.geom.SimpleGeometry} */ (instruction[3]); - var renderer = instruction[4]; - var fn = instruction.length == 6 ? instruction[5] : undefined; + const geometry = /** @type {ol.geom.SimpleGeometry} */ (instruction[3]); + const renderer = instruction[4]; + const fn = instruction.length == 6 ? instruction[5] : undefined; state.geometry = geometry; state.feature = feature; if (!(i in coordinateCache)) { coordinateCache[i] = []; } - var coords = coordinateCache[i]; + const coords = coordinateCache[i]; if (fn) { fn(pixelCoordinates, d, dd, 2, coords); } else { @@ -661,17 +661,17 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( anchorX = /** @type {number} */ (instruction[4]); anchorY = /** @type {number} */ (instruction[5]); declutterGroup = featureCallback ? null : /** @type {ol.DeclutterGroup} */ (instruction[6]); - var height = /** @type {number} */ (instruction[7]); - var opacity = /** @type {number} */ (instruction[8]); - var originX = /** @type {number} */ (instruction[9]); - var originY = /** @type {number} */ (instruction[10]); - var rotateWithView = /** @type {boolean} */ (instruction[11]); - var rotation = /** @type {number} */ (instruction[12]); - var scale = /** @type {number} */ (instruction[13]); - var snapToPixel = /** @type {boolean} */ (instruction[14]); - var width = /** @type {number} */ (instruction[15]); + const height = /** @type {number} */ (instruction[7]); + const opacity = /** @type {number} */ (instruction[8]); + const originX = /** @type {number} */ (instruction[9]); + const originY = /** @type {number} */ (instruction[10]); + const rotateWithView = /** @type {boolean} */ (instruction[11]); + let rotation = /** @type {number} */ (instruction[12]); + const scale = /** @type {number} */ (instruction[13]); + const snapToPixel = /** @type {boolean} */ (instruction[14]); + const width = /** @type {number} */ (instruction[15]); - var padding, backgroundFill, backgroundStroke; + let padding, backgroundFill, backgroundStroke; if (instruction.length > 16) { padding = /** @type {Array.} */ (instruction[16]); backgroundFill = /** @type {boolean} */ (instruction[17]); @@ -686,40 +686,40 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( } for (; d < dd; d += 2) { this.replayImage_(context, - pixelCoordinates[d], pixelCoordinates[d + 1], image, anchorX, anchorY, - declutterGroup, height, opacity, originX, originY, rotation, scale, - snapToPixel, width, padding, - backgroundFill ? /** @type {Array.<*>} */ (lastFillInstruction) : null, - backgroundStroke ? /** @type {Array.<*>} */ (lastStrokeInstruction) : null); + pixelCoordinates[d], pixelCoordinates[d + 1], image, anchorX, anchorY, + declutterGroup, height, opacity, originX, originY, rotation, scale, + snapToPixel, width, padding, + backgroundFill ? /** @type {Array.<*>} */ (lastFillInstruction) : null, + backgroundStroke ? /** @type {Array.<*>} */ (lastStrokeInstruction) : null); } this.renderDeclutter_(declutterGroup, feature); ++i; break; case _ol_render_canvas_Instruction_.DRAW_CHARS: - var begin = /** @type {number} */ (instruction[1]); - var end = /** @type {number} */ (instruction[2]); - var baseline = /** @type {number} */ (instruction[3]); + const begin = /** @type {number} */ (instruction[1]); + const end = /** @type {number} */ (instruction[2]); + const baseline = /** @type {number} */ (instruction[3]); declutterGroup = featureCallback ? null : /** @type {ol.DeclutterGroup} */ (instruction[4]); - var overflow = /** @type {number} */ (instruction[5]); - var fillKey = /** @type {string} */ (instruction[6]); - var maxAngle = /** @type {number} */ (instruction[7]); - var measure = /** @type {function(string):number} */ (instruction[8]); - var offsetY = /** @type {number} */ (instruction[9]); - var strokeKey = /** @type {string} */ (instruction[10]); - var strokeWidth = /** @type {number} */ (instruction[11]); - var text = /** @type {string} */ (instruction[12]); - var textKey = /** @type {string} */ (instruction[13]); - var textScale = /** @type {number} */ (instruction[14]); + const overflow = /** @type {number} */ (instruction[5]); + const fillKey = /** @type {string} */ (instruction[6]); + const maxAngle = /** @type {number} */ (instruction[7]); + const measure = /** @type {function(string):number} */ (instruction[8]); + const offsetY = /** @type {number} */ (instruction[9]); + const strokeKey = /** @type {string} */ (instruction[10]); + const strokeWidth = /** @type {number} */ (instruction[11]); + const text = /** @type {string} */ (instruction[12]); + const textKey = /** @type {string} */ (instruction[13]); + const textScale = /** @type {number} */ (instruction[14]); - var pathLength = _ol_geom_flat_length_.lineString(pixelCoordinates, begin, end, 2); - var textLength = measure(text); + const pathLength = _ol_geom_flat_length_.lineString(pixelCoordinates, begin, end, 2); + const textLength = measure(text); if (overflow || textLength <= pathLength) { - var textAlign = /** @type {ol.render.canvas.TextReplay} */ (this).textStates[textKey].textAlign; - var startM = (pathLength - textLength) * _ol_render_replay_.TEXT_ALIGN[textAlign]; - var parts = _ol_geom_flat_textpath_.lineString( - pixelCoordinates, begin, end, 2, text, measure, startM, maxAngle); + const textAlign = /** @type {ol.render.canvas.TextReplay} */ (this).textStates[textKey].textAlign; + const startM = (pathLength - textLength) * _ol_render_replay_.TEXT_ALIGN[textAlign]; + const parts = _ol_geom_flat_textpath_.lineString( + pixelCoordinates, begin, end, 2, text, measure, startM, maxAngle); if (parts) { - var c, cc, chars, label, part; + let c, cc, chars, label, part; if (strokeKey) { for (c = 0, cc = parts.length; c < cc; ++c) { part = parts[c]; // x, y, anchorX, rotation, chunk @@ -728,10 +728,10 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( anchorX = /** @type {number} */ (part[2]) + strokeWidth; anchorY = baseline * label.height + (0.5 - baseline) * 2 * strokeWidth - offsetY; this.replayImage_(context, - /** @type {number} */ (part[0]), /** @type {number} */ (part[1]), label, - anchorX, anchorY, declutterGroup, label.height, 1, 0, 0, - /** @type {number} */ (part[3]), textScale, false, label.width, - _ol_render_canvas_.defaultPadding, null, null); + /** @type {number} */ (part[0]), /** @type {number} */ (part[1]), label, + anchorX, anchorY, declutterGroup, label.height, 1, 0, 0, + /** @type {number} */ (part[3]), textScale, false, label.width, + _ol_render_canvas_.defaultPadding, null, null); } } if (fillKey) { @@ -742,10 +742,10 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( anchorX = /** @type {number} */ (part[2]); anchorY = baseline * label.height - offsetY; this.replayImage_(context, - /** @type {number} */ (part[0]), /** @type {number} */ (part[1]), label, - anchorX, anchorY, declutterGroup, label.height, 1, 0, 0, - /** @type {number} */ (part[3]), textScale, false, label.width, - _ol_render_canvas_.defaultPadding, null, null); + /** @type {number} */ (part[0]), /** @type {number} */ (part[1]), label, + anchorX, anchorY, declutterGroup, label.height, 1, 0, 0, + /** @type {number} */ (part[3]), textScale, false, label.width, + _ol_render_canvas_.defaultPadding, null, null); } } } @@ -756,7 +756,7 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( case _ol_render_canvas_Instruction_.END_GEOMETRY: if (featureCallback !== undefined) { feature = /** @type {ol.Feature|ol.render.Feature} */ (instruction[1]); - var result = featureCallback(feature); + const result = featureCallback(feature); if (result) { return result; } @@ -852,10 +852,10 @@ _ol_render_canvas_Replay_.prototype.replay_ = function( * to skip. */ _ol_render_canvas_Replay_.prototype.replay = function( - context, transform, viewRotation, skippedFeaturesHash) { + context, transform, viewRotation, skippedFeaturesHash) { this.viewRotation_ = viewRotation; this.replay_(context, transform, - skippedFeaturesHash, this.instructions, undefined, undefined); + skippedFeaturesHash, this.instructions, undefined, undefined); }; @@ -873,11 +873,11 @@ _ol_render_canvas_Replay_.prototype.replay = function( * @template T */ _ol_render_canvas_Replay_.prototype.replayHitDetection = function( - context, transform, viewRotation, skippedFeaturesHash, - opt_featureCallback, opt_hitExtent) { + context, transform, viewRotation, skippedFeaturesHash, + opt_featureCallback, opt_hitExtent) { this.viewRotation_ = viewRotation; return this.replay_(context, transform, skippedFeaturesHash, - this.hitDetectionInstructions, opt_featureCallback, opt_hitExtent); + this.hitDetectionInstructions, opt_featureCallback, opt_hitExtent); }; @@ -885,15 +885,15 @@ _ol_render_canvas_Replay_.prototype.replayHitDetection = function( * Reverse the hit detection instructions. */ _ol_render_canvas_Replay_.prototype.reverseHitDetectionInstructions = function() { - var hitDetectionInstructions = this.hitDetectionInstructions; + const hitDetectionInstructions = this.hitDetectionInstructions; // step 1 - reverse array hitDetectionInstructions.reverse(); // step 2 - reverse instructions within geometry blocks - var i; - var n = hitDetectionInstructions.length; - var instruction; - var type; - var begin = -1; + let i; + const n = hitDetectionInstructions.length; + let instruction; + let type; + let begin = -1; for (i = 0; i < n; ++i) { instruction = hitDetectionInstructions[i]; type = /** @type {ol.render.canvas.Instruction} */ (instruction[0]); @@ -912,34 +912,34 @@ _ol_render_canvas_Replay_.prototype.reverseHitDetectionInstructions = function() * @inheritDoc */ _ol_render_canvas_Replay_.prototype.setFillStrokeStyle = function(fillStyle, strokeStyle) { - var state = this.state; + const state = this.state; if (fillStyle) { - var fillStyleColor = fillStyle.getColor(); + const fillStyleColor = fillStyle.getColor(); state.fillStyle = asColorLike(fillStyleColor ? fillStyleColor : _ol_render_canvas_.defaultFillStyle); } else { state.fillStyle = undefined; } if (strokeStyle) { - var strokeStyleColor = strokeStyle.getColor(); + const strokeStyleColor = strokeStyle.getColor(); state.strokeStyle = asColorLike(strokeStyleColor ? strokeStyleColor : _ol_render_canvas_.defaultStrokeStyle); - var strokeStyleLineCap = strokeStyle.getLineCap(); + const strokeStyleLineCap = strokeStyle.getLineCap(); state.lineCap = strokeStyleLineCap !== undefined ? strokeStyleLineCap : _ol_render_canvas_.defaultLineCap; - var strokeStyleLineDash = strokeStyle.getLineDash(); + const strokeStyleLineDash = strokeStyle.getLineDash(); state.lineDash = strokeStyleLineDash ? strokeStyleLineDash.slice() : _ol_render_canvas_.defaultLineDash; - var strokeStyleLineDashOffset = strokeStyle.getLineDashOffset(); + const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset(); state.lineDashOffset = strokeStyleLineDashOffset ? strokeStyleLineDashOffset : _ol_render_canvas_.defaultLineDashOffset; - var strokeStyleLineJoin = strokeStyle.getLineJoin(); + const strokeStyleLineJoin = strokeStyle.getLineJoin(); state.lineJoin = strokeStyleLineJoin !== undefined ? strokeStyleLineJoin : _ol_render_canvas_.defaultLineJoin; - var strokeStyleWidth = strokeStyle.getWidth(); + const strokeStyleWidth = strokeStyle.getWidth(); state.lineWidth = strokeStyleWidth !== undefined ? strokeStyleWidth : _ol_render_canvas_.defaultLineWidth; - var strokeStyleMiterLimit = strokeStyle.getMiterLimit(); + const strokeStyleMiterLimit = strokeStyle.getMiterLimit(); state.miterLimit = strokeStyleMiterLimit !== undefined ? strokeStyleMiterLimit : _ol_render_canvas_.defaultMiterLimit; @@ -966,10 +966,10 @@ _ol_render_canvas_Replay_.prototype.setFillStrokeStyle = function(fillStyle, str * @return {Array.<*>} Fill instruction. */ _ol_render_canvas_Replay_.prototype.createFill = function(state, geometry) { - var fillStyle = state.fillStyle; - var fillInstruction = [_ol_render_canvas_Instruction_.SET_FILL_STYLE, fillStyle]; + const fillStyle = state.fillStyle; + const fillInstruction = [_ol_render_canvas_Instruction_.SET_FILL_STYLE, fillStyle]; if (typeof fillStyle !== 'string') { - var fillExtent = geometry.getExtent(); + const fillExtent = geometry.getExtent(); fillInstruction.push([fillExtent[0], fillExtent[3]]); } return fillInstruction; @@ -1004,7 +1004,7 @@ _ol_render_canvas_Replay_.prototype.createStroke = function(state) { * @param {ol.geom.Geometry|ol.render.Feature} geometry Geometry. */ _ol_render_canvas_Replay_.prototype.updateFillStyle = function(state, createFill, geometry) { - var fillStyle = state.fillStyle; + const fillStyle = state.fillStyle; if (typeof fillStyle !== 'string' || state.currentFillStyle != fillStyle) { if (fillStyle !== undefined) { this.instructions.push(createFill.call(this, state, geometry)); @@ -1019,13 +1019,13 @@ _ol_render_canvas_Replay_.prototype.updateFillStyle = function(state, createFill * @param {function(this:ol.render.canvas.Replay, ol.CanvasFillStrokeState)} applyStroke Apply stroke. */ _ol_render_canvas_Replay_.prototype.updateStrokeStyle = function(state, applyStroke) { - var strokeStyle = state.strokeStyle; - var lineCap = state.lineCap; - var lineDash = state.lineDash; - var lineDashOffset = state.lineDashOffset; - var lineJoin = state.lineJoin; - var lineWidth = state.lineWidth; - var miterLimit = state.miterLimit; + const strokeStyle = state.strokeStyle; + const lineCap = state.lineCap; + const lineDash = state.lineDash; + const lineDashOffset = state.lineDashOffset; + const lineJoin = state.lineJoin; + const lineWidth = state.lineWidth; + const miterLimit = state.miterLimit; if (state.currentStrokeStyle != strokeStyle || state.currentLineCap != lineCap || (lineDash != state.currentLineDash && !equals(state.currentLineDash, lineDash)) || @@ -1056,7 +1056,7 @@ _ol_render_canvas_Replay_.prototype.endGeometry = function(geometry, feature) { this.beginGeometryInstruction1_ = null; this.beginGeometryInstruction2_[2] = this.hitDetectionInstructions.length; this.beginGeometryInstruction2_ = null; - var endGeometryInstruction = + const endGeometryInstruction = [_ol_render_canvas_Instruction_.END_GEOMETRY, feature]; this.instructions.push(endGeometryInstruction); this.hitDetectionInstructions.push(endGeometryInstruction); @@ -1080,7 +1080,7 @@ _ol_render_canvas_Replay_.prototype.getBufferedMaxExtent = function() { if (!this.bufferedMaxExtent_) { this.bufferedMaxExtent_ = clone(this.maxExtent); if (this.maxLineWidth > 0) { - var width = this.resolution * (this.maxLineWidth + 1) / 2; + const width = this.resolution * (this.maxLineWidth + 1) / 2; buffer(this.bufferedMaxExtent_, width, this.bufferedMaxExtent_); } } diff --git a/src/ol/render/canvas/ReplayGroup.js b/src/ol/render/canvas/ReplayGroup.js index 3ae68cca7e..89f30a18f6 100644 --- a/src/ol/render/canvas/ReplayGroup.js +++ b/src/ol/render/canvas/ReplayGroup.js @@ -30,8 +30,8 @@ import _ol_transform_ from '../../transform.js'; * @param {number=} opt_renderBuffer Optional rendering buffer. * @struct */ -var _ol_render_canvas_ReplayGroup_ = function( - tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree, opt_renderBuffer) { +const _ol_render_canvas_ReplayGroup_ = function( + tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree, opt_renderBuffer) { _ol_render_ReplayGroup_.call(this); /** @@ -125,8 +125,8 @@ _ol_render_canvas_ReplayGroup_.circleArrayCache_ = { * @private */ _ol_render_canvas_ReplayGroup_.fillCircleArrayRowToMiddle_ = function(array, x, y) { - var i; - var radius = Math.floor(array.length / 2); + let i; + const radius = Math.floor(array.length / 2); if (x >= radius) { for (i = radius; i < x; i++) { array[i][y] = true; @@ -153,15 +153,15 @@ _ol_render_canvas_ReplayGroup_.getCircleArray_ = function(radius) { return _ol_render_canvas_ReplayGroup_.circleArrayCache_[radius]; } - var arraySize = radius * 2 + 1; - var arr = new Array(arraySize); - for (var i = 0; i < arraySize; i++) { + const arraySize = radius * 2 + 1; + const arr = new Array(arraySize); + for (let i = 0; i < arraySize; i++) { arr[i] = new Array(arraySize); } - var x = radius; - var y = 0; - var error = 0; + let x = radius; + let y = 0; + let error = 0; while (x >= y) { _ol_render_canvas_ReplayGroup_.fillCircleArrayRowToMiddle_(arr, radius + x, radius + y); @@ -192,13 +192,13 @@ _ol_render_canvas_ReplayGroup_.getCircleArray_ = function(radius) { * @param {number} rotation Rotation. */ _ol_render_canvas_ReplayGroup_.replayDeclutter = function(declutterReplays, context, rotation) { - var zs = Object.keys(declutterReplays).map(Number).sort(numberSafeCompareFunction); - var skippedFeatureUids = {}; - for (var z = 0, zz = zs.length; z < zz; ++z) { - var replayData = declutterReplays[zs[z].toString()]; - for (var i = 0, ii = replayData.length; i < ii;) { - var replay = replayData[i++]; - var transform = replayData[i++]; + const zs = Object.keys(declutterReplays).map(Number).sort(numberSafeCompareFunction); + const skippedFeatureUids = {}; + for (let z = 0, zz = zs.length; z < zz; ++z) { + const replayData = declutterReplays[zs[z].toString()]; + for (let i = 0, ii = replayData.length; i < ii;) { + const replay = replayData[i++]; + const transform = replayData[i++]; replay.replay(context, transform, rotation, skippedFeatureUids); } } @@ -210,7 +210,7 @@ _ol_render_canvas_ReplayGroup_.replayDeclutter = function(declutterReplays, cont * @return {ol.DeclutterGroup} Declutter instruction group. */ _ol_render_canvas_ReplayGroup_.prototype.addDeclutter = function(group) { - var declutter = null; + let declutter = null; if (this.declutterTree_) { if (group) { declutter = this.declutterGroup_; @@ -229,7 +229,7 @@ _ol_render_canvas_ReplayGroup_.prototype.addDeclutter = function(group) { * @param {ol.Transform} transform Transform. */ _ol_render_canvas_ReplayGroup_.prototype.clip = function(context, transform) { - var flatClipCoords = this.getClipCoords(transform); + const flatClipCoords = this.getClipCoords(transform); context.beginPath(); context.moveTo(flatClipCoords[0], flatClipCoords[1]); context.lineTo(flatClipCoords[2], flatClipCoords[3]); @@ -244,9 +244,9 @@ _ol_render_canvas_ReplayGroup_.prototype.clip = function(context, transform) { * @return {boolean} Has replays of the provided types. */ _ol_render_canvas_ReplayGroup_.prototype.hasReplays = function(replays) { - for (var zIndex in this.replaysByZIndex_) { - var candidates = this.replaysByZIndex_[zIndex]; - for (var i = 0, ii = replays.length; i < ii; ++i) { + for (const zIndex in this.replaysByZIndex_) { + const candidates = this.replaysByZIndex_[zIndex]; + for (let i = 0, ii = replays.length; i < ii; ++i) { if (replays[i] in candidates) { return true; } @@ -260,11 +260,10 @@ _ol_render_canvas_ReplayGroup_.prototype.hasReplays = function(replays) { * FIXME empty description for jsdoc */ _ol_render_canvas_ReplayGroup_.prototype.finish = function() { - var zKey; + let zKey; for (zKey in this.replaysByZIndex_) { - var replays = this.replaysByZIndex_[zKey]; - var replayKey; - for (replayKey in replays) { + const replays = this.replaysByZIndex_[zKey]; + for (const replayKey in replays) { replays[replayKey].finish(); } } @@ -286,16 +285,16 @@ _ol_render_canvas_ReplayGroup_.prototype.finish = function() { * @template T */ _ol_render_canvas_ReplayGroup_.prototype.forEachFeatureAtCoordinate = function( - coordinate, resolution, rotation, hitTolerance, skippedFeaturesHash, callback, declutterReplays) { + coordinate, resolution, rotation, hitTolerance, skippedFeaturesHash, callback, declutterReplays) { hitTolerance = Math.round(hitTolerance); - var contextSize = hitTolerance * 2 + 1; - var transform = _ol_transform_.compose(this.hitDetectionTransform_, - hitTolerance + 0.5, hitTolerance + 0.5, - 1 / resolution, -1 / resolution, - -rotation, - -coordinate[0], -coordinate[1]); - var context = this.hitDetectionContext_; + const contextSize = hitTolerance * 2 + 1; + const transform = _ol_transform_.compose(this.hitDetectionTransform_, + hitTolerance + 0.5, hitTolerance + 0.5, + 1 / resolution, -1 / resolution, + -rotation, + -coordinate[0], -coordinate[1]); + const context = this.hitDetectionContext_; if (context.canvas.width !== contextSize || context.canvas.height !== contextSize) { context.canvas.width = contextSize; @@ -307,34 +306,34 @@ _ol_render_canvas_ReplayGroup_.prototype.forEachFeatureAtCoordinate = function( /** * @type {ol.Extent} */ - var hitExtent; + let hitExtent; if (this.renderBuffer_ !== undefined) { hitExtent = createEmpty(); extendCoordinate(hitExtent, coordinate); buffer(hitExtent, resolution * (this.renderBuffer_ + hitTolerance), hitExtent); } - var mask = _ol_render_canvas_ReplayGroup_.getCircleArray_(hitTolerance); - var declutteredFeatures; + const mask = _ol_render_canvas_ReplayGroup_.getCircleArray_(hitTolerance); + let declutteredFeatures; if (this.declutterTree_) { declutteredFeatures = this.declutterTree_.all().map(function(entry) { return entry.value; }); } - var replayType; + let replayType; /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @return {?} Callback result. */ function featureCallback(feature) { - var imageData = context.getImageData(0, 0, contextSize, contextSize).data; - for (var i = 0; i < contextSize; i++) { - for (var j = 0; j < contextSize; j++) { + const imageData = context.getImageData(0, 0, contextSize, contextSize).data; + for (let i = 0; i < contextSize; i++) { + for (let j = 0; j < contextSize; j++) { if (mask[i][j]) { if (imageData[(j * contextSize + i) * 4 + 3] > 0) { - var result; + let result; if (!(declutteredFeatures && (replayType == ReplayType.IMAGE || replayType == ReplayType.TEXT)) || declutteredFeatures.indexOf(feature) !== -1) { result = callback(feature); @@ -352,12 +351,12 @@ _ol_render_canvas_ReplayGroup_.prototype.forEachFeatureAtCoordinate = function( } /** @type {Array.} */ - var zs = Object.keys(this.replaysByZIndex_).map(Number); + const zs = Object.keys(this.replaysByZIndex_).map(Number); zs.sort(numberSafeCompareFunction); - var i, j, replays, replay, result; + let i, j, replays, replay, result; for (i = zs.length - 1; i >= 0; --i) { - var zIndexKey = zs[i].toString(); + const zIndexKey = zs[i].toString(); replays = this.replaysByZIndex_[zIndexKey]; for (j = _ol_render_replay_.ORDER.length - 1; j >= 0; --j) { replayType = _ol_render_replay_.ORDER[j]; @@ -365,7 +364,7 @@ _ol_render_canvas_ReplayGroup_.prototype.forEachFeatureAtCoordinate = function( if (replay !== undefined) { if (declutterReplays && (replayType == ReplayType.IMAGE || replayType == ReplayType.TEXT)) { - var declutter = declutterReplays[zIndexKey]; + const declutter = declutterReplays[zIndexKey]; if (!declutter) { declutterReplays[zIndexKey] = [replay, transform.slice(0)]; } else { @@ -373,7 +372,7 @@ _ol_render_canvas_ReplayGroup_.prototype.forEachFeatureAtCoordinate = function( } } else { result = replay.replayHitDetection(context, transform, rotation, - skippedFeaturesHash, featureCallback, hitExtent); + skippedFeaturesHash, featureCallback, hitExtent); if (result) { return result; } @@ -390,14 +389,14 @@ _ol_render_canvas_ReplayGroup_.prototype.forEachFeatureAtCoordinate = function( * @return {Array.} Clip coordinates. */ _ol_render_canvas_ReplayGroup_.prototype.getClipCoords = function(transform) { - var maxExtent = this.maxExtent_; - var minX = maxExtent[0]; - var minY = maxExtent[1]; - var maxX = maxExtent[2]; - var maxY = maxExtent[3]; - var flatClipCoords = [minX, minY, minX, maxY, maxX, maxY, maxX, minY]; + const maxExtent = this.maxExtent_; + const minX = maxExtent[0]; + const minY = maxExtent[1]; + const maxX = maxExtent[2]; + const maxY = maxExtent[3]; + const flatClipCoords = [minX, minY, minX, maxY, maxX, maxY, maxX, minY]; _ol_geom_flat_transform_.transform2D( - flatClipCoords, 0, 8, 2, transform, flatClipCoords); + flatClipCoords, 0, 8, 2, transform, flatClipCoords); return flatClipCoords; }; @@ -406,17 +405,17 @@ _ol_render_canvas_ReplayGroup_.prototype.getClipCoords = function(transform) { * @inheritDoc */ _ol_render_canvas_ReplayGroup_.prototype.getReplay = function(zIndex, replayType) { - var zIndexKey = zIndex !== undefined ? zIndex.toString() : '0'; - var replays = this.replaysByZIndex_[zIndexKey]; + const zIndexKey = zIndex !== undefined ? zIndex.toString() : '0'; + let replays = this.replaysByZIndex_[zIndexKey]; if (replays === undefined) { replays = {}; this.replaysByZIndex_[zIndexKey] = replays; } - var replay = replays[replayType]; + let replay = replays[replayType]; if (replay === undefined) { - var Constructor = _ol_render_canvas_ReplayGroup_.BATCH_CONSTRUCTORS_[replayType]; + const Constructor = _ol_render_canvas_ReplayGroup_.BATCH_CONSTRUCTORS_[replayType]; replay = new Constructor(this.tolerance_, this.maxExtent_, - this.resolution_, this.pixelRatio_, this.overlaps_, this.declutterTree_); + this.resolution_, this.pixelRatio_, this.overlaps_, this.declutterTree_); replays[replayType] = replay; } return replay; @@ -451,10 +450,10 @@ _ol_render_canvas_ReplayGroup_.prototype.isEmpty = function() { * replays. */ _ol_render_canvas_ReplayGroup_.prototype.replay = function(context, - transform, viewRotation, skippedFeaturesHash, opt_replayTypes, opt_declutterReplays) { + transform, viewRotation, skippedFeaturesHash, opt_replayTypes, opt_declutterReplays) { /** @type {Array.} */ - var zs = Object.keys(this.replaysByZIndex_).map(Number); + const zs = Object.keys(this.replaysByZIndex_).map(Number); zs.sort(numberSafeCompareFunction); // setup clipping so that the parts of over-simplified geometries are not @@ -462,18 +461,18 @@ _ol_render_canvas_ReplayGroup_.prototype.replay = function(context, context.save(); this.clip(context, transform); - var replayTypes = opt_replayTypes ? opt_replayTypes : _ol_render_replay_.ORDER; - var i, ii, j, jj, replays, replay; + const replayTypes = opt_replayTypes ? opt_replayTypes : _ol_render_replay_.ORDER; + let i, ii, j, jj, replays, replay; for (i = 0, ii = zs.length; i < ii; ++i) { - var zIndexKey = zs[i].toString(); + const zIndexKey = zs[i].toString(); replays = this.replaysByZIndex_[zIndexKey]; for (j = 0, jj = replayTypes.length; j < jj; ++j) { - var replayType = replayTypes[j]; + const replayType = replayTypes[j]; replay = replays[replayType]; if (replay !== undefined) { if (opt_declutterReplays && (replayType == ReplayType.IMAGE || replayType == ReplayType.TEXT)) { - var declutter = opt_declutterReplays[zIndexKey]; + const declutter = opt_declutterReplays[zIndexKey]; if (!declutter) { opt_declutterReplays[zIndexKey] = [replay, transform.slice(0)]; } else { diff --git a/src/ol/render/canvas/TextReplay.js b/src/ol/render/canvas/TextReplay.js index ef4d2e286d..e63f277863 100644 --- a/src/ol/render/canvas/TextReplay.js +++ b/src/ol/render/canvas/TextReplay.js @@ -25,10 +25,10 @@ import TextPlacement from '../../style/TextPlacement.js'; * @param {?} declutterTree Declutter tree. * @struct */ -var _ol_render_canvas_TextReplay_ = function( - tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree) { +const _ol_render_canvas_TextReplay_ = function( + tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree) { _ol_render_canvas_Replay_.call(this, - tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree); + tolerance, maxExtent, resolution, pixelRatio, overlaps, declutterTree); /** * @private @@ -129,7 +129,7 @@ var _ol_render_canvas_TextReplay_ = function( */ this.widths_ = {}; - var labelCache = _ol_render_canvas_.labelCache; + const labelCache = _ol_render_canvas_.labelCache; labelCache.prune(); }; @@ -145,9 +145,9 @@ inherits(_ol_render_canvas_TextReplay_, _ol_render_canvas_Replay_); * @return {number} Width of the whole text. */ _ol_render_canvas_TextReplay_.measureTextWidths = function(font, lines, widths) { - var numLines = lines.length; - var width = 0; - var currentWidth, i; + const numLines = lines.length; + let width = 0; + let currentWidth, i; for (i = 0; i < numLines; ++i) { currentWidth = _ol_render_canvas_.measureTextWidth(font, lines[i]); width = Math.max(width, currentWidth); @@ -161,26 +161,26 @@ _ol_render_canvas_TextReplay_.measureTextWidths = function(font, lines, widths) * @inheritDoc */ _ol_render_canvas_TextReplay_.prototype.drawText = function(geometry, feature) { - var fillState = this.textFillState_; - var strokeState = this.textStrokeState_; - var textState = this.textState_; + const fillState = this.textFillState_; + const strokeState = this.textStrokeState_; + const textState = this.textState_; if (this.text_ === '' || !textState || (!fillState && !strokeState)) { return; } - var begin = this.coordinates.length; + let begin = this.coordinates.length; - var geometryType = geometry.getType(); - var flatCoordinates = null; - var end = 2; - var stride = 2; - var i, ii; + const geometryType = geometry.getType(); + let flatCoordinates = null; + let end = 2; + let stride = 2; + let i, ii; if (textState.placement === TextPlacement.LINE) { if (!intersects(this.getBufferedMaxExtent(), geometry.getExtent())) { return; } - var ends; + let ends; flatCoordinates = geometry.getFlatCoordinates(); stride = geometry.getStride(); if (geometryType == GeometryType.LINE_STRING) { @@ -190,20 +190,20 @@ _ol_render_canvas_TextReplay_.prototype.drawText = function(geometry, feature) { } else if (geometryType == GeometryType.POLYGON) { ends = geometry.getEnds().slice(0, 1); } else if (geometryType == GeometryType.MULTI_POLYGON) { - var endss = geometry.getEndss(); + const endss = geometry.getEndss(); ends = []; for (i = 0, ii = endss.length; i < ii; ++i) { ends.push(endss[i][0]); } } this.beginGeometry(geometry, feature); - var textAlign = textState.textAlign; - var flatOffset = 0; - var flatEnd; - for (var o = 0, oo = ends.length; o < oo; ++o) { + const textAlign = textState.textAlign; + let flatOffset = 0; + let flatEnd; + for (let o = 0, oo = ends.length; o < oo; ++o) { if (textAlign == undefined) { - var range = _ol_geom_flat_straightchunk_.lineString( - textState.maxAngle, flatCoordinates, flatOffset, ends[o], stride); + const range = _ol_geom_flat_straightchunk_.lineString( + textState.maxAngle, flatCoordinates, flatOffset, ends[o], stride); flatOffset = range[0]; flatEnd = range[1]; } else { @@ -220,8 +220,8 @@ _ol_render_canvas_TextReplay_.prototype.drawText = function(geometry, feature) { this.endGeometry(geometry, feature); } else { - var label = this.getImage(this.text_, this.textKey_, this.fillKey_, this.strokeKey_); - var width = label.width / this.pixelRatio; + const label = this.getImage(this.text_, this.textKey_, this.fillKey_, this.strokeKey_); + const width = label.width / this.pixelRatio; switch (geometryType) { case GeometryType.POINT: case GeometryType.MULTI_POINT: @@ -246,7 +246,7 @@ _ol_render_canvas_TextReplay_.prototype.drawText = function(geometry, feature) { stride = 3; break; case GeometryType.MULTI_POLYGON: - var interiorPoints = /** @type {ol.geom.MultiPolygon} */ (geometry).getFlatInteriorPoints(); + const interiorPoints = /** @type {ol.geom.MultiPolygon} */ (geometry).getFlatInteriorPoints(); flatCoordinates = []; for (i = 0, ii = interiorPoints.length; i < ii; i += 3) { if (textState.overflow || interiorPoints[i + 2] / this.resolution >= width) { @@ -283,29 +283,29 @@ _ol_render_canvas_TextReplay_.prototype.drawText = function(geometry, feature) { * @return {HTMLCanvasElement} Image. */ _ol_render_canvas_TextReplay_.prototype.getImage = function(text, textKey, fillKey, strokeKey) { - var label; - var key = strokeKey + textKey + text + fillKey + this.pixelRatio; + let label; + const key = strokeKey + textKey + text + fillKey + this.pixelRatio; - var labelCache = _ol_render_canvas_.labelCache; + const labelCache = _ol_render_canvas_.labelCache; if (!labelCache.containsKey(key)) { - var strokeState = strokeKey ? this.strokeStates[strokeKey] || this.textStrokeState_ : null; - var fillState = fillKey ? this.fillStates[fillKey] || this.textFillState_ : null; - var textState = this.textStates[textKey] || this.textState_; - var pixelRatio = this.pixelRatio; - var scale = textState.scale * pixelRatio; - var align = _ol_render_replay_.TEXT_ALIGN[textState.textAlign || _ol_render_canvas_.defaultTextAlign]; - var strokeWidth = strokeKey && strokeState.lineWidth ? strokeState.lineWidth : 0; + const strokeState = strokeKey ? this.strokeStates[strokeKey] || this.textStrokeState_ : null; + const fillState = fillKey ? this.fillStates[fillKey] || this.textFillState_ : null; + const textState = this.textStates[textKey] || this.textState_; + const pixelRatio = this.pixelRatio; + const scale = textState.scale * pixelRatio; + const align = _ol_render_replay_.TEXT_ALIGN[textState.textAlign || _ol_render_canvas_.defaultTextAlign]; + const strokeWidth = strokeKey && strokeState.lineWidth ? strokeState.lineWidth : 0; - var lines = text.split('\n'); - var numLines = lines.length; - var widths = []; - var width = _ol_render_canvas_TextReplay_.measureTextWidths(textState.font, lines, widths); - var lineHeight = _ol_render_canvas_.measureTextHeight(textState.font); - var height = lineHeight * numLines; - var renderWidth = (width + strokeWidth); - var context = createCanvasContext2D( - Math.ceil(renderWidth * scale), - Math.ceil((height + strokeWidth) * scale)); + const lines = text.split('\n'); + const numLines = lines.length; + const widths = []; + const width = _ol_render_canvas_TextReplay_.measureTextWidths(textState.font, lines, widths); + const lineHeight = _ol_render_canvas_.measureTextHeight(textState.font); + const height = lineHeight * numLines; + const renderWidth = (width + strokeWidth); + const context = createCanvasContext2D( + Math.ceil(renderWidth * scale), + Math.ceil((height + strokeWidth) * scale)); label = context.canvas; labelCache.set(key, label); if (scale != 1) { @@ -328,9 +328,9 @@ _ol_render_canvas_TextReplay_.prototype.getImage = function(text, textKey, fillK } context.textBaseline = 'middle'; context.textAlign = 'center'; - var leftRight = (0.5 - align); - var x = align * label.width / scale + leftRight * strokeWidth; - var i; + const leftRight = (0.5 - align); + const x = align * label.width / scale + leftRight * strokeWidth; + let i; if (strokeKey) { for (i = 0; i < numLines; ++i) { context.strokeText(lines[i], x + leftRight * widths[i], 0.5 * (strokeWidth + lineHeight) + i * lineHeight); @@ -353,15 +353,15 @@ _ol_render_canvas_TextReplay_.prototype.getImage = function(text, textKey, fillK * @param {number} end End. */ _ol_render_canvas_TextReplay_.prototype.drawTextImage_ = function(label, begin, end) { - var textState = this.textState_; - var strokeState = this.textStrokeState_; - var pixelRatio = this.pixelRatio; - var align = _ol_render_replay_.TEXT_ALIGN[textState.textAlign || _ol_render_canvas_.defaultTextAlign]; - var baseline = _ol_render_replay_.TEXT_ALIGN[textState.textBaseline]; - var strokeWidth = strokeState && strokeState.lineWidth ? strokeState.lineWidth : 0; + const textState = this.textState_; + const strokeState = this.textStrokeState_; + const pixelRatio = this.pixelRatio; + const align = _ol_render_replay_.TEXT_ALIGN[textState.textAlign || _ol_render_canvas_.defaultTextAlign]; + const baseline = _ol_render_replay_.TEXT_ALIGN[textState.textBaseline]; + const strokeWidth = strokeState && strokeState.lineWidth ? strokeState.lineWidth : 0; - var anchorX = align * label.width / pixelRatio + 2 * (0.5 - align) * strokeWidth; - var anchorY = baseline * label.height / pixelRatio + 2 * (0.5 - baseline) * strokeWidth; + const anchorX = align * label.width / pixelRatio + 2 * (0.5 - align) * strokeWidth; + const anchorY = baseline * label.height / pixelRatio + 2 * (0.5 - baseline) * strokeWidth; this.instructions.push([_ol_render_canvas_Instruction_.DRAW_IMAGE, begin, end, label, (anchorX - this.textOffsetX_) * pixelRatio, (anchorY - this.textOffsetY_) * pixelRatio, this.declutterGroup_, label.height, 1, 0, 0, this.textRotateWithView_, this.textRotation_, @@ -388,11 +388,11 @@ _ol_render_canvas_TextReplay_.prototype.drawTextImage_ = function(label, begin, * @param {ol.DeclutterGroup} declutterGroup Declutter group. */ _ol_render_canvas_TextReplay_.prototype.drawChars_ = function(begin, end, declutterGroup) { - var strokeState = this.textStrokeState_; - var textState = this.textState_; - var fillState = this.textFillState_; + const strokeState = this.textStrokeState_; + const textState = this.textState_; + const fillState = this.textFillState_; - var strokeKey = this.strokeKey_; + const strokeKey = this.strokeKey_; if (strokeState) { if (!(strokeKey in this.strokeStates)) { this.strokeStates[strokeKey] = /** @type {ol.CanvasStrokeState} */ ({ @@ -406,7 +406,7 @@ _ol_render_canvas_TextReplay_.prototype.drawChars_ = function(begin, end, declut }); } } - var textKey = this.textKey_; + const textKey = this.textKey_; if (!(this.textKey_ in this.textStates)) { this.textStates[this.textKey_] = /** @type {ol.CanvasTextState} */ ({ font: textState.font, @@ -414,7 +414,7 @@ _ol_render_canvas_TextReplay_.prototype.drawChars_ = function(begin, end, declut scale: textState.scale }); } - var fillKey = this.fillKey_; + const fillKey = this.fillKey_; if (fillState) { if (!(fillKey in this.fillStates)) { this.fillStates[fillKey] = /** @type {ol.CanvasFillState} */ ({ @@ -423,15 +423,15 @@ _ol_render_canvas_TextReplay_.prototype.drawChars_ = function(begin, end, declut } } - var pixelRatio = this.pixelRatio; - var baseline = _ol_render_replay_.TEXT_ALIGN[textState.textBaseline]; + const pixelRatio = this.pixelRatio; + const baseline = _ol_render_replay_.TEXT_ALIGN[textState.textBaseline]; - var offsetY = this.textOffsetY_ * pixelRatio; - var text = this.text_; - var font = textState.font; - var textScale = textState.scale; - var strokeWidth = strokeState ? strokeState.lineWidth * textScale / 2 : 0; - var widths = this.widths_[font]; + const offsetY = this.textOffsetY_ * pixelRatio; + const text = this.text_; + const font = textState.font; + const textScale = textState.scale; + const strokeWidth = strokeState ? strokeState.lineWidth * textScale / 2 : 0; + let widths = this.widths_[font]; if (!widths) { this.widths_[font] = widths = {}; } @@ -439,7 +439,7 @@ _ol_render_canvas_TextReplay_.prototype.drawChars_ = function(begin, end, declut begin, end, baseline, declutterGroup, textState.overflow, fillKey, textState.maxAngle, function(text) { - var width = widths[text]; + let width = widths[text]; if (!width) { width = widths[text] = _ol_render_canvas_.measureTextWidth(font, text); } @@ -451,7 +451,7 @@ _ol_render_canvas_TextReplay_.prototype.drawChars_ = function(begin, end, declut begin, end, baseline, declutterGroup, textState.overflow, fillKey, textState.maxAngle, function(text) { - var width = widths[text]; + let width = widths[text]; if (!width) { width = widths[text] = _ol_render_canvas_.measureTextWidth(font, text); } @@ -466,13 +466,13 @@ _ol_render_canvas_TextReplay_.prototype.drawChars_ = function(begin, end, declut * @inheritDoc */ _ol_render_canvas_TextReplay_.prototype.setTextStyle = function(textStyle, declutterGroup) { - var textState, fillState, strokeState; + let textState, fillState, strokeState; if (!textStyle) { this.text_ = ''; } else { this.declutterGroup_ = /** @type {ol.DeclutterGroup} */ (declutterGroup); - var textFillStyle = textStyle.getFill(); + const textFillStyle = textStyle.getFill(); if (!textFillStyle) { fillState = this.textFillState_ = null; } else { @@ -481,10 +481,10 @@ _ol_render_canvas_TextReplay_.prototype.setTextStyle = function(textStyle, declu fillState = this.textFillState_ = /** @type {ol.CanvasFillState} */ ({}); } fillState.fillStyle = asColorLike( - textFillStyle.getColor() || _ol_render_canvas_.defaultFillStyle); + textFillStyle.getColor() || _ol_render_canvas_.defaultFillStyle); } - var textStrokeStyle = textStyle.getStroke(); + const textStrokeStyle = textStyle.getStroke(); if (!textStrokeStyle) { strokeState = this.textStrokeState_ = null; } else { @@ -492,10 +492,10 @@ _ol_render_canvas_TextReplay_.prototype.setTextStyle = function(textStyle, declu if (!strokeState) { strokeState = this.textStrokeState_ = /** @type {ol.CanvasStrokeState} */ ({}); } - var lineDash = textStrokeStyle.getLineDash(); - var lineDashOffset = textStrokeStyle.getLineDashOffset(); - var lineWidth = textStrokeStyle.getWidth(); - var miterLimit = textStrokeStyle.getMiterLimit(); + const lineDash = textStrokeStyle.getLineDash(); + const lineDashOffset = textStrokeStyle.getLineDashOffset(); + const lineWidth = textStrokeStyle.getWidth(); + const miterLimit = textStrokeStyle.getMiterLimit(); strokeState.lineCap = textStrokeStyle.getLineCap() || _ol_render_canvas_.defaultLineCap; strokeState.lineDash = lineDash ? lineDash.slice() : _ol_render_canvas_.defaultLineDash; strokeState.lineDashOffset = @@ -506,13 +506,13 @@ _ol_render_canvas_TextReplay_.prototype.setTextStyle = function(textStyle, declu strokeState.miterLimit = miterLimit === undefined ? _ol_render_canvas_.defaultMiterLimit : miterLimit; strokeState.strokeStyle = asColorLike( - textStrokeStyle.getColor() || _ol_render_canvas_.defaultStrokeStyle); + textStrokeStyle.getColor() || _ol_render_canvas_.defaultStrokeStyle); } textState = this.textState_; - var font = textStyle.getFont() || _ol_render_canvas_.defaultFont; + const font = textStyle.getFont() || _ol_render_canvas_.defaultFont; _ol_render_canvas_.checkFont(font); - var textScale = textStyle.getScale(); + const textScale = textStyle.getScale(); textState.overflow = textStyle.getOverflow(); textState.font = font; textState.maxAngle = textStyle.getMaxAngle(); @@ -524,10 +524,10 @@ _ol_render_canvas_TextReplay_.prototype.setTextStyle = function(textStyle, declu textState.padding = textStyle.getPadding() || _ol_render_canvas_.defaultPadding; textState.scale = textScale === undefined ? 1 : textScale; - var textOffsetX = textStyle.getOffsetX(); - var textOffsetY = textStyle.getOffsetY(); - var textRotateWithView = textStyle.getRotateWithView(); - var textRotation = textStyle.getRotation(); + const textOffsetX = textStyle.getOffsetX(); + const textOffsetY = textStyle.getOffsetY(); + const textRotateWithView = textStyle.getRotateWithView(); + const textRotation = textStyle.getRotation(); this.text_ = textStyle.getText() || ''; this.textOffsetX_ = textOffsetX === undefined ? 0 : textOffsetX; this.textOffsetY_ = textOffsetY === undefined ? 0 : textOffsetY; diff --git a/src/ol/render/replay.js b/src/ol/render/replay.js index e9d554d756..c477763e7a 100644 --- a/src/ol/render/replay.js +++ b/src/ol/render/replay.js @@ -2,7 +2,7 @@ * @module ol/render/replay */ import ReplayType from '../render/ReplayType.js'; -var _ol_render_replay_ = {}; +const _ol_render_replay_ = {}; /** diff --git a/src/ol/render/webgl.js b/src/ol/render/webgl.js index fbb0b61ef0..b02b092533 100644 --- a/src/ol/render/webgl.js +++ b/src/ol/render/webgl.js @@ -1,7 +1,7 @@ /** * @module ol/render/webgl */ -var _ol_render_webgl_ = {}; +const _ol_render_webgl_ = {}; /** @@ -90,7 +90,7 @@ _ol_render_webgl_.defaultLineWidth = 1; * @return {boolean|undefined} Triangle is clockwise. */ _ol_render_webgl_.triangleIsCounterClockwise = function(x1, y1, x2, y2, x3, y3) { - var area = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1); + const area = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1); return (area <= _ol_render_webgl_.EPSILON && area >= -_ol_render_webgl_.EPSILON) ? undefined : area > 0; }; diff --git a/src/ol/render/webgl/CircleReplay.js b/src/ol/render/webgl/CircleReplay.js index dc08fa678d..3b976e5bb0 100644 --- a/src/ol/render/webgl/CircleReplay.js +++ b/src/ol/render/webgl/CircleReplay.js @@ -21,7 +21,7 @@ import _ol_webgl_Buffer_ from '../../webgl/Buffer.js'; * @param {ol.Extent} maxExtent Max extent. * @struct */ -var _ol_render_webgl_CircleReplay_ = function(tolerance, maxExtent) { +const _ol_render_webgl_CircleReplay_ = function(tolerance, maxExtent) { _ol_render_webgl_Replay_.call(this, tolerance, maxExtent); /** @@ -79,11 +79,11 @@ inherits(_ol_render_webgl_CircleReplay_, _ol_render_webgl_Replay_); * @param {number} stride Stride. */ _ol_render_webgl_CircleReplay_.prototype.drawCoordinates_ = function( - flatCoordinates, offset, end, stride) { - var numVertices = this.vertices.length; - var numIndices = this.indices.length; - var n = numVertices / 4; - var i, ii; + flatCoordinates, offset, end, stride) { + let numVertices = this.vertices.length; + let numIndices = this.indices.length; + let n = numVertices / 4; + let i, ii; for (i = offset, ii = end; i < ii; i += stride) { this.vertices[numVertices++] = flatCoordinates[i]; this.vertices[numVertices++] = flatCoordinates[i + 1]; @@ -122,8 +122,8 @@ _ol_render_webgl_CircleReplay_.prototype.drawCoordinates_ = function( * @inheritDoc */ _ol_render_webgl_CircleReplay_.prototype.drawCircle = function(circleGeometry, feature) { - var radius = circleGeometry.getRadius(); - var stride = circleGeometry.getStride(); + const radius = circleGeometry.getRadius(); + const stride = circleGeometry.getStride(); if (radius) { this.startIndices.push(this.indices.length); this.startIndicesFeature.push(feature); @@ -133,15 +133,15 @@ _ol_render_webgl_CircleReplay_.prototype.drawCircle = function(circleGeometry, f } this.radius_ = radius; - var flatCoordinates = circleGeometry.getFlatCoordinates(); + let flatCoordinates = circleGeometry.getFlatCoordinates(); flatCoordinates = _ol_geom_flat_transform_.translate(flatCoordinates, 0, 2, - stride, -this.origin[0], -this.origin[1]); + stride, -this.origin[0], -this.origin[1]); this.drawCoordinates_(flatCoordinates, 0, 2, stride); } else { if (this.state_.changed) { this.styles_.pop(); if (this.styles_.length) { - var lastState = this.styles_[this.styles_.length - 1]; + const lastState = this.styles_[this.styles_.length - 1]; this.state_.fillColor = /** @type {Array.} */ (lastState[0]); this.state_.strokeColor = /** @type {Array.} */ (lastState[1]); this.state_.lineWidth = /** @type {number} */ (lastState[2]); @@ -182,8 +182,8 @@ _ol_render_webgl_CircleReplay_.prototype.getDeleteResourcesFunction = function(c // be used by other CircleReplay instances (for other layers). And // they will be deleted when disposing of the ol.webgl.Context // object. - var verticesBuffer = this.verticesBuffer; - var indicesBuffer = this.indicesBuffer; + const verticesBuffer = this.verticesBuffer; + const indicesBuffer = this.indicesBuffer; return function() { context.deleteBuffer(verticesBuffer); context.deleteBuffer(indicesBuffer); @@ -196,13 +196,12 @@ _ol_render_webgl_CircleReplay_.prototype.getDeleteResourcesFunction = function(c */ _ol_render_webgl_CircleReplay_.prototype.setUpProgram = function(gl, context, size, pixelRatio) { // get the program - var fragmentShader, vertexShader; - fragmentShader = _ol_render_webgl_circlereplay_defaultshader_.fragment; - vertexShader = _ol_render_webgl_circlereplay_defaultshader_.vertex; - var program = context.getProgram(fragmentShader, vertexShader); + const fragmentShader = _ol_render_webgl_circlereplay_defaultshader_.fragment; + const vertexShader = _ol_render_webgl_circlereplay_defaultshader_.vertex; + const program = context.getProgram(fragmentShader, vertexShader); // get the locations - var locations; + let locations; if (!this.defaultLocations_) { locations = new _ol_render_webgl_circlereplay_defaultshader_Locations_(gl, program); this.defaultLocations_ = locations; @@ -215,15 +214,15 @@ _ol_render_webgl_CircleReplay_.prototype.setUpProgram = function(gl, context, si // enable the vertex attrib arrays gl.enableVertexAttribArray(locations.a_position); gl.vertexAttribPointer(locations.a_position, 2, _ol_webgl_.FLOAT, - false, 16, 0); + false, 16, 0); gl.enableVertexAttribArray(locations.a_instruction); gl.vertexAttribPointer(locations.a_instruction, 1, _ol_webgl_.FLOAT, - false, 16, 8); + false, 16, 8); gl.enableVertexAttribArray(locations.a_radius); gl.vertexAttribPointer(locations.a_radius, 1, _ol_webgl_.FLOAT, - false, 16, 12); + false, 16, 12); // Enable renderer specific uniforms. gl.uniform2fv(locations.u_size, size); @@ -251,14 +250,14 @@ _ol_render_webgl_CircleReplay_.prototype.drawReplay = function(gl, context, skip this.drawReplaySkipping_(gl, context, skippedFeaturesHash); } else { //Draw by style groups to minimize drawElements() calls. - var i, start, end, nextStyle; + let i, start, end, nextStyle; end = this.startIndices[this.startIndices.length - 1]; for (i = this.styleIndices_.length - 1; i >= 0; --i) { start = this.styleIndices_[i]; nextStyle = this.styles_[i]; this.setFillStyle_(gl, /** @type {Array.} */ (nextStyle[0])); this.setStrokeStyle_(gl, /** @type {Array.} */ (nextStyle[1]), - /** @type {number} */ (nextStyle[2])); + /** @type {number} */ (nextStyle[2])); this.drawElements(gl, context, start, end); end = start; } @@ -270,15 +269,15 @@ _ol_render_webgl_CircleReplay_.prototype.drawReplay = function(gl, context, skip * @inheritDoc */ _ol_render_webgl_CircleReplay_.prototype.drawHitDetectionReplayOneByOne = function(gl, context, skippedFeaturesHash, - featureCallback, opt_hitExtent) { - var i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex; + featureCallback, opt_hitExtent) { + let i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex; featureIndex = this.startIndices.length - 2; end = this.startIndices[featureIndex + 1]; for (i = this.styleIndices_.length - 1; i >= 0; --i) { nextStyle = this.styles_[i]; this.setFillStyle_(gl, /** @type {Array.} */ (nextStyle[0])); this.setStrokeStyle_(gl, /** @type {Array.} */ (nextStyle[1]), - /** @type {number} */ (nextStyle[2])); + /** @type {number} */ (nextStyle[2])); groupStart = this.styleIndices_[i]; while (featureIndex >= 0 && @@ -290,12 +289,12 @@ _ol_render_webgl_CircleReplay_.prototype.drawHitDetectionReplayOneByOne = functi if (skippedFeaturesHash[featureUid] === undefined && feature.getGeometry() && (opt_hitExtent === undefined || intersects( - /** @type {Array} */ (opt_hitExtent), - feature.getGeometry().getExtent()))) { + /** @type {Array} */ (opt_hitExtent), + feature.getGeometry().getExtent()))) { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); this.drawElements(gl, context, start, end); - var result = featureCallback(feature); + const result = featureCallback(feature); if (result) { return result; @@ -317,14 +316,14 @@ _ol_render_webgl_CircleReplay_.prototype.drawHitDetectionReplayOneByOne = functi * @param {Object} skippedFeaturesHash Ids of features to skip. */ _ol_render_webgl_CircleReplay_.prototype.drawReplaySkipping_ = function(gl, context, skippedFeaturesHash) { - var i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex, featureStart; + let i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex, featureStart; featureIndex = this.startIndices.length - 2; end = start = this.startIndices[featureIndex + 1]; for (i = this.styleIndices_.length - 1; i >= 0; --i) { nextStyle = this.styles_[i]; this.setFillStyle_(gl, /** @type {Array.} */ (nextStyle[0])); this.setStrokeStyle_(gl, /** @type {Array.} */ (nextStyle[1]), - /** @type {number} */ (nextStyle[2])); + /** @type {number} */ (nextStyle[2])); groupStart = this.styleIndices_[i]; while (featureIndex >= 0 && @@ -376,12 +375,12 @@ _ol_render_webgl_CircleReplay_.prototype.setStrokeStyle_ = function(gl, color, l * @inheritDoc */ _ol_render_webgl_CircleReplay_.prototype.setFillStrokeStyle = function(fillStyle, strokeStyle) { - var strokeStyleColor, strokeStyleWidth; + let strokeStyleColor, strokeStyleWidth; if (strokeStyle) { - var strokeStyleLineDash = strokeStyle.getLineDash(); + const strokeStyleLineDash = strokeStyle.getLineDash(); this.state_.lineDash = strokeStyleLineDash ? strokeStyleLineDash : _ol_render_webgl_.defaultLineDash; - var strokeStyleLineDashOffset = strokeStyle.getLineDashOffset(); + const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset(); this.state_.lineDashOffset = strokeStyleLineDashOffset ? strokeStyleLineDashOffset : _ol_render_webgl_.defaultLineDashOffset; strokeStyleColor = strokeStyle.getColor(); @@ -400,7 +399,7 @@ _ol_render_webgl_CircleReplay_.prototype.setFillStrokeStyle = function(fillStyle strokeStyleColor = [0, 0, 0, 0]; strokeStyleWidth = 0; } - var fillStyleColor = fillStyle ? fillStyle.getColor() : [0, 0, 0, 0]; + let fillStyleColor = fillStyle ? fillStyle.getColor() : [0, 0, 0, 0]; if (!(fillStyleColor instanceof CanvasGradient) && !(fillStyleColor instanceof CanvasPattern)) { fillStyleColor = asArray(fillStyleColor).map(function(c, i) { diff --git a/src/ol/render/webgl/ImageReplay.js b/src/ol/render/webgl/ImageReplay.js index c72d3f4ff0..7df8d22304 100644 --- a/src/ol/render/webgl/ImageReplay.js +++ b/src/ol/render/webgl/ImageReplay.js @@ -12,7 +12,7 @@ import _ol_webgl_Buffer_ from '../../webgl/Buffer.js'; * @param {ol.Extent} maxExtent Max extent. * @struct */ -var _ol_render_webgl_ImageReplay_ = function(tolerance, maxExtent) { +const _ol_render_webgl_ImageReplay_ = function(tolerance, maxExtent) { _ol_render_webgl_TextureReplay_.call(this, tolerance, maxExtent); /** @@ -50,10 +50,10 @@ inherits(_ol_render_webgl_ImageReplay_, _ol_render_webgl_TextureReplay_); _ol_render_webgl_ImageReplay_.prototype.drawMultiPoint = function(multiPointGeometry, feature) { this.startIndices.push(this.indices.length); this.startIndicesFeature.push(feature); - var flatCoordinates = multiPointGeometry.getFlatCoordinates(); - var stride = multiPointGeometry.getStride(); + const flatCoordinates = multiPointGeometry.getFlatCoordinates(); + const stride = multiPointGeometry.getStride(); this.drawCoordinates( - flatCoordinates, 0, flatCoordinates.length, stride); + flatCoordinates, 0, flatCoordinates.length, stride); }; @@ -63,10 +63,10 @@ _ol_render_webgl_ImageReplay_.prototype.drawMultiPoint = function(multiPointGeom _ol_render_webgl_ImageReplay_.prototype.drawPoint = function(pointGeometry, feature) { this.startIndices.push(this.indices.length); this.startIndicesFeature.push(feature); - var flatCoordinates = pointGeometry.getFlatCoordinates(); - var stride = pointGeometry.getStride(); + const flatCoordinates = pointGeometry.getFlatCoordinates(); + const stride = pointGeometry.getStride(); this.drawCoordinates( - flatCoordinates, 0, flatCoordinates.length, stride); + flatCoordinates, 0, flatCoordinates.length, stride); }; @@ -74,7 +74,7 @@ _ol_render_webgl_ImageReplay_.prototype.drawPoint = function(pointGeometry, feat * @inheritDoc */ _ol_render_webgl_ImageReplay_.prototype.finish = function(context) { - var gl = context.getGL(); + const gl = context.getGL(); this.groupIndices.push(this.indices.length); this.hitDetectionGroupIndices.push(this.indices.length); @@ -82,19 +82,19 @@ _ol_render_webgl_ImageReplay_.prototype.finish = function(context) { // create, bind, and populate the vertices buffer this.verticesBuffer = new _ol_webgl_Buffer_(this.vertices); - var indices = this.indices; + const indices = this.indices; // create, bind, and populate the indices buffer this.indicesBuffer = new _ol_webgl_Buffer_(indices); // create textures /** @type {Object.} */ - var texturePerImage = {}; + const texturePerImage = {}; this.createTextures(this.textures_, this.images_, texturePerImage, gl); this.createTextures(this.hitDetectionTextures_, this.hitDetectionImages_, - texturePerImage, gl); + texturePerImage, gl); this.images_ = null; this.hitDetectionImages_ = null; @@ -106,18 +106,18 @@ _ol_render_webgl_ImageReplay_.prototype.finish = function(context) { * @inheritDoc */ _ol_render_webgl_ImageReplay_.prototype.setImageStyle = function(imageStyle) { - var anchor = imageStyle.getAnchor(); - var image = imageStyle.getImage(1); - var imageSize = imageStyle.getImageSize(); - var hitDetectionImage = imageStyle.getHitDetectionImage(1); - var opacity = imageStyle.getOpacity(); - var origin = imageStyle.getOrigin(); - var rotateWithView = imageStyle.getRotateWithView(); - var rotation = imageStyle.getRotation(); - var size = imageStyle.getSize(); - var scale = imageStyle.getScale(); + const anchor = imageStyle.getAnchor(); + const image = imageStyle.getImage(1); + const imageSize = imageStyle.getImageSize(); + const hitDetectionImage = imageStyle.getHitDetectionImage(1); + const opacity = imageStyle.getOpacity(); + const origin = imageStyle.getOrigin(); + const rotateWithView = imageStyle.getRotateWithView(); + const rotation = imageStyle.getRotation(); + const size = imageStyle.getSize(); + const scale = imageStyle.getScale(); - var currentImage; + let currentImage; if (this.images_.length === 0) { this.images_.push(image); } else { diff --git a/src/ol/render/webgl/Immediate.js b/src/ol/render/webgl/Immediate.js index 8c80efae84..c984b0536c 100644 --- a/src/ol/render/webgl/Immediate.js +++ b/src/ol/render/webgl/Immediate.js @@ -20,7 +20,7 @@ import _ol_render_webgl_ReplayGroup_ from '../webgl/ReplayGroup.js'; * @param {number} pixelRatio Pixel ratio. * @struct */ -var _ol_render_webgl_Immediate_ = function(context, center, resolution, rotation, size, extent, pixelRatio) { +const _ol_render_webgl_Immediate_ = function(context, center, resolution, rotation, size, extent, pixelRatio) { VectorContext.call(this); /** @@ -93,20 +93,20 @@ inherits(_ol_render_webgl_Immediate_, VectorContext); * @private */ _ol_render_webgl_Immediate_.prototype.drawText_ = function(replayGroup, geometry) { - var context = this.context_; - var replay = /** @type {ol.render.webgl.TextReplay} */ ( + const context = this.context_; + const replay = /** @type {ol.render.webgl.TextReplay} */ ( replayGroup.getReplay(0, ReplayType.TEXT)); replay.setTextStyle(this.textStyle_); replay.drawText(geometry, null); replay.finish(context); // default colors - var opacity = 1; - var skippedFeatures = {}; - var featureCallback; - var oneByOne = false; + const opacity = 1; + const skippedFeatures = {}; + let featureCallback; + const oneByOne = false; replay.replay(this.context_, this.center_, this.resolution_, this.rotation_, - this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, - oneByOne); + this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, + oneByOne); replay.getDeleteResourcesFunction(context)(); }; @@ -135,7 +135,7 @@ _ol_render_webgl_Immediate_.prototype.setStyle = function(style) { * @api */ _ol_render_webgl_Immediate_.prototype.drawGeometry = function(geometry) { - var type = geometry.getType(); + const type = geometry.getType(); switch (type) { case GeometryType.POINT: this.drawPoint(/** @type {ol.geom.Point} */ (geometry), null); @@ -172,7 +172,7 @@ _ol_render_webgl_Immediate_.prototype.drawGeometry = function(geometry) { * @api */ _ol_render_webgl_Immediate_.prototype.drawFeature = function(feature, style) { - var geometry = style.getGeometryFunction()(feature); + const geometry = style.getGeometryFunction()(feature); if (!geometry || !intersects(this.extent_, geometry.getExtent())) { return; } @@ -185,8 +185,8 @@ _ol_render_webgl_Immediate_.prototype.drawFeature = function(feature, style) { * @inheritDoc */ _ol_render_webgl_Immediate_.prototype.drawGeometryCollection = function(geometry, data) { - var geometries = geometry.getGeometriesArray(); - var i, ii; + const geometries = geometry.getGeometriesArray(); + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { this.drawGeometry(geometries[i]); } @@ -197,21 +197,21 @@ _ol_render_webgl_Immediate_.prototype.drawGeometryCollection = function(geometry * @inheritDoc */ _ol_render_webgl_Immediate_.prototype.drawPoint = function(geometry, data) { - var context = this.context_; - var replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); - var replay = /** @type {ol.render.webgl.ImageReplay} */ ( + const context = this.context_; + const replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); + const replay = /** @type {ol.render.webgl.ImageReplay} */ ( replayGroup.getReplay(0, ReplayType.IMAGE)); replay.setImageStyle(this.imageStyle_); replay.drawPoint(geometry, data); replay.finish(context); // default colors - var opacity = 1; - var skippedFeatures = {}; - var featureCallback; - var oneByOne = false; + const opacity = 1; + const skippedFeatures = {}; + let featureCallback; + const oneByOne = false; replay.replay(this.context_, this.center_, this.resolution_, this.rotation_, - this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, - oneByOne); + this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, + oneByOne); replay.getDeleteResourcesFunction(context)(); if (this.textStyle_) { @@ -224,20 +224,20 @@ _ol_render_webgl_Immediate_.prototype.drawPoint = function(geometry, data) { * @inheritDoc */ _ol_render_webgl_Immediate_.prototype.drawMultiPoint = function(geometry, data) { - var context = this.context_; - var replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); - var replay = /** @type {ol.render.webgl.ImageReplay} */ ( + const context = this.context_; + const replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); + const replay = /** @type {ol.render.webgl.ImageReplay} */ ( replayGroup.getReplay(0, ReplayType.IMAGE)); replay.setImageStyle(this.imageStyle_); replay.drawMultiPoint(geometry, data); replay.finish(context); - var opacity = 1; - var skippedFeatures = {}; - var featureCallback; - var oneByOne = false; + const opacity = 1; + const skippedFeatures = {}; + let featureCallback; + const oneByOne = false; replay.replay(this.context_, this.center_, this.resolution_, this.rotation_, - this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, - oneByOne); + this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, + oneByOne); replay.getDeleteResourcesFunction(context)(); if (this.textStyle_) { @@ -250,20 +250,20 @@ _ol_render_webgl_Immediate_.prototype.drawMultiPoint = function(geometry, data) * @inheritDoc */ _ol_render_webgl_Immediate_.prototype.drawLineString = function(geometry, data) { - var context = this.context_; - var replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); - var replay = /** @type {ol.render.webgl.LineStringReplay} */ ( + const context = this.context_; + const replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); + const replay = /** @type {ol.render.webgl.LineStringReplay} */ ( replayGroup.getReplay(0, ReplayType.LINE_STRING)); replay.setFillStrokeStyle(null, this.strokeStyle_); replay.drawLineString(geometry, data); replay.finish(context); - var opacity = 1; - var skippedFeatures = {}; - var featureCallback; - var oneByOne = false; + const opacity = 1; + const skippedFeatures = {}; + let featureCallback; + const oneByOne = false; replay.replay(this.context_, this.center_, this.resolution_, this.rotation_, - this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, - oneByOne); + this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, + oneByOne); replay.getDeleteResourcesFunction(context)(); if (this.textStyle_) { @@ -276,20 +276,20 @@ _ol_render_webgl_Immediate_.prototype.drawLineString = function(geometry, data) * @inheritDoc */ _ol_render_webgl_Immediate_.prototype.drawMultiLineString = function(geometry, data) { - var context = this.context_; - var replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); - var replay = /** @type {ol.render.webgl.LineStringReplay} */ ( + const context = this.context_; + const replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); + const replay = /** @type {ol.render.webgl.LineStringReplay} */ ( replayGroup.getReplay(0, ReplayType.LINE_STRING)); replay.setFillStrokeStyle(null, this.strokeStyle_); replay.drawMultiLineString(geometry, data); replay.finish(context); - var opacity = 1; - var skippedFeatures = {}; - var featureCallback; - var oneByOne = false; + const opacity = 1; + const skippedFeatures = {}; + let featureCallback; + const oneByOne = false; replay.replay(this.context_, this.center_, this.resolution_, this.rotation_, - this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, - oneByOne); + this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, + oneByOne); replay.getDeleteResourcesFunction(context)(); if (this.textStyle_) { @@ -302,20 +302,20 @@ _ol_render_webgl_Immediate_.prototype.drawMultiLineString = function(geometry, d * @inheritDoc */ _ol_render_webgl_Immediate_.prototype.drawPolygon = function(geometry, data) { - var context = this.context_; - var replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); - var replay = /** @type {ol.render.webgl.PolygonReplay} */ ( + const context = this.context_; + const replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); + const replay = /** @type {ol.render.webgl.PolygonReplay} */ ( replayGroup.getReplay(0, ReplayType.POLYGON)); replay.setFillStrokeStyle(this.fillStyle_, this.strokeStyle_); replay.drawPolygon(geometry, data); replay.finish(context); - var opacity = 1; - var skippedFeatures = {}; - var featureCallback; - var oneByOne = false; + const opacity = 1; + const skippedFeatures = {}; + let featureCallback; + const oneByOne = false; replay.replay(this.context_, this.center_, this.resolution_, this.rotation_, - this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, - oneByOne); + this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, + oneByOne); replay.getDeleteResourcesFunction(context)(); if (this.textStyle_) { @@ -328,20 +328,20 @@ _ol_render_webgl_Immediate_.prototype.drawPolygon = function(geometry, data) { * @inheritDoc */ _ol_render_webgl_Immediate_.prototype.drawMultiPolygon = function(geometry, data) { - var context = this.context_; - var replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); - var replay = /** @type {ol.render.webgl.PolygonReplay} */ ( + const context = this.context_; + const replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); + const replay = /** @type {ol.render.webgl.PolygonReplay} */ ( replayGroup.getReplay(0, ReplayType.POLYGON)); replay.setFillStrokeStyle(this.fillStyle_, this.strokeStyle_); replay.drawMultiPolygon(geometry, data); replay.finish(context); - var opacity = 1; - var skippedFeatures = {}; - var featureCallback; - var oneByOne = false; + const opacity = 1; + const skippedFeatures = {}; + let featureCallback; + const oneByOne = false; replay.replay(this.context_, this.center_, this.resolution_, this.rotation_, - this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, - oneByOne); + this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, + oneByOne); replay.getDeleteResourcesFunction(context)(); if (this.textStyle_) { @@ -354,20 +354,20 @@ _ol_render_webgl_Immediate_.prototype.drawMultiPolygon = function(geometry, data * @inheritDoc */ _ol_render_webgl_Immediate_.prototype.drawCircle = function(geometry, data) { - var context = this.context_; - var replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); - var replay = /** @type {ol.render.webgl.CircleReplay} */ ( + const context = this.context_; + const replayGroup = new _ol_render_webgl_ReplayGroup_(1, this.extent_); + const replay = /** @type {ol.render.webgl.CircleReplay} */ ( replayGroup.getReplay(0, ReplayType.CIRCLE)); replay.setFillStrokeStyle(this.fillStyle_, this.strokeStyle_); replay.drawCircle(geometry, data); replay.finish(context); - var opacity = 1; - var skippedFeatures = {}; - var featureCallback; - var oneByOne = false; + const opacity = 1; + const skippedFeatures = {}; + let featureCallback; + const oneByOne = false; replay.replay(this.context_, this.center_, this.resolution_, this.rotation_, - this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, - oneByOne); + this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, + oneByOne); replay.getDeleteResourcesFunction(context)(); if (this.textStyle_) { diff --git a/src/ol/render/webgl/LineStringReplay.js b/src/ol/render/webgl/LineStringReplay.js index 604a3f3ca9..3088a970c0 100644 --- a/src/ol/render/webgl/LineStringReplay.js +++ b/src/ol/render/webgl/LineStringReplay.js @@ -23,7 +23,7 @@ import _ol_webgl_Buffer_ from '../../webgl/Buffer.js'; * @param {ol.Extent} maxExtent Max extent. * @struct */ -var _ol_render_webgl_LineStringReplay_ = function(tolerance, maxExtent) { +const _ol_render_webgl_LineStringReplay_ = function(tolerance, maxExtent) { _ol_render_webgl_Replay_.call(this, tolerance, maxExtent); /** @@ -81,22 +81,22 @@ inherits(_ol_render_webgl_LineStringReplay_, _ol_render_webgl_Replay_); */ _ol_render_webgl_LineStringReplay_.prototype.drawCoordinates_ = function(flatCoordinates, offset, end, stride) { - var i, ii; - var numVertices = this.vertices.length; - var numIndices = this.indices.length; + let i, ii; + let numVertices = this.vertices.length; + let numIndices = this.indices.length; //To save a vertex, the direction of a point is a product of the sign (1 or -1), a prime from //ol.render.webgl.LineStringReplay.Instruction_, and a rounding factor (1 or 2). If the product is even, //we round it. If it is odd, we don't. - var lineJoin = this.state_.lineJoin === 'bevel' ? 0 : + const lineJoin = this.state_.lineJoin === 'bevel' ? 0 : this.state_.lineJoin === 'miter' ? 1 : 2; - var lineCap = this.state_.lineCap === 'butt' ? 0 : + const lineCap = this.state_.lineCap === 'butt' ? 0 : this.state_.lineCap === 'square' ? 1 : 2; - var closed = _ol_geom_flat_topology_.lineStringIsClosed(flatCoordinates, offset, end, stride); - var startCoords, sign, n; - var lastIndex = numIndices; - var lastSign = 1; + const closed = _ol_geom_flat_topology_.lineStringIsClosed(flatCoordinates, offset, end, stride); + let startCoords, sign, n; + let lastIndex = numIndices; + let lastSign = 1; //We need the adjacent vertices to define normals in joins. p0 = last, p1 = current, p2 = next. - var p0, p1, p2; + let p0, p1, p2; for (i = offset, ii = end; i < ii; i += stride) { @@ -121,10 +121,10 @@ _ol_render_webgl_LineStringReplay_.prototype.drawCoordinates_ = function(flatCoo if (lineCap) { numVertices = this.addVertices_([0, 0], p1, p2, - lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.BEGIN_LINE_CAP * lineCap, numVertices); + lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.BEGIN_LINE_CAP * lineCap, numVertices); numVertices = this.addVertices_([0, 0], p1, p2, - -lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.BEGIN_LINE_CAP * lineCap, numVertices); + -lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.BEGIN_LINE_CAP * lineCap, numVertices); this.indices[numIndices++] = n + 2; this.indices[numIndices++] = n; @@ -137,10 +137,10 @@ _ol_render_webgl_LineStringReplay_.prototype.drawCoordinates_ = function(flatCoo } numVertices = this.addVertices_([0, 0], p1, p2, - lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.BEGIN_LINE * (lineCap || 1), numVertices); + lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.BEGIN_LINE * (lineCap || 1), numVertices); numVertices = this.addVertices_([0, 0], p1, p2, - -lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.BEGIN_LINE * (lineCap || 1), numVertices); + -lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.BEGIN_LINE * (lineCap || 1), numVertices); lastIndex = numVertices / 7 - 1; @@ -156,10 +156,10 @@ _ol_render_webgl_LineStringReplay_.prototype.drawCoordinates_ = function(flatCoo p0 = p0 || [0, 0]; numVertices = this.addVertices_(p0, p1, [0, 0], - lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.END_LINE * (lineCap || 1), numVertices); + lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.END_LINE * (lineCap || 1), numVertices); numVertices = this.addVertices_(p0, p1, [0, 0], - -lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.END_LINE * (lineCap || 1), numVertices); + -lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.END_LINE * (lineCap || 1), numVertices); this.indices[numIndices++] = n; this.indices[numIndices++] = lastIndex - 1; @@ -171,10 +171,10 @@ _ol_render_webgl_LineStringReplay_.prototype.drawCoordinates_ = function(flatCoo if (lineCap) { numVertices = this.addVertices_(p0, p1, [0, 0], - lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.END_LINE_CAP * lineCap, numVertices); + lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.END_LINE_CAP * lineCap, numVertices); numVertices = this.addVertices_(p0, p1, [0, 0], - -lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.END_LINE_CAP * lineCap, numVertices); + -lastSign * _ol_render_webgl_LineStringReplay_.Instruction_.END_LINE_CAP * lineCap, numVertices); this.indices[numIndices++] = n + 2; this.indices[numIndices++] = n; @@ -197,13 +197,13 @@ _ol_render_webgl_LineStringReplay_.prototype.drawCoordinates_ = function(flatCoo ? -1 : 1; numVertices = this.addVertices_(p0, p1, p2, - sign * _ol_render_webgl_LineStringReplay_.Instruction_.BEVEL_FIRST * (lineJoin || 1), numVertices); + sign * _ol_render_webgl_LineStringReplay_.Instruction_.BEVEL_FIRST * (lineJoin || 1), numVertices); numVertices = this.addVertices_(p0, p1, p2, - sign * _ol_render_webgl_LineStringReplay_.Instruction_.BEVEL_SECOND * (lineJoin || 1), numVertices); + sign * _ol_render_webgl_LineStringReplay_.Instruction_.BEVEL_SECOND * (lineJoin || 1), numVertices); numVertices = this.addVertices_(p0, p1, p2, - -sign * _ol_render_webgl_LineStringReplay_.Instruction_.MITER_BOTTOM * (lineJoin || 1), numVertices); + -sign * _ol_render_webgl_LineStringReplay_.Instruction_.MITER_BOTTOM * (lineJoin || 1), numVertices); if (i > offset) { this.indices[numIndices++] = n; @@ -225,7 +225,7 @@ _ol_render_webgl_LineStringReplay_.prototype.drawCoordinates_ = function(flatCoo //Add miter if (lineJoin) { numVertices = this.addVertices_(p0, p1, p2, - sign * _ol_render_webgl_LineStringReplay_.Instruction_.MITER_TOP * lineJoin, numVertices); + sign * _ol_render_webgl_LineStringReplay_.Instruction_.MITER_TOP * lineJoin, numVertices); this.indices[numIndices++] = n + 1; this.indices[numIndices++] = n + 3; @@ -239,10 +239,10 @@ _ol_render_webgl_LineStringReplay_.prototype.drawCoordinates_ = function(flatCoo ? 1 : -1; numVertices = this.addVertices_(p0, p1, p2, - sign * _ol_render_webgl_LineStringReplay_.Instruction_.BEVEL_FIRST * (lineJoin || 1), numVertices); + sign * _ol_render_webgl_LineStringReplay_.Instruction_.BEVEL_FIRST * (lineJoin || 1), numVertices); numVertices = this.addVertices_(p0, p1, p2, - -sign * _ol_render_webgl_LineStringReplay_.Instruction_.MITER_BOTTOM * (lineJoin || 1), numVertices); + -sign * _ol_render_webgl_LineStringReplay_.Instruction_.MITER_BOTTOM * (lineJoin || 1), numVertices); this.indices[numIndices++] = n; this.indices[numIndices++] = lastIndex - 1; @@ -285,12 +285,12 @@ _ol_render_webgl_LineStringReplay_.prototype.addVertices_ = function(p0, p1, p2, * @private */ _ol_render_webgl_LineStringReplay_.prototype.isValid_ = function(flatCoordinates, offset, end, stride) { - var range = end - offset; + const range = end - offset; if (range < stride * 2) { return false; } else if (range === stride * 2) { - var firstP = [flatCoordinates[offset], flatCoordinates[offset + 1]]; - var lastP = [flatCoordinates[offset + stride], flatCoordinates[offset + stride + 1]]; + const firstP = [flatCoordinates[offset], flatCoordinates[offset + 1]]; + const lastP = [flatCoordinates[offset + stride], flatCoordinates[offset + stride + 1]]; return !equals(firstP, lastP); } @@ -302,11 +302,11 @@ _ol_render_webgl_LineStringReplay_.prototype.isValid_ = function(flatCoordinates * @inheritDoc */ _ol_render_webgl_LineStringReplay_.prototype.drawLineString = function(lineStringGeometry, feature) { - var flatCoordinates = lineStringGeometry.getFlatCoordinates(); - var stride = lineStringGeometry.getStride(); + let flatCoordinates = lineStringGeometry.getFlatCoordinates(); + const stride = lineStringGeometry.getStride(); if (this.isValid_(flatCoordinates, 0, flatCoordinates.length, stride)) { flatCoordinates = _ol_geom_flat_transform_.translate(flatCoordinates, 0, flatCoordinates.length, - stride, -this.origin[0], -this.origin[1]); + stride, -this.origin[0], -this.origin[1]); if (this.state_.changed) { this.styleIndices_.push(this.indices.length); this.state_.changed = false; @@ -314,7 +314,7 @@ _ol_render_webgl_LineStringReplay_.prototype.drawLineString = function(lineStrin this.startIndices.push(this.indices.length); this.startIndicesFeature.push(feature); this.drawCoordinates_( - flatCoordinates, 0, flatCoordinates.length, stride); + flatCoordinates, 0, flatCoordinates.length, stride); } }; @@ -323,19 +323,19 @@ _ol_render_webgl_LineStringReplay_.prototype.drawLineString = function(lineStrin * @inheritDoc */ _ol_render_webgl_LineStringReplay_.prototype.drawMultiLineString = function(multiLineStringGeometry, feature) { - var indexCount = this.indices.length; - var ends = multiLineStringGeometry.getEnds(); + const indexCount = this.indices.length; + const ends = multiLineStringGeometry.getEnds(); ends.unshift(0); - var flatCoordinates = multiLineStringGeometry.getFlatCoordinates(); - var stride = multiLineStringGeometry.getStride(); - var i, ii; + const flatCoordinates = multiLineStringGeometry.getFlatCoordinates(); + const stride = multiLineStringGeometry.getStride(); + let i, ii; if (ends.length > 1) { for (i = 1, ii = ends.length; i < ii; ++i) { if (this.isValid_(flatCoordinates, ends[i - 1], ends[i], stride)) { - var lineString = _ol_geom_flat_transform_.translate(flatCoordinates, ends[i - 1], ends[i], - stride, -this.origin[0], -this.origin[1]); + const lineString = _ol_geom_flat_transform_.translate(flatCoordinates, ends[i - 1], ends[i], + stride, -this.origin[0], -this.origin[1]); this.drawCoordinates_( - lineString, 0, lineString.length, stride); + lineString, 0, lineString.length, stride); } } } @@ -356,23 +356,23 @@ _ol_render_webgl_LineStringReplay_.prototype.drawMultiLineString = function(mult * @param {number} stride Stride. */ _ol_render_webgl_LineStringReplay_.prototype.drawPolygonCoordinates = function( - flatCoordinates, holeFlatCoordinates, stride) { + flatCoordinates, holeFlatCoordinates, stride) { if (!_ol_geom_flat_topology_.lineStringIsClosed(flatCoordinates, 0, - flatCoordinates.length, stride)) { + flatCoordinates.length, stride)) { flatCoordinates.push(flatCoordinates[0]); flatCoordinates.push(flatCoordinates[1]); } this.drawCoordinates_(flatCoordinates, 0, flatCoordinates.length, stride); if (holeFlatCoordinates.length) { - var i, ii; + let i, ii; for (i = 0, ii = holeFlatCoordinates.length; i < ii; ++i) { if (!_ol_geom_flat_topology_.lineStringIsClosed(holeFlatCoordinates[i], 0, - holeFlatCoordinates[i].length, stride)) { + holeFlatCoordinates[i].length, stride)) { holeFlatCoordinates[i].push(holeFlatCoordinates[i][0]); holeFlatCoordinates[i].push(holeFlatCoordinates[i][1]); } this.drawCoordinates_(holeFlatCoordinates[i], 0, - holeFlatCoordinates[i].length, stride); + holeFlatCoordinates[i].length, stride); } } }; @@ -383,7 +383,7 @@ _ol_render_webgl_LineStringReplay_.prototype.drawPolygonCoordinates = function( * @param {number=} opt_index Index count. */ _ol_render_webgl_LineStringReplay_.prototype.setPolygonStyle = function(feature, opt_index) { - var index = opt_index === undefined ? this.indices.length : opt_index; + const index = opt_index === undefined ? this.indices.length : opt_index; this.startIndices.push(index); this.startIndicesFeature.push(feature); if (this.state_.changed) { @@ -427,8 +427,8 @@ _ol_render_webgl_LineStringReplay_.prototype.finish = function(context) { * @inheritDoc */ _ol_render_webgl_LineStringReplay_.prototype.getDeleteResourcesFunction = function(context) { - var verticesBuffer = this.verticesBuffer; - var indicesBuffer = this.indicesBuffer; + const verticesBuffer = this.verticesBuffer; + const indicesBuffer = this.indicesBuffer; return function() { context.deleteBuffer(verticesBuffer); context.deleteBuffer(indicesBuffer); @@ -441,13 +441,12 @@ _ol_render_webgl_LineStringReplay_.prototype.getDeleteResourcesFunction = functi */ _ol_render_webgl_LineStringReplay_.prototype.setUpProgram = function(gl, context, size, pixelRatio) { // get the program - var fragmentShader, vertexShader; - fragmentShader = _ol_render_webgl_linestringreplay_defaultshader_.fragment; - vertexShader = _ol_render_webgl_linestringreplay_defaultshader_.vertex; - var program = context.getProgram(fragmentShader, vertexShader); + const fragmentShader = _ol_render_webgl_linestringreplay_defaultshader_.fragment; + const vertexShader = _ol_render_webgl_linestringreplay_defaultshader_.vertex; + const program = context.getProgram(fragmentShader, vertexShader); // get the locations - var locations; + let locations; if (!this.defaultLocations_) { locations = new _ol_render_webgl_linestringreplay_defaultshader_Locations_(gl, program); this.defaultLocations_ = locations; @@ -460,19 +459,19 @@ _ol_render_webgl_LineStringReplay_.prototype.setUpProgram = function(gl, context // enable the vertex attrib arrays gl.enableVertexAttribArray(locations.a_lastPos); gl.vertexAttribPointer(locations.a_lastPos, 2, _ol_webgl_.FLOAT, - false, 28, 0); + false, 28, 0); gl.enableVertexAttribArray(locations.a_position); gl.vertexAttribPointer(locations.a_position, 2, _ol_webgl_.FLOAT, - false, 28, 8); + false, 28, 8); gl.enableVertexAttribArray(locations.a_nextPos); gl.vertexAttribPointer(locations.a_nextPos, 2, _ol_webgl_.FLOAT, - false, 28, 16); + false, 28, 16); gl.enableVertexAttribArray(locations.a_direction); gl.vertexAttribPointer(locations.a_direction, 1, _ol_webgl_.FLOAT, - false, 28, 24); + false, 28, 24); // Enable renderer specific uniforms. gl.uniform2fv(locations.u_size, size); @@ -498,8 +497,8 @@ _ol_render_webgl_LineStringReplay_.prototype.shutDownProgram = function(gl, loca */ _ol_render_webgl_LineStringReplay_.prototype.drawReplay = function(gl, context, skippedFeaturesHash, hitDetection) { //Save GL parameters. - var tmpDepthFunc = /** @type {number} */ (gl.getParameter(gl.DEPTH_FUNC)); - var tmpDepthMask = /** @type {boolean} */ (gl.getParameter(gl.DEPTH_WRITEMASK)); + const tmpDepthFunc = /** @type {number} */ (gl.getParameter(gl.DEPTH_FUNC)); + const tmpDepthMask = /** @type {boolean} */ (gl.getParameter(gl.DEPTH_WRITEMASK)); if (!hitDetection) { gl.enable(gl.DEPTH_TEST); @@ -511,7 +510,7 @@ _ol_render_webgl_LineStringReplay_.prototype.drawReplay = function(gl, context, this.drawReplaySkipping_(gl, context, skippedFeaturesHash); } else { //Draw by style groups to minimize drawElements() calls. - var i, start, end, nextStyle; + let i, start, end, nextStyle; end = this.startIndices[this.startIndices.length - 1]; for (i = this.styleIndices_.length - 1; i >= 0; --i) { start = this.styleIndices_[i]; @@ -539,7 +538,7 @@ _ol_render_webgl_LineStringReplay_.prototype.drawReplay = function(gl, context, * @param {Object} skippedFeaturesHash Ids of features to skip. */ _ol_render_webgl_LineStringReplay_.prototype.drawReplaySkipping_ = function(gl, context, skippedFeaturesHash) { - var i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex, featureStart; + let i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex, featureStart; featureIndex = this.startIndices.length - 2; end = start = this.startIndices[featureIndex + 1]; for (i = this.styleIndices_.length - 1; i >= 0; --i) { @@ -576,8 +575,8 @@ _ol_render_webgl_LineStringReplay_.prototype.drawReplaySkipping_ = function(gl, * @inheritDoc */ _ol_render_webgl_LineStringReplay_.prototype.drawHitDetectionReplayOneByOne = function(gl, context, skippedFeaturesHash, - featureCallback, opt_hitExtent) { - var i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex; + featureCallback, opt_hitExtent) { + let i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex; featureIndex = this.startIndices.length - 2; end = this.startIndices[featureIndex + 1]; for (i = this.styleIndices_.length - 1; i >= 0; --i) { @@ -594,12 +593,12 @@ _ol_render_webgl_LineStringReplay_.prototype.drawHitDetectionReplayOneByOne = fu if (skippedFeaturesHash[featureUid] === undefined && feature.getGeometry() && (opt_hitExtent === undefined || intersects( - /** @type {Array} */ (opt_hitExtent), - feature.getGeometry().getExtent()))) { + /** @type {Array} */ (opt_hitExtent), + feature.getGeometry().getExtent()))) { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); this.drawElements(gl, context, start, end); - var result = featureCallback(feature); + const result = featureCallback(feature); if (result) { return result; @@ -632,19 +631,19 @@ _ol_render_webgl_LineStringReplay_.prototype.setStrokeStyle_ = function(gl, colo * @inheritDoc */ _ol_render_webgl_LineStringReplay_.prototype.setFillStrokeStyle = function(fillStyle, strokeStyle) { - var strokeStyleLineCap = strokeStyle.getLineCap(); + const strokeStyleLineCap = strokeStyle.getLineCap(); this.state_.lineCap = strokeStyleLineCap !== undefined ? strokeStyleLineCap : _ol_render_webgl_.defaultLineCap; - var strokeStyleLineDash = strokeStyle.getLineDash(); + const strokeStyleLineDash = strokeStyle.getLineDash(); this.state_.lineDash = strokeStyleLineDash ? strokeStyleLineDash : _ol_render_webgl_.defaultLineDash; - var strokeStyleLineDashOffset = strokeStyle.getLineDashOffset(); + const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset(); this.state_.lineDashOffset = strokeStyleLineDashOffset ? strokeStyleLineDashOffset : _ol_render_webgl_.defaultLineDashOffset; - var strokeStyleLineJoin = strokeStyle.getLineJoin(); + const strokeStyleLineJoin = strokeStyle.getLineJoin(); this.state_.lineJoin = strokeStyleLineJoin !== undefined ? strokeStyleLineJoin : _ol_render_webgl_.defaultLineJoin; - var strokeStyleColor = strokeStyle.getColor(); + let strokeStyleColor = strokeStyle.getColor(); if (!(strokeStyleColor instanceof CanvasGradient) && !(strokeStyleColor instanceof CanvasPattern)) { strokeStyleColor = asArray(strokeStyleColor).map(function(c, i) { @@ -653,10 +652,10 @@ _ol_render_webgl_LineStringReplay_.prototype.setFillStrokeStyle = function(fillS } else { strokeStyleColor = _ol_render_webgl_.defaultStrokeStyle; } - var strokeStyleWidth = strokeStyle.getWidth(); + let strokeStyleWidth = strokeStyle.getWidth(); strokeStyleWidth = strokeStyleWidth !== undefined ? strokeStyleWidth : _ol_render_webgl_.defaultLineWidth; - var strokeStyleMiterLimit = strokeStyle.getMiterLimit(); + let strokeStyleMiterLimit = strokeStyle.getMiterLimit(); strokeStyleMiterLimit = strokeStyleMiterLimit !== undefined ? strokeStyleMiterLimit : _ol_render_webgl_.defaultMiterLimit; if (!this.state_.strokeColor || !equals(this.state_.strokeColor, strokeStyleColor) || diff --git a/src/ol/render/webgl/PolygonReplay.js b/src/ol/render/webgl/PolygonReplay.js index 8d3bfad1f9..6d969635ad 100644 --- a/src/ol/render/webgl/PolygonReplay.js +++ b/src/ol/render/webgl/PolygonReplay.js @@ -27,11 +27,11 @@ import _ol_webgl_Buffer_ from '../../webgl/Buffer.js'; * @param {ol.Extent} maxExtent Max extent. * @struct */ -var _ol_render_webgl_PolygonReplay_ = function(tolerance, maxExtent) { +const _ol_render_webgl_PolygonReplay_ = function(tolerance, maxExtent) { _ol_render_webgl_Replay_.call(this, tolerance, maxExtent); this.lineStringReplay = new _ol_render_webgl_LineStringReplay_( - tolerance, maxExtent); + tolerance, maxExtent); /** * @private @@ -74,27 +74,27 @@ inherits(_ol_render_webgl_PolygonReplay_, _ol_render_webgl_Replay_); * @private */ _ol_render_webgl_PolygonReplay_.prototype.drawCoordinates_ = function( - flatCoordinates, holeFlatCoordinates, stride) { + flatCoordinates, holeFlatCoordinates, stride) { // Triangulate the polygon - var outerRing = new LinkedList(); - var rtree = new RBush(); + const outerRing = new LinkedList(); + const rtree = new RBush(); // Initialize the outer ring this.processFlatCoordinates_(flatCoordinates, stride, outerRing, rtree, true); - var maxCoords = this.getMaxCoords_(outerRing); + const maxCoords = this.getMaxCoords_(outerRing); // Eliminate holes, if there are any if (holeFlatCoordinates.length) { - var i, ii; - var holeLists = []; + let i, ii; + const holeLists = []; for (i = 0, ii = holeFlatCoordinates.length; i < ii; ++i) { - var holeList = { + const holeList = { list: new LinkedList(), maxCoords: undefined, rtree: new RBush() }; holeLists.push(holeList); this.processFlatCoordinates_(holeFlatCoordinates[i], - stride, holeList.list, holeList.rtree, false); + stride, holeList.list, holeList.rtree, false); this.classifyPoints_(holeList.list, holeList.rtree, true); holeList.maxCoords = this.getMaxCoords_(holeList.list); } @@ -103,10 +103,10 @@ _ol_render_webgl_PolygonReplay_.prototype.drawCoordinates_ = function( a.maxCoords[1] - b.maxCoords[1] : b.maxCoords[0] - a.maxCoords[0]; }); for (i = 0; i < holeLists.length; ++i) { - var currList = holeLists[i].list; - var start = currList.firstItem(); - var currItem = start; - var intersection; + const currList = holeLists[i].list; + const start = currList.firstItem(); + let currItem = start; + let intersection; do { //TODO: Triangulate holes when they intersect the outer ring. if (this.getIntersections_(currItem, rtree).length) { @@ -139,19 +139,19 @@ _ol_render_webgl_PolygonReplay_.prototype.drawCoordinates_ = function( * @param {boolean} clockwise Coordinate order should be clockwise. */ _ol_render_webgl_PolygonReplay_.prototype.processFlatCoordinates_ = function( - flatCoordinates, stride, list, rtree, clockwise) { - var isClockwise = _ol_geom_flat_orient_.linearRingIsClockwise(flatCoordinates, - 0, flatCoordinates.length, stride); - var i, ii; - var n = this.vertices.length / 2; + flatCoordinates, stride, list, rtree, clockwise) { + const isClockwise = _ol_geom_flat_orient_.linearRingIsClockwise(flatCoordinates, + 0, flatCoordinates.length, stride); + let i, ii; + let n = this.vertices.length / 2; /** @type {ol.WebglPolygonVertex} */ - var start; + let start; /** @type {ol.WebglPolygonVertex} */ - var p0; + let p0; /** @type {ol.WebglPolygonVertex} */ - var p1; - var extents = []; - var segments = []; + let p1; + const extents = []; + const segments = []; if (clockwise === isClockwise) { start = this.createPoint_(flatCoordinates[0], flatCoordinates[1], n++); p0 = start; @@ -166,7 +166,7 @@ _ol_render_webgl_PolygonReplay_.prototype.processFlatCoordinates_ = function( extents.push([Math.min(p0.x, p1.x), Math.min(p0.y, p1.y), Math.max(p0.x, p1.x), Math.max(p0.y, p1.y)]); } else { - var end = flatCoordinates.length - stride; + const end = flatCoordinates.length - stride; start = this.createPoint_(flatCoordinates[end], flatCoordinates[end + 1], n++); p0 = start; for (i = end - stride, ii = 0; i >= ii; i -= stride) { @@ -191,9 +191,9 @@ _ol_render_webgl_PolygonReplay_.prototype.processFlatCoordinates_ = function( * @return {Array.} Max X coordinates. */ _ol_render_webgl_PolygonReplay_.prototype.getMaxCoords_ = function(list) { - var start = list.firstItem(); - var seg = start; - var maxCoords = [seg.p0.x, seg.p0.y]; + const start = list.firstItem(); + let seg = start; + let maxCoords = [seg.p0.x, seg.p0.y]; do { seg = list.nextItem(); @@ -215,15 +215,15 @@ _ol_render_webgl_PolygonReplay_.prototype.getMaxCoords_ = function(list) { * @return {boolean} There were reclassified points. */ _ol_render_webgl_PolygonReplay_.prototype.classifyPoints_ = function(list, rtree, ccw) { - var start = list.firstItem(); - var s0 = start; - var s1 = list.nextItem(); - var pointsReclassified = false; + let start = list.firstItem(); + let s0 = start; + let s1 = list.nextItem(); + let pointsReclassified = false; do { - var reflex = ccw ? _ol_render_webgl_.triangleIsCounterClockwise(s1.p1.x, - s1.p1.y, s0.p1.x, s0.p1.y, s0.p0.x, s0.p0.y) : + const reflex = ccw ? _ol_render_webgl_.triangleIsCounterClockwise(s1.p1.x, + s1.p1.y, s0.p1.x, s0.p1.y, s0.p0.x, s0.p0.y) : _ol_render_webgl_.triangleIsCounterClockwise(s0.p0.x, s0.p0.y, s0.p1.x, - s0.p1.y, s1.p1.x, s1.p1.y); + s0.p1.y, s1.p1.x, s1.p1.y); if (reflex === undefined) { this.removeItem_(s0, s1, list, rtree); pointsReclassified = true; @@ -253,28 +253,28 @@ _ol_render_webgl_PolygonReplay_.prototype.classifyPoints_ = function(list, rtree * @return {boolean} Bridging was successful. */ _ol_render_webgl_PolygonReplay_.prototype.bridgeHole_ = function(hole, holeMaxX, - list, listMaxX, rtree) { - var seg = hole.firstItem(); + list, listMaxX, rtree) { + let seg = hole.firstItem(); while (seg.p1.x !== holeMaxX) { seg = hole.nextItem(); } - var p1 = seg.p1; + const p1 = seg.p1; /** @type {ol.WebglPolygonVertex} */ - var p2 = {x: listMaxX, y: p1.y, i: -1}; - var minDist = Infinity; - var i, ii, bestPoint; + const p2 = {x: listMaxX, y: p1.y, i: -1}; + let minDist = Infinity; + let i, ii, bestPoint; /** @type {ol.WebglPolygonVertex} */ - var p5; + let p5; - var intersectingSegments = this.getIntersections_({p0: p1, p1: p2}, rtree, true); + const intersectingSegments = this.getIntersections_({p0: p1, p1: p2}, rtree, true); for (i = 0, ii = intersectingSegments.length; i < ii; ++i) { - var currSeg = intersectingSegments[i]; - var intersection = this.calculateIntersection_(p1, p2, currSeg.p0, - currSeg.p1, true); - var dist = Math.abs(p1.x - intersection[0]); + const currSeg = intersectingSegments[i]; + const intersection = this.calculateIntersection_(p1, p2, currSeg.p0, + currSeg.p1, true); + const dist = Math.abs(p1.x - intersection[0]); if (dist < minDist && _ol_render_webgl_.triangleIsCounterClockwise(p1.x, p1.y, - currSeg.p0.x, currSeg.p0.y, currSeg.p1.x, currSeg.p1.y) !== undefined) { + currSeg.p0.x, currSeg.p0.y, currSeg.p1.x, currSeg.p1.y) !== undefined) { minDist = dist; p5 = {x: intersection[0], y: intersection[1], i: -1}; seg = currSeg; @@ -286,12 +286,12 @@ _ol_render_webgl_PolygonReplay_.prototype.bridgeHole_ = function(hole, holeMaxX, bestPoint = seg.p1; if (minDist > 0) { - var pointsInTriangle = this.getPointsInTriangle_(p1, p5, seg.p1, rtree); + const pointsInTriangle = this.getPointsInTriangle_(p1, p5, seg.p1, rtree); if (pointsInTriangle.length) { - var theta = Infinity; + let theta = Infinity; for (i = 0, ii = pointsInTriangle.length; i < ii; ++i) { - var currPoint = pointsInTriangle[i]; - var currTheta = Math.atan2(p1.y - currPoint.y, p2.x - currPoint.x); + const currPoint = pointsInTriangle[i]; + const currTheta = Math.atan2(p1.y - currPoint.y, p2.x - currPoint.x); if (currTheta < theta || (currTheta === theta && currPoint.x < bestPoint.x)) { theta = currTheta; bestPoint = currPoint; @@ -306,8 +306,8 @@ _ol_render_webgl_PolygonReplay_.prototype.bridgeHole_ = function(hole, holeMaxX, } //We clone the bridge points as they can have different convexity. - var p0Bridge = {x: p1.x, y: p1.y, i: p1.i, reflex: undefined}; - var p1Bridge = {x: seg.p1.x, y: seg.p1.y, i: seg.p1.i, reflex: undefined}; + const p0Bridge = {x: p1.x, y: p1.y, i: p1.i, reflex: undefined}; + const p1Bridge = {x: seg.p1.x, y: seg.p1.y, i: seg.p1.i, reflex: undefined}; hole.getNextItem().p0 = p0Bridge; this.insertItem_(p1, seg.p1, hole, rtree); @@ -326,8 +326,8 @@ _ol_render_webgl_PolygonReplay_.prototype.bridgeHole_ = function(hole, holeMaxX, * @param {ol.structs.RBush} rtree R-Tree of the polygon. */ _ol_render_webgl_PolygonReplay_.prototype.triangulate_ = function(list, rtree) { - var ccw = false; - var simple = this.isSimple_(list, rtree); + let ccw = false; + let simple = this.isSimple_(list, rtree); // Start clipping ears while (list.getLength() > 3) { @@ -362,7 +362,7 @@ _ol_render_webgl_PolygonReplay_.prototype.triangulate_ = function(list, rtree) { } } if (list.getLength() === 3) { - var numIndices = this.indices.length; + let numIndices = this.indices.length; this.indices[numIndices++] = list.getPrevItem().p0.i; this.indices[numIndices++] = list.getCurrItem().p0.i; this.indices[numIndices++] = list.getNextItem().p0.i; @@ -379,26 +379,26 @@ _ol_render_webgl_PolygonReplay_.prototype.triangulate_ = function(list, rtree) { * @return {boolean} There were processed ears. */ _ol_render_webgl_PolygonReplay_.prototype.clipEars_ = function(list, rtree, simple, ccw) { - var numIndices = this.indices.length; - var start = list.firstItem(); - var s0 = list.getPrevItem(); - var s1 = start; - var s2 = list.nextItem(); - var s3 = list.getNextItem(); - var p0, p1, p2; - var processedEars = false; + let numIndices = this.indices.length; + let start = list.firstItem(); + let s0 = list.getPrevItem(); + let s1 = start; + let s2 = list.nextItem(); + let s3 = list.getNextItem(); + let p0, p1, p2; + let processedEars = false; do { p0 = s1.p0; p1 = s1.p1; p2 = s2.p1; if (p1.reflex === false) { // We might have a valid ear - var variableCriterion; + let variableCriterion; if (simple) { variableCriterion = this.getPointsInTriangle_(p0, p1, p2, rtree, true).length === 0; } else { variableCriterion = ccw ? this.diagonalIsInside_(s3.p1, p2, p1, p0, - s0.p0) : this.diagonalIsInside_(s0.p0, p0, p1, p2, s3.p1); + s0.p0) : this.diagonalIsInside_(s0.p0, p0, p1, p2, s3.p1); } if ((simple || this.getIntersections_({p0: p0, p1: p2}, rtree).length === 0) && variableCriterion) { @@ -437,26 +437,26 @@ _ol_render_webgl_PolygonReplay_.prototype.clipEars_ = function(list, rtree, simp * @return {boolean} There were resolved intersections. */ _ol_render_webgl_PolygonReplay_.prototype.resolveSelfIntersections_ = function( - list, rtree, opt_touch) { - var start = list.firstItem(); + list, rtree, opt_touch) { + const start = list.firstItem(); list.nextItem(); - var s0 = start; - var s1 = list.nextItem(); - var resolvedIntersections = false; + let s0 = start; + let s1 = list.nextItem(); + let resolvedIntersections = false; do { - var intersection = this.calculateIntersection_(s0.p0, s0.p1, s1.p0, s1.p1, - opt_touch); + const intersection = this.calculateIntersection_(s0.p0, s0.p1, s1.p0, s1.p1, + opt_touch); if (intersection) { - var breakCond = false; - var numVertices = this.vertices.length; - var numIndices = this.indices.length; - var n = numVertices / 2; - var seg = list.prevItem(); + let breakCond = false; + const numVertices = this.vertices.length; + let numIndices = this.indices.length; + const n = numVertices / 2; + const seg = list.prevItem(); list.removeItem(); rtree.remove(seg); breakCond = (seg === start); - var p; + let p; if (opt_touch) { if (intersection[0] === s0.p0.x && intersection[1] === s0.p0.y) { list.prevItem(); @@ -505,8 +505,8 @@ _ol_render_webgl_PolygonReplay_.prototype.resolveSelfIntersections_ = function( * @return {boolean} The polygon is simple. */ _ol_render_webgl_PolygonReplay_.prototype.isSimple_ = function(list, rtree) { - var start = list.firstItem(); - var seg = start; + const start = list.firstItem(); + let seg = start; do { if (this.getIntersections_(seg, rtree).length) { return false; @@ -523,11 +523,11 @@ _ol_render_webgl_PolygonReplay_.prototype.isSimple_ = function(list, rtree) { * @return {boolean} Orientation is clockwise. */ _ol_render_webgl_PolygonReplay_.prototype.isClockwise_ = function(list) { - var length = list.getLength() * 2; - var flatCoordinates = new Array(length); - var start = list.firstItem(); - var seg = start; - var i = 0; + const length = list.getLength() * 2; + const flatCoordinates = new Array(length); + const start = list.firstItem(); + let seg = start; + let i = 0; do { flatCoordinates[i++] = seg.p0.x; flatCoordinates[i++] = seg.p0.y; @@ -543,23 +543,23 @@ _ol_render_webgl_PolygonReplay_.prototype.isClockwise_ = function(list) { * @param {ol.structs.RBush} rtree R-Tree of the polygon. */ _ol_render_webgl_PolygonReplay_.prototype.splitPolygon_ = function(list, rtree) { - var start = list.firstItem(); - var s0 = start; + const start = list.firstItem(); + let s0 = start; do { - var intersections = this.getIntersections_(s0, rtree); + const intersections = this.getIntersections_(s0, rtree); if (intersections.length) { - var s1 = intersections[0]; - var n = this.vertices.length / 2; - var intersection = this.calculateIntersection_(s0.p0, - s0.p1, s1.p0, s1.p1); - var p = this.createPoint_(intersection[0], intersection[1], n); - var newPolygon = new LinkedList(); - var newRtree = new RBush(); + const s1 = intersections[0]; + const n = this.vertices.length / 2; + const intersection = this.calculateIntersection_(s0.p0, + s0.p1, s1.p0, s1.p1); + const p = this.createPoint_(intersection[0], intersection[1], n); + const newPolygon = new LinkedList(); + const newRtree = new RBush(); this.insertItem_(p, s0.p1, newPolygon, newRtree); s0.p1 = p; rtree.update([Math.min(s0.p0.x, p.x), Math.min(s0.p0.y, p.y), Math.max(s0.p0.x, p.x), Math.max(s0.p0.y, p.y)], s0); - var currItem = list.nextItem(); + let currItem = list.nextItem(); while (currItem !== s1) { this.insertItem_(currItem.p0, currItem.p1, newPolygon, newRtree); rtree.remove(currItem); @@ -589,11 +589,11 @@ _ol_render_webgl_PolygonReplay_.prototype.splitPolygon_ = function(list, rtree) * @return {ol.WebglPolygonVertex} List item. */ _ol_render_webgl_PolygonReplay_.prototype.createPoint_ = function(x, y, i) { - var numVertices = this.vertices.length; + let numVertices = this.vertices.length; this.vertices[numVertices++] = x; this.vertices[numVertices++] = y; /** @type {ol.WebglPolygonVertex} */ - var p = { + const p = { x: x, y: y, i: i, @@ -612,7 +612,7 @@ _ol_render_webgl_PolygonReplay_.prototype.createPoint_ = function(x, y, i) { * @return {ol.WebglPolygonSegment} segment. */ _ol_render_webgl_PolygonReplay_.prototype.insertItem_ = function(p0, p1, list, opt_rtree) { - var seg = { + const seg = { p0: p0, p1: p1 }; @@ -653,12 +653,12 @@ _ol_render_webgl_PolygonReplay_.prototype.removeItem_ = function(s0, s1, list, r * @return {Array.} Points in the triangle. */ _ol_render_webgl_PolygonReplay_.prototype.getPointsInTriangle_ = function(p0, p1, - p2, rtree, opt_reflex) { - var i, ii, j, p; - var result = []; - var segmentsInExtent = rtree.getInExtent([Math.min(p0.x, p1.x, p2.x), + p2, rtree, opt_reflex) { + let i, ii, j, p; + const result = []; + const segmentsInExtent = rtree.getInExtent([Math.min(p0.x, p1.x, p2.x), Math.min(p0.y, p1.y, p2.y), Math.max(p0.x, p1.x, p2.x), Math.max(p0.y, - p1.y, p2.y)]); + p1.y, p2.y)]); for (i = 0, ii = segmentsInExtent.length; i < ii; ++i) { for (j in segmentsInExtent[i]) { p = segmentsInExtent[i][j]; @@ -684,14 +684,14 @@ _ol_render_webgl_PolygonReplay_.prototype.getPointsInTriangle_ = function(p0, p1 * @return {Array.} Intersecting segments. */ _ol_render_webgl_PolygonReplay_.prototype.getIntersections_ = function(segment, rtree, opt_touch) { - var p0 = segment.p0; - var p1 = segment.p1; - var segmentsInExtent = rtree.getInExtent([Math.min(p0.x, p1.x), + const p0 = segment.p0; + const p1 = segment.p1; + const segmentsInExtent = rtree.getInExtent([Math.min(p0.x, p1.x), Math.min(p0.y, p1.y), Math.max(p0.x, p1.x), Math.max(p0.y, p1.y)]); - var result = []; - var i, ii; + const result = []; + let i, ii; for (i = 0, ii = segmentsInExtent.length; i < ii; ++i) { - var currSeg = segmentsInExtent[i]; + const currSeg = segmentsInExtent[i]; if (segment !== currSeg && (opt_touch || currSeg.p0 !== p1 || currSeg.p1 !== p0) && this.calculateIntersection_(p0, p1, currSeg.p0, currSeg.p1, opt_touch)) { result.push(currSeg); @@ -714,11 +714,11 @@ _ol_render_webgl_PolygonReplay_.prototype.getIntersections_ = function(segment, * @return {Array.|undefined} Intersection coordinates. */ _ol_render_webgl_PolygonReplay_.prototype.calculateIntersection_ = function(p0, - p1, p2, p3, opt_touch) { - var denom = (p3.y - p2.y) * (p1.x - p0.x) - (p3.x - p2.x) * (p1.y - p0.y); + p1, p2, p3, opt_touch) { + const denom = (p3.y - p2.y) * (p1.x - p0.x) - (p3.x - p2.x) * (p1.y - p0.y); if (denom !== 0) { - var ua = ((p3.x - p2.x) * (p0.y - p2.y) - (p3.y - p2.y) * (p0.x - p2.x)) / denom; - var ub = ((p1.x - p0.x) * (p0.y - p2.y) - (p1.y - p0.y) * (p0.x - p2.x)) / denom; + const ua = ((p3.x - p2.x) * (p0.y - p2.y) - (p3.y - p2.y) * (p0.x - p2.x)) / denom; + const ub = ((p1.x - p0.x) * (p0.y - p2.y) - (p1.y - p0.y) * (p0.x - p2.x)) / denom; if ((!opt_touch && ua > _ol_render_webgl_.EPSILON && ua < 1 - _ol_render_webgl_.EPSILON && ub > _ol_render_webgl_.EPSILON && ub < 1 - _ol_render_webgl_.EPSILON) || (opt_touch && ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1)) { @@ -742,12 +742,12 @@ _ol_render_webgl_PolygonReplay_.prototype.diagonalIsInside_ = function(p0, p1, p if (p1.reflex === undefined || p3.reflex === undefined) { return false; } - var p1IsLeftOf = (p2.x - p3.x) * (p1.y - p3.y) > (p2.y - p3.y) * (p1.x - p3.x); - var p1IsRightOf = (p4.x - p3.x) * (p1.y - p3.y) < (p4.y - p3.y) * (p1.x - p3.x); - var p3IsLeftOf = (p0.x - p1.x) * (p3.y - p1.y) > (p0.y - p1.y) * (p3.x - p1.x); - var p3IsRightOf = (p2.x - p1.x) * (p3.y - p1.y) < (p2.y - p1.y) * (p3.x - p1.x); - var p1InCone = p3.reflex ? p1IsRightOf || p1IsLeftOf : p1IsRightOf && p1IsLeftOf; - var p3InCone = p1.reflex ? p3IsRightOf || p3IsLeftOf : p3IsRightOf && p3IsLeftOf; + const p1IsLeftOf = (p2.x - p3.x) * (p1.y - p3.y) > (p2.y - p3.y) * (p1.x - p3.x); + const p1IsRightOf = (p4.x - p3.x) * (p1.y - p3.y) < (p4.y - p3.y) * (p1.x - p3.x); + const p3IsLeftOf = (p0.x - p1.x) * (p3.y - p1.y) > (p0.y - p1.y) * (p3.x - p1.x); + const p3IsRightOf = (p2.x - p1.x) * (p3.y - p1.y) < (p2.y - p1.y) * (p3.x - p1.x); + const p1InCone = p3.reflex ? p1IsRightOf || p1IsLeftOf : p1IsRightOf && p1IsLeftOf; + const p3InCone = p1.reflex ? p3IsRightOf || p3IsLeftOf : p3IsRightOf && p3IsLeftOf; return p1InCone && p3InCone; }; @@ -756,25 +756,25 @@ _ol_render_webgl_PolygonReplay_.prototype.diagonalIsInside_ = function(p0, p1, p * @inheritDoc */ _ol_render_webgl_PolygonReplay_.prototype.drawMultiPolygon = function(multiPolygonGeometry, feature) { - var endss = multiPolygonGeometry.getEndss(); - var stride = multiPolygonGeometry.getStride(); - var currIndex = this.indices.length; - var currLineIndex = this.lineStringReplay.getCurrentIndex(); - var flatCoordinates = multiPolygonGeometry.getFlatCoordinates(); - var i, ii, j, jj; - var start = 0; + const endss = multiPolygonGeometry.getEndss(); + const stride = multiPolygonGeometry.getStride(); + const currIndex = this.indices.length; + const currLineIndex = this.lineStringReplay.getCurrentIndex(); + const flatCoordinates = multiPolygonGeometry.getFlatCoordinates(); + let i, ii, j, jj; + let start = 0; for (i = 0, ii = endss.length; i < ii; ++i) { - var ends = endss[i]; + const ends = endss[i]; if (ends.length > 0) { - var outerRing = _ol_geom_flat_transform_.translate(flatCoordinates, start, ends[0], - stride, -this.origin[0], -this.origin[1]); + const outerRing = _ol_geom_flat_transform_.translate(flatCoordinates, start, ends[0], + stride, -this.origin[0], -this.origin[1]); if (outerRing.length) { - var holes = []; - var holeFlatCoords; + const holes = []; + let holeFlatCoords; for (j = 1, jj = ends.length; j < jj; ++j) { if (ends[j] !== ends[j - 1]) { holeFlatCoords = _ol_geom_flat_transform_.translate(flatCoordinates, ends[j - 1], - ends[j], stride, -this.origin[0], -this.origin[1]); + ends[j], stride, -this.origin[0], -this.origin[1]); holes.push(holeFlatCoords); } } @@ -802,19 +802,19 @@ _ol_render_webgl_PolygonReplay_.prototype.drawMultiPolygon = function(multiPolyg * @inheritDoc */ _ol_render_webgl_PolygonReplay_.prototype.drawPolygon = function(polygonGeometry, feature) { - var ends = polygonGeometry.getEnds(); - var stride = polygonGeometry.getStride(); + const ends = polygonGeometry.getEnds(); + const stride = polygonGeometry.getStride(); if (ends.length > 0) { - var flatCoordinates = polygonGeometry.getFlatCoordinates().map(Number); - var outerRing = _ol_geom_flat_transform_.translate(flatCoordinates, 0, ends[0], - stride, -this.origin[0], -this.origin[1]); + const flatCoordinates = polygonGeometry.getFlatCoordinates().map(Number); + const outerRing = _ol_geom_flat_transform_.translate(flatCoordinates, 0, ends[0], + stride, -this.origin[0], -this.origin[1]); if (outerRing.length) { - var holes = []; - var i, ii, holeFlatCoords; + const holes = []; + let i, ii, holeFlatCoords; for (i = 1, ii = ends.length; i < ii; ++i) { if (ends[i] !== ends[i - 1]) { holeFlatCoords = _ol_geom_flat_transform_.translate(flatCoordinates, ends[i - 1], - ends[i], stride, -this.origin[0], -this.origin[1]); + ends[i], stride, -this.origin[0], -this.origin[1]); holes.push(holeFlatCoords); } } @@ -862,9 +862,9 @@ _ol_render_webgl_PolygonReplay_.prototype.finish = function(context) { * @inheritDoc */ _ol_render_webgl_PolygonReplay_.prototype.getDeleteResourcesFunction = function(context) { - var verticesBuffer = this.verticesBuffer; - var indicesBuffer = this.indicesBuffer; - var lineDeleter = this.lineStringReplay.getDeleteResourcesFunction(context); + const verticesBuffer = this.verticesBuffer; + const indicesBuffer = this.indicesBuffer; + const lineDeleter = this.lineStringReplay.getDeleteResourcesFunction(context); return function() { context.deleteBuffer(verticesBuffer); context.deleteBuffer(indicesBuffer); @@ -878,13 +878,12 @@ _ol_render_webgl_PolygonReplay_.prototype.getDeleteResourcesFunction = function( */ _ol_render_webgl_PolygonReplay_.prototype.setUpProgram = function(gl, context, size, pixelRatio) { // get the program - var fragmentShader, vertexShader; - fragmentShader = _ol_render_webgl_polygonreplay_defaultshader_.fragment; - vertexShader = _ol_render_webgl_polygonreplay_defaultshader_.vertex; - var program = context.getProgram(fragmentShader, vertexShader); + const fragmentShader = _ol_render_webgl_polygonreplay_defaultshader_.fragment; + const vertexShader = _ol_render_webgl_polygonreplay_defaultshader_.vertex; + const program = context.getProgram(fragmentShader, vertexShader); // get the locations - var locations; + let locations; if (!this.defaultLocations_) { locations = new _ol_render_webgl_polygonreplay_defaultshader_Locations_(gl, program); this.defaultLocations_ = locations; @@ -897,7 +896,7 @@ _ol_render_webgl_PolygonReplay_.prototype.setUpProgram = function(gl, context, s // enable the vertex attrib arrays gl.enableVertexAttribArray(locations.a_position); gl.vertexAttribPointer(locations.a_position, 2, _ol_webgl_.FLOAT, - false, 8, 0); + false, 8, 0); return locations; }; @@ -916,8 +915,8 @@ _ol_render_webgl_PolygonReplay_.prototype.shutDownProgram = function(gl, locatio */ _ol_render_webgl_PolygonReplay_.prototype.drawReplay = function(gl, context, skippedFeaturesHash, hitDetection) { //Save GL parameters. - var tmpDepthFunc = /** @type {number} */ (gl.getParameter(gl.DEPTH_FUNC)); - var tmpDepthMask = /** @type {boolean} */ (gl.getParameter(gl.DEPTH_WRITEMASK)); + const tmpDepthFunc = /** @type {number} */ (gl.getParameter(gl.DEPTH_FUNC)); + const tmpDepthMask = /** @type {boolean} */ (gl.getParameter(gl.DEPTH_WRITEMASK)); if (!hitDetection) { gl.enable(gl.DEPTH_TEST); @@ -929,7 +928,7 @@ _ol_render_webgl_PolygonReplay_.prototype.drawReplay = function(gl, context, ski this.drawReplaySkipping_(gl, context, skippedFeaturesHash); } else { //Draw by style groups to minimize drawElements() calls. - var i, start, end, nextStyle; + let i, start, end, nextStyle; end = this.startIndices[this.startIndices.length - 1]; for (i = this.styleIndices_.length - 1; i >= 0; --i) { start = this.styleIndices_[i]; @@ -953,8 +952,8 @@ _ol_render_webgl_PolygonReplay_.prototype.drawReplay = function(gl, context, ski * @inheritDoc */ _ol_render_webgl_PolygonReplay_.prototype.drawHitDetectionReplayOneByOne = function(gl, context, skippedFeaturesHash, - featureCallback, opt_hitExtent) { - var i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex; + featureCallback, opt_hitExtent) { + let i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex; featureIndex = this.startIndices.length - 2; end = this.startIndices[featureIndex + 1]; for (i = this.styleIndices_.length - 1; i >= 0; --i) { @@ -971,12 +970,12 @@ _ol_render_webgl_PolygonReplay_.prototype.drawHitDetectionReplayOneByOne = funct if (skippedFeaturesHash[featureUid] === undefined && feature.getGeometry() && (opt_hitExtent === undefined || intersects( - /** @type {Array} */ (opt_hitExtent), - feature.getGeometry().getExtent()))) { + /** @type {Array} */ (opt_hitExtent), + feature.getGeometry().getExtent()))) { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); this.drawElements(gl, context, start, end); - var result = featureCallback(feature); + const result = featureCallback(feature); if (result) { return result; @@ -998,7 +997,7 @@ _ol_render_webgl_PolygonReplay_.prototype.drawHitDetectionReplayOneByOne = funct * @param {Object} skippedFeaturesHash Ids of features to skip. */ _ol_render_webgl_PolygonReplay_.prototype.drawReplaySkipping_ = function(gl, context, skippedFeaturesHash) { - var i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex, featureStart; + let i, start, end, nextStyle, groupStart, feature, featureUid, featureIndex, featureStart; featureIndex = this.startIndices.length - 2; end = start = this.startIndices[featureIndex + 1]; for (i = this.styleIndices_.length - 1; i >= 0; --i) { @@ -1045,7 +1044,7 @@ _ol_render_webgl_PolygonReplay_.prototype.setFillStyle_ = function(gl, color) { * @inheritDoc */ _ol_render_webgl_PolygonReplay_.prototype.setFillStrokeStyle = function(fillStyle, strokeStyle) { - var fillStyleColor = fillStyle ? fillStyle.getColor() : [0, 0, 0, 0]; + let fillStyleColor = fillStyle ? fillStyle.getColor() : [0, 0, 0, 0]; if (!(fillStyleColor instanceof CanvasGradient) && !(fillStyleColor instanceof CanvasPattern)) { fillStyleColor = asArray(fillStyleColor).map(function(c, i) { @@ -1063,7 +1062,7 @@ _ol_render_webgl_PolygonReplay_.prototype.setFillStrokeStyle = function(fillStyl if (strokeStyle) { this.lineStringReplay.setFillStrokeStyle(null, strokeStyle); } else { - var nullStrokeStyle = new Stroke({ + const nullStrokeStyle = new Stroke({ color: [0, 0, 0, 0], lineWidth: 0 }); diff --git a/src/ol/render/webgl/Replay.js b/src/ol/render/webgl/Replay.js index 2f985a925a..bbf76f6ad3 100644 --- a/src/ol/render/webgl/Replay.js +++ b/src/ol/render/webgl/Replay.js @@ -16,7 +16,7 @@ import _ol_webgl_ from '../../webgl.js'; * @param {ol.Extent} maxExtent Max extent. * @struct */ -var _ol_render_webgl_Replay_ = function(tolerance, maxExtent) { +const _ol_render_webgl_Replay_ = function(tolerance, maxExtent) { VectorContext.call(this); /** @@ -200,15 +200,15 @@ _ol_render_webgl_Replay_.prototype.drawHitDetectionReplayOneByOne = function(gl, * @template T */ _ol_render_webgl_Replay_.prototype.drawHitDetectionReplay = function(gl, context, skippedFeaturesHash, - featureCallback, oneByOne, opt_hitExtent) { + featureCallback, oneByOne, opt_hitExtent) { if (!oneByOne) { // draw all hit-detection features in "once" (by texture group) return this.drawHitDetectionReplayAll(gl, context, - skippedFeaturesHash, featureCallback); + skippedFeaturesHash, featureCallback); } else { // draw hit-detection features one by one return this.drawHitDetectionReplayOneByOne(gl, context, - skippedFeaturesHash, featureCallback, opt_hitExtent); + skippedFeaturesHash, featureCallback, opt_hitExtent); } }; @@ -224,11 +224,11 @@ _ol_render_webgl_Replay_.prototype.drawHitDetectionReplay = function(gl, context * @template T */ _ol_render_webgl_Replay_.prototype.drawHitDetectionReplayAll = function(gl, context, skippedFeaturesHash, - featureCallback) { + featureCallback) { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); this.drawReplay(gl, context, skippedFeaturesHash, true); - var result = featureCallback(null); + const result = featureCallback(null); if (result) { return result; } else { @@ -255,11 +255,11 @@ _ol_render_webgl_Replay_.prototype.drawHitDetectionReplayAll = function(gl, cont * @template T */ _ol_render_webgl_Replay_.prototype.replay = function(context, - center, resolution, rotation, size, pixelRatio, - opacity, skippedFeaturesHash, - featureCallback, oneByOne, opt_hitExtent) { - var gl = context.getGL(); - var tmpStencil, tmpStencilFunc, tmpStencilMaskVal, tmpStencilRef, tmpStencilMask, + center, resolution, rotation, size, pixelRatio, + opacity, skippedFeaturesHash, + featureCallback, oneByOne, opt_hitExtent) { + const gl = context.getGL(); + let tmpStencil, tmpStencilFunc, tmpStencilMaskVal, tmpStencilRef, tmpStencilMask, tmpStencilOpFail, tmpStencilOpPass, tmpStencilOpZFail; if (this.lineStringReplay) { @@ -279,9 +279,9 @@ _ol_render_webgl_Replay_.prototype.replay = function(context, gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE); this.lineStringReplay.replay(context, - center, resolution, rotation, size, pixelRatio, - opacity, skippedFeaturesHash, - featureCallback, oneByOne, opt_hitExtent); + center, resolution, rotation, size, pixelRatio, + opacity, skippedFeaturesHash, + featureCallback, oneByOne, opt_hitExtent); gl.stencilMask(0); gl.stencilFunc(gl.NOTEQUAL, 1, 255); @@ -291,38 +291,38 @@ _ol_render_webgl_Replay_.prototype.replay = function(context, context.bindBuffer(_ol_webgl_.ELEMENT_ARRAY_BUFFER, this.indicesBuffer); - var locations = this.setUpProgram(gl, context, size, pixelRatio); + const locations = this.setUpProgram(gl, context, size, pixelRatio); // set the "uniform" values - var projectionMatrix = _ol_transform_.reset(this.projectionMatrix_); + const projectionMatrix = _ol_transform_.reset(this.projectionMatrix_); _ol_transform_.scale(projectionMatrix, 2 / (resolution * size[0]), 2 / (resolution * size[1])); _ol_transform_.rotate(projectionMatrix, -rotation); _ol_transform_.translate(projectionMatrix, -(center[0] - this.origin[0]), -(center[1] - this.origin[1])); - var offsetScaleMatrix = _ol_transform_.reset(this.offsetScaleMatrix_); + const offsetScaleMatrix = _ol_transform_.reset(this.offsetScaleMatrix_); _ol_transform_.scale(offsetScaleMatrix, 2 / size[0], 2 / size[1]); - var offsetRotateMatrix = _ol_transform_.reset(this.offsetRotateMatrix_); + const offsetRotateMatrix = _ol_transform_.reset(this.offsetRotateMatrix_); if (rotation !== 0) { _ol_transform_.rotate(offsetRotateMatrix, -rotation); } gl.uniformMatrix4fv(locations.u_projectionMatrix, false, - fromTransform(this.tmpMat4_, projectionMatrix)); + fromTransform(this.tmpMat4_, projectionMatrix)); gl.uniformMatrix4fv(locations.u_offsetScaleMatrix, false, - fromTransform(this.tmpMat4_, offsetScaleMatrix)); + fromTransform(this.tmpMat4_, offsetScaleMatrix)); gl.uniformMatrix4fv(locations.u_offsetRotateMatrix, false, - fromTransform(this.tmpMat4_, offsetRotateMatrix)); + fromTransform(this.tmpMat4_, offsetRotateMatrix)); gl.uniform1f(locations.u_opacity, opacity); // draw! - var result; + let result; if (featureCallback === undefined) { this.drawReplay(gl, context, skippedFeaturesHash, false); } else { // draw feature by feature for the hit-detection result = this.drawHitDetectionReplay(gl, context, skippedFeaturesHash, - featureCallback, oneByOne, opt_hitExtent); + featureCallback, oneByOne, opt_hitExtent); } // disable the vertex attrib arrays @@ -334,10 +334,10 @@ _ol_render_webgl_Replay_.prototype.replay = function(context, } gl.clear(gl.STENCIL_BUFFER_BIT); gl.stencilFunc(/** @type {number} */ (tmpStencilFunc), - /** @type {number} */ (tmpStencilRef), /** @type {number} */ (tmpStencilMaskVal)); + /** @type {number} */ (tmpStencilRef), /** @type {number} */ (tmpStencilMaskVal)); gl.stencilMask(/** @type {number} */ (tmpStencilMask)); gl.stencilOp(/** @type {number} */ (tmpStencilOpFail), - /** @type {number} */ (tmpStencilOpZFail), /** @type {number} */ (tmpStencilOpPass)); + /** @type {number} */ (tmpStencilOpZFail), /** @type {number} */ (tmpStencilOpPass)); } return result; @@ -351,13 +351,13 @@ _ol_render_webgl_Replay_.prototype.replay = function(context, * @param {number} end End index. */ _ol_render_webgl_Replay_.prototype.drawElements = function( - gl, context, start, end) { - var elementType = context.hasOESElementIndexUint ? + gl, context, start, end) { + const elementType = context.hasOESElementIndexUint ? _ol_webgl_.UNSIGNED_INT : _ol_webgl_.UNSIGNED_SHORT; - var elementSize = context.hasOESElementIndexUint ? 4 : 2; + const elementSize = context.hasOESElementIndexUint ? 4 : 2; - var numItems = end - start; - var offsetInBytes = start * elementSize; + const numItems = end - start; + const offsetInBytes = start * elementSize; gl.drawElements(_ol_webgl_.TRIANGLES, numItems, elementType, offsetInBytes); }; export default _ol_render_webgl_Replay_; diff --git a/src/ol/render/webgl/ReplayGroup.js b/src/ol/render/webgl/ReplayGroup.js index e14048ffdd..45978a46ae 100644 --- a/src/ol/render/webgl/ReplayGroup.js +++ b/src/ol/render/webgl/ReplayGroup.js @@ -21,7 +21,7 @@ import _ol_render_webgl_TextReplay_ from '../webgl/TextReplay.js'; * @param {number=} opt_renderBuffer Render buffer. * @struct */ -var _ol_render_webgl_ReplayGroup_ = function(tolerance, maxExtent, opt_renderBuffer) { +const _ol_render_webgl_ReplayGroup_ = function(tolerance, maxExtent, opt_renderBuffer) { _ol_render_ReplayGroup_.call(this); /** @@ -66,20 +66,19 @@ _ol_render_webgl_ReplayGroup_.prototype.addDeclutter = function(style, group) {} * @return {function()} Delete resources function. */ _ol_render_webgl_ReplayGroup_.prototype.getDeleteResourcesFunction = function(context) { - var functions = []; - var zKey; + const functions = []; + let zKey; for (zKey in this.replaysByZIndex_) { - var replays = this.replaysByZIndex_[zKey]; - var replayKey; - for (replayKey in replays) { + const replays = this.replaysByZIndex_[zKey]; + for (const replayKey in replays) { functions.push( - replays[replayKey].getDeleteResourcesFunction(context)); + replays[replayKey].getDeleteResourcesFunction(context)); } } return function() { - var length = functions.length; - var result; - for (var i = 0; i < length; i++) { + const length = functions.length; + let result; + for (let i = 0; i < length; i++) { result = functions[i].apply(this, arguments); } return result; @@ -91,11 +90,10 @@ _ol_render_webgl_ReplayGroup_.prototype.getDeleteResourcesFunction = function(co * @param {ol.webgl.Context} context Context. */ _ol_render_webgl_ReplayGroup_.prototype.finish = function(context) { - var zKey; + let zKey; for (zKey in this.replaysByZIndex_) { - var replays = this.replaysByZIndex_[zKey]; - var replayKey; - for (replayKey in replays) { + const replays = this.replaysByZIndex_[zKey]; + for (const replayKey in replays) { replays[replayKey].finish(context); } } @@ -106,18 +104,18 @@ _ol_render_webgl_ReplayGroup_.prototype.finish = function(context) { * @inheritDoc */ _ol_render_webgl_ReplayGroup_.prototype.getReplay = function(zIndex, replayType) { - var zIndexKey = zIndex !== undefined ? zIndex.toString() : '0'; - var replays = this.replaysByZIndex_[zIndexKey]; + const zIndexKey = zIndex !== undefined ? zIndex.toString() : '0'; + let replays = this.replaysByZIndex_[zIndexKey]; if (replays === undefined) { replays = {}; this.replaysByZIndex_[zIndexKey] = replays; } - var replay = replays[replayType]; + let replay = replays[replayType]; if (replay === undefined) { /** * @type {Function} */ - var Constructor = _ol_render_webgl_ReplayGroup_.BATCH_CONSTRUCTORS_[replayType]; + const Constructor = _ol_render_webgl_ReplayGroup_.BATCH_CONSTRUCTORS_[replayType]; replay = new Constructor(this.tolerance_, this.maxExtent_); replays[replayType] = replay; } @@ -145,22 +143,22 @@ _ol_render_webgl_ReplayGroup_.prototype.isEmpty = function() { * to skip. */ _ol_render_webgl_ReplayGroup_.prototype.replay = function(context, - center, resolution, rotation, size, pixelRatio, - opacity, skippedFeaturesHash) { + center, resolution, rotation, size, pixelRatio, + opacity, skippedFeaturesHash) { /** @type {Array.} */ - var zs = Object.keys(this.replaysByZIndex_).map(Number); + const zs = Object.keys(this.replaysByZIndex_).map(Number); zs.sort(numberSafeCompareFunction); - var i, ii, j, jj, replays, replay; + let i, ii, j, jj, replays, replay; for (i = 0, ii = zs.length; i < ii; ++i) { replays = this.replaysByZIndex_[zs[i].toString()]; for (j = 0, jj = _ol_render_replay_.ORDER.length; j < jj; ++j) { replay = replays[_ol_render_replay_.ORDER[j]]; if (replay !== undefined) { replay.replay(context, - center, resolution, rotation, size, pixelRatio, - opacity, skippedFeaturesHash, - undefined, false); + center, resolution, rotation, size, pixelRatio, + opacity, skippedFeaturesHash, + undefined, false); } } } @@ -186,23 +184,23 @@ _ol_render_webgl_ReplayGroup_.prototype.replay = function(context, * @template T */ _ol_render_webgl_ReplayGroup_.prototype.replayHitDetection_ = function(context, - center, resolution, rotation, size, pixelRatio, opacity, - skippedFeaturesHash, featureCallback, oneByOne, opt_hitExtent) { + center, resolution, rotation, size, pixelRatio, opacity, + skippedFeaturesHash, featureCallback, oneByOne, opt_hitExtent) { /** @type {Array.} */ - var zs = Object.keys(this.replaysByZIndex_).map(Number); + const zs = Object.keys(this.replaysByZIndex_).map(Number); zs.sort(function(a, b) { return b - a; }); - var i, ii, j, replays, replay, result; + let i, ii, j, replays, replay, result; for (i = 0, ii = zs.length; i < ii; ++i) { replays = this.replaysByZIndex_[zs[i].toString()]; for (j = _ol_render_replay_.ORDER.length - 1; j >= 0; --j) { replay = replays[_ol_render_replay_.ORDER[j]]; if (replay !== undefined) { result = replay.replay(context, - center, resolution, rotation, size, pixelRatio, opacity, - skippedFeaturesHash, featureCallback, oneByOne, opt_hitExtent); + center, resolution, rotation, size, pixelRatio, opacity, + skippedFeaturesHash, featureCallback, oneByOne, opt_hitExtent); if (result) { return result; } @@ -229,18 +227,18 @@ _ol_render_webgl_ReplayGroup_.prototype.replayHitDetection_ = function(context, * @template T */ _ol_render_webgl_ReplayGroup_.prototype.forEachFeatureAtCoordinate = function( - coordinate, context, center, resolution, rotation, size, pixelRatio, - opacity, skippedFeaturesHash, - callback) { - var gl = context.getGL(); + coordinate, context, center, resolution, rotation, size, pixelRatio, + opacity, skippedFeaturesHash, + callback) { + const gl = context.getGL(); gl.bindFramebuffer( - gl.FRAMEBUFFER, context.getHitDetectionFramebuffer()); + gl.FRAMEBUFFER, context.getHitDetectionFramebuffer()); /** * @type {ol.Extent} */ - var hitExtent; + let hitExtent; if (this.renderBuffer_ !== undefined) { // build an extent around the coordinate, so that only features that // intersect this extent are checked @@ -248,23 +246,23 @@ _ol_render_webgl_ReplayGroup_.prototype.forEachFeatureAtCoordinate = function( } return this.replayHitDetection_(context, - coordinate, resolution, rotation, _ol_render_webgl_ReplayGroup_.HIT_DETECTION_SIZE_, - pixelRatio, opacity, skippedFeaturesHash, - /** + coordinate, resolution, rotation, _ol_render_webgl_ReplayGroup_.HIT_DETECTION_SIZE_, + pixelRatio, opacity, skippedFeaturesHash, + /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @return {?} Callback result. */ - function(feature) { - var imageData = new Uint8Array(4); - gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, imageData); + function(feature) { + const imageData = new Uint8Array(4); + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, imageData); - if (imageData[3] > 0) { - var result = callback(feature); - if (result) { - return result; - } + if (imageData[3] > 0) { + const result = callback(feature); + if (result) { + return result; } - }, true, hitExtent); + } + }, true, hitExtent); }; @@ -282,24 +280,24 @@ _ol_render_webgl_ReplayGroup_.prototype.forEachFeatureAtCoordinate = function( * @return {boolean} Is there a feature at the given coordinate? */ _ol_render_webgl_ReplayGroup_.prototype.hasFeatureAtCoordinate = function( - coordinate, context, center, resolution, rotation, size, pixelRatio, - opacity, skippedFeaturesHash) { - var gl = context.getGL(); + coordinate, context, center, resolution, rotation, size, pixelRatio, + opacity, skippedFeaturesHash) { + const gl = context.getGL(); gl.bindFramebuffer( - gl.FRAMEBUFFER, context.getHitDetectionFramebuffer()); + gl.FRAMEBUFFER, context.getHitDetectionFramebuffer()); - var hasFeature = this.replayHitDetection_(context, - coordinate, resolution, rotation, _ol_render_webgl_ReplayGroup_.HIT_DETECTION_SIZE_, - pixelRatio, opacity, skippedFeaturesHash, - /** + const hasFeature = this.replayHitDetection_(context, + coordinate, resolution, rotation, _ol_render_webgl_ReplayGroup_.HIT_DETECTION_SIZE_, + pixelRatio, opacity, skippedFeaturesHash, + /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @return {boolean} Is there a feature? */ - function(feature) { - var imageData = new Uint8Array(4); - gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, imageData); - return imageData[3] > 0; - }, false); + function(feature) { + const imageData = new Uint8Array(4); + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, imageData); + return imageData[3] > 0; + }, false); return hasFeature !== undefined; }; diff --git a/src/ol/render/webgl/TextReplay.js b/src/ol/render/webgl/TextReplay.js index c83e2bb11f..6204fc0789 100644 --- a/src/ol/render/webgl/TextReplay.js +++ b/src/ol/render/webgl/TextReplay.js @@ -19,7 +19,7 @@ import _ol_webgl_Buffer_ from '../../webgl/Buffer.js'; * @param {ol.Extent} maxExtent Max extent. * @struct */ -var _ol_render_webgl_TextReplay_ = function(tolerance, maxExtent) { +const _ol_render_webgl_TextReplay_ = function(tolerance, maxExtent) { _ol_render_webgl_TextureReplay_.call(this, tolerance, maxExtent); /** @@ -122,10 +122,10 @@ inherits(_ol_render_webgl_TextReplay_, _ol_render_webgl_TextureReplay_); */ _ol_render_webgl_TextReplay_.prototype.drawText = function(geometry, feature) { if (this.text_) { - var flatCoordinates = null; - var offset = 0; - var end = 2; - var stride = 2; + let flatCoordinates = null; + const offset = 0; + let end = 2; + let stride = 2; switch (geometry.getType()) { case GeometryType.POINT: case GeometryType.MULTI_POINT: @@ -155,13 +155,13 @@ _ol_render_webgl_TextReplay_.prototype.drawText = function(geometry, feature) { this.startIndices.push(this.indices.length); this.startIndicesFeature.push(feature); - var glyphAtlas = this.currAtlas_; - var lines = this.text_.split('\n'); - var textSize = this.getTextSize_(lines); - var i, ii, j, jj, currX, currY, charArr, charInfo; - var anchorX = Math.round(textSize[0] * this.textAlign_ - this.offsetX_); - var anchorY = Math.round(textSize[1] * this.textBaseline_ - this.offsetY_); - var lineWidth = (this.state_.lineWidth / 2) * this.state_.scale; + const glyphAtlas = this.currAtlas_; + const lines = this.text_.split('\n'); + const textSize = this.getTextSize_(lines); + let i, ii, j, jj, currX, currY, charArr, charInfo; + const anchorX = Math.round(textSize[0] * this.textAlign_ - this.offsetX_); + const anchorY = Math.round(textSize[1] * this.textBaseline_ - this.offsetY_); + const lineWidth = (this.state_.lineWidth / 2) * this.state_.scale; for (i = 0, ii = lines.length; i < ii; ++i) { currX = 0; @@ -172,7 +172,7 @@ _ol_render_webgl_TextReplay_.prototype.drawText = function(geometry, feature) { charInfo = glyphAtlas.atlas.getInfo(charArr[j]); if (charInfo) { - var image = charInfo.image; + const image = charInfo.image; this.anchorX = anchorX - currX; this.anchorY = anchorY - currY; @@ -184,11 +184,10 @@ _ol_render_webgl_TextReplay_.prototype.drawText = function(geometry, feature) { this.imageHeight = image.height; this.imageWidth = image.width; - var currentImage; if (this.images_.length === 0) { this.images_.push(image); } else { - currentImage = this.images_[this.images_.length - 1]; + const currentImage = this.images_[this.images_.length - 1]; if (getUid(currentImage) != getUid(image)) { this.groupIndices.push(this.indices.length); this.images_.push(image); @@ -210,15 +209,15 @@ _ol_render_webgl_TextReplay_.prototype.drawText = function(geometry, feature) { * @return {Array.} Size of the label in pixels. */ _ol_render_webgl_TextReplay_.prototype.getTextSize_ = function(lines) { - var self = this; - var glyphAtlas = this.currAtlas_; - var textHeight = lines.length * glyphAtlas.height; + const self = this; + const glyphAtlas = this.currAtlas_; + const textHeight = lines.length * glyphAtlas.height; //Split every line to an array of chars, sum up their width, and select the longest. - var textWidth = lines.map(function(str) { - var sum = 0; - var i, ii; + const textWidth = lines.map(function(str) { + let sum = 0; + let i, ii; for (i = 0, ii = str.length; i < ii; ++i) { - var curr = str[i]; + const curr = str[i]; if (!glyphAtlas.width[curr]) { self.addCharToAtlas_(curr); } @@ -241,8 +240,8 @@ _ol_render_webgl_TextReplay_.prototype.getTextSize_ = function(lines) { * @param {number} stride Stride. */ _ol_render_webgl_TextReplay_.prototype.drawText_ = function(flatCoordinates, offset, - end, stride) { - var i, ii; + end, stride) { + let i, ii; for (i = offset, ii = end; i < ii; i += stride) { this.drawCoordinates(flatCoordinates, offset, end, stride); } @@ -255,43 +254,43 @@ _ol_render_webgl_TextReplay_.prototype.drawText_ = function(flatCoordinates, off */ _ol_render_webgl_TextReplay_.prototype.addCharToAtlas_ = function(char) { if (char.length === 1) { - var glyphAtlas = this.currAtlas_; - var state = this.state_; - var mCtx = this.measureCanvas_.getContext('2d'); + const glyphAtlas = this.currAtlas_; + const state = this.state_; + const mCtx = this.measureCanvas_.getContext('2d'); mCtx.font = state.font; - var width = Math.ceil(mCtx.measureText(char).width * state.scale); + const width = Math.ceil(mCtx.measureText(char).width * state.scale); - var info = glyphAtlas.atlas.add(char, width, glyphAtlas.height, - function(ctx, x, y) { - //Parameterize the canvas - ctx.font = /** @type {string} */ (state.font); - ctx.fillStyle = state.fillColor; - ctx.strokeStyle = state.strokeColor; - ctx.lineWidth = state.lineWidth; - ctx.lineCap = /*** @type {string} */ (state.lineCap); - ctx.lineJoin = /** @type {string} */ (state.lineJoin); - ctx.miterLimit = /** @type {number} */ (state.miterLimit); - ctx.textAlign = 'left'; - ctx.textBaseline = 'top'; - if (_ol_has_.CANVAS_LINE_DASH && state.lineDash) { - //FIXME: use pixelRatio - ctx.setLineDash(state.lineDash); - ctx.lineDashOffset = /** @type {number} */ (state.lineDashOffset); - } - if (state.scale !== 1) { - //FIXME: use pixelRatio - ctx.setTransform(/** @type {number} */ (state.scale), 0, 0, - /** @type {number} */ (state.scale), 0, 0); - } + const info = glyphAtlas.atlas.add(char, width, glyphAtlas.height, + function(ctx, x, y) { + //Parameterize the canvas + ctx.font = /** @type {string} */ (state.font); + ctx.fillStyle = state.fillColor; + ctx.strokeStyle = state.strokeColor; + ctx.lineWidth = state.lineWidth; + ctx.lineCap = /*** @type {string} */ (state.lineCap); + ctx.lineJoin = /** @type {string} */ (state.lineJoin); + ctx.miterLimit = /** @type {number} */ (state.miterLimit); + ctx.textAlign = 'left'; + ctx.textBaseline = 'top'; + if (_ol_has_.CANVAS_LINE_DASH && state.lineDash) { + //FIXME: use pixelRatio + ctx.setLineDash(state.lineDash); + ctx.lineDashOffset = /** @type {number} */ (state.lineDashOffset); + } + if (state.scale !== 1) { + //FIXME: use pixelRatio + ctx.setTransform(/** @type {number} */ (state.scale), 0, 0, + /** @type {number} */ (state.scale), 0, 0); + } - //Draw the character on the canvas - if (state.strokeColor) { - ctx.strokeText(char, x, y); - } - if (state.fillColor) { - ctx.fillText(char, x, y); - } - }); + //Draw the character on the canvas + if (state.strokeColor) { + ctx.strokeText(char, x, y); + } + if (state.fillColor) { + ctx.fillText(char, x, y); + } + }); if (info) { glyphAtlas.width[char] = width; @@ -304,7 +303,7 @@ _ol_render_webgl_TextReplay_.prototype.addCharToAtlas_ = function(char) { * @inheritDoc */ _ol_render_webgl_TextReplay_.prototype.finish = function(context) { - var gl = context.getGL(); + const gl = context.getGL(); this.groupIndices.push(this.indices.length); this.hitDetectionGroupIndices = this.groupIndices; @@ -317,7 +316,7 @@ _ol_render_webgl_TextReplay_.prototype.finish = function(context) { // create textures /** @type {Object.} */ - var texturePerImage = {}; + const texturePerImage = {}; this.createTextures(this.textures_, this.images_, texturePerImage, gl); @@ -349,16 +348,16 @@ _ol_render_webgl_TextReplay_.prototype.finish = function(context) { * @inheritDoc */ _ol_render_webgl_TextReplay_.prototype.setTextStyle = function(textStyle) { - var state = this.state_; - var textFillStyle = textStyle.getFill(); - var textStrokeStyle = textStyle.getStroke(); + const state = this.state_; + const textFillStyle = textStyle.getFill(); + const textStrokeStyle = textStyle.getStroke(); if (!textStyle || !textStyle.getText() || (!textFillStyle && !textStrokeStyle)) { this.text_ = ''; } else { if (!textFillStyle) { state.fillColor = null; } else { - var textFillStyleColor = textFillStyle.getColor(); + const textFillStyleColor = textFillStyle.getColor(); state.fillColor = asColorLike(textFillStyleColor ? textFillStyleColor : _ol_render_webgl_.defaultFillStyle); } @@ -366,7 +365,7 @@ _ol_render_webgl_TextReplay_.prototype.setTextStyle = function(textStyle) { state.strokeColor = null; state.lineWidth = 0; } else { - var textStrokeStyleColor = textStrokeStyle.getColor(); + const textStrokeStyleColor = textStrokeStyle.getColor(); state.strokeColor = asColorLike(textStrokeStyleColor ? textStrokeStyleColor : _ol_render_webgl_.defaultStrokeStyle); state.lineWidth = textStrokeStyle.getWidth() || _ol_render_webgl_.defaultLineWidth; @@ -374,14 +373,14 @@ _ol_render_webgl_TextReplay_.prototype.setTextStyle = function(textStyle) { state.lineDashOffset = textStrokeStyle.getLineDashOffset() || _ol_render_webgl_.defaultLineDashOffset; state.lineJoin = textStrokeStyle.getLineJoin() || _ol_render_webgl_.defaultLineJoin; state.miterLimit = textStrokeStyle.getMiterLimit() || _ol_render_webgl_.defaultMiterLimit; - var lineDash = textStrokeStyle.getLineDash(); + const lineDash = textStrokeStyle.getLineDash(); state.lineDash = lineDash ? lineDash.slice() : _ol_render_webgl_.defaultLineDash; } state.font = textStyle.getFont() || _ol_render_webgl_.defaultFont; state.scale = textStyle.getScale() || 1; this.text_ = /** @type {string} */ (textStyle.getText()); - var textAlign = _ol_render_replay_.TEXT_ALIGN[textStyle.getTextAlign()]; - var textBaseline = _ol_render_replay_.TEXT_ALIGN[textStyle.getTextBaseline()]; + const textAlign = _ol_render_replay_.TEXT_ALIGN[textStyle.getTextAlign()]; + const textBaseline = _ol_render_replay_.TEXT_ALIGN[textStyle.getTextBaseline()]; this.textAlign_ = textAlign === undefined ? _ol_render_webgl_.defaultTextAlign : textAlign; this.textBaseline_ = textBaseline === undefined ? @@ -402,8 +401,8 @@ _ol_render_webgl_TextReplay_.prototype.setTextStyle = function(textStyle) { * @return {ol.WebglGlyphAtlas} Glyph atlas. */ _ol_render_webgl_TextReplay_.prototype.getAtlas_ = function(state) { - var params = []; - var i; + let params = []; + let i; for (i in state) { if (state[i] || state[i] === 0) { if (Array.isArray(state[i])) { @@ -413,11 +412,11 @@ _ol_render_webgl_TextReplay_.prototype.getAtlas_ = function(state) { } } } - var hash = this.calculateHash_(params); + const hash = this.calculateHash_(params); if (!this.atlases_[hash]) { - var mCtx = this.measureCanvas_.getContext('2d'); + const mCtx = this.measureCanvas_.getContext('2d'); mCtx.font = state.font; - var height = Math.ceil((mCtx.measureText('M').width * 1.5 + + const height = Math.ceil((mCtx.measureText('M').width * 1.5 + state.lineWidth / 2) * state.scale); this.atlases_[hash] = { @@ -439,8 +438,8 @@ _ol_render_webgl_TextReplay_.prototype.getAtlas_ = function(state) { */ _ol_render_webgl_TextReplay_.prototype.calculateHash_ = function(params) { //TODO: Create a more performant, reliable, general hash function. - var i, ii; - var hash = ''; + let i, ii; + let hash = ''; for (i = 0, ii = params.length; i < ii; ++i) { hash += params[i]; } diff --git a/src/ol/render/webgl/TextureReplay.js b/src/ol/render/webgl/TextureReplay.js index f64194b432..0e41d302e4 100644 --- a/src/ol/render/webgl/TextureReplay.js +++ b/src/ol/render/webgl/TextureReplay.js @@ -18,7 +18,7 @@ import _ol_webgl_Context_ from '../../webgl/Context.js'; * @param {ol.Extent} maxExtent Max extent. * @struct */ -var _ol_render_webgl_TextureReplay_ = function(tolerance, maxExtent) { +const _ol_render_webgl_TextureReplay_ = function(tolerance, maxExtent) { _ol_render_webgl_Replay_.call(this, tolerance, maxExtent); /** @@ -119,13 +119,13 @@ inherits(_ol_render_webgl_TextureReplay_, _ol_render_webgl_Replay_); * @inheritDoc */ _ol_render_webgl_TextureReplay_.prototype.getDeleteResourcesFunction = function(context) { - var verticesBuffer = this.verticesBuffer; - var indicesBuffer = this.indicesBuffer; - var textures = this.getTextures(true); - var gl = context.getGL(); + const verticesBuffer = this.verticesBuffer; + const indicesBuffer = this.indicesBuffer; + const textures = this.getTextures(true); + const gl = context.getGL(); return function() { if (!gl.isContextLost()) { - var i, ii; + let i, ii; for (i = 0, ii = textures.length; i < ii; ++i) { gl.deleteTexture(textures[i]); } @@ -145,24 +145,24 @@ _ol_render_webgl_TextureReplay_.prototype.getDeleteResourcesFunction = function( * @protected */ _ol_render_webgl_TextureReplay_.prototype.drawCoordinates = function(flatCoordinates, offset, end, stride) { - var anchorX = /** @type {number} */ (this.anchorX); - var anchorY = /** @type {number} */ (this.anchorY); - var height = /** @type {number} */ (this.height); - var imageHeight = /** @type {number} */ (this.imageHeight); - var imageWidth = /** @type {number} */ (this.imageWidth); - var opacity = /** @type {number} */ (this.opacity); - var originX = /** @type {number} */ (this.originX); - var originY = /** @type {number} */ (this.originY); - var rotateWithView = this.rotateWithView ? 1.0 : 0.0; + const anchorX = /** @type {number} */ (this.anchorX); + const anchorY = /** @type {number} */ (this.anchorY); + const height = /** @type {number} */ (this.height); + const imageHeight = /** @type {number} */ (this.imageHeight); + const imageWidth = /** @type {number} */ (this.imageWidth); + const opacity = /** @type {number} */ (this.opacity); + const originX = /** @type {number} */ (this.originX); + const originY = /** @type {number} */ (this.originY); + const rotateWithView = this.rotateWithView ? 1.0 : 0.0; // this.rotation_ is anti-clockwise, but rotation is clockwise - var rotation = /** @type {number} */ (-this.rotation); - var scale = /** @type {number} */ (this.scale); - var width = /** @type {number} */ (this.width); - var cos = Math.cos(rotation); - var sin = Math.sin(rotation); - var numIndices = this.indices.length; - var numVertices = this.vertices.length; - var i, n, offsetX, offsetY, x, y; + const rotation = /** @type {number} */ (-this.rotation); + const scale = /** @type {number} */ (this.scale); + const width = /** @type {number} */ (this.width); + const cos = Math.cos(rotation); + const sin = Math.sin(rotation); + let numIndices = this.indices.length; + let numVertices = this.vertices.length; + let i, n, offsetX, offsetY, x, y; for (i = offset; i < end; i += stride) { x = flatCoordinates[i] - this.origin[0]; y = flatCoordinates[i + 1] - this.origin[1]; @@ -248,8 +248,8 @@ _ol_render_webgl_TextureReplay_.prototype.drawCoordinates = function(flatCoordin * @param {WebGLRenderingContext} gl Gl. */ _ol_render_webgl_TextureReplay_.prototype.createTextures = function(textures, images, texturePerImage, gl) { - var texture, image, uid, i; - var ii = images.length; + let texture, image, uid, i; + const ii = images.length; for (i = 0; i < ii; ++i) { image = images[i]; @@ -258,7 +258,7 @@ _ol_render_webgl_TextureReplay_.prototype.createTextures = function(textures, im texture = texturePerImage[uid]; } else { texture = _ol_webgl_Context_.createTexture( - gl, image, _ol_webgl_.CLAMP_TO_EDGE, _ol_webgl_.CLAMP_TO_EDGE); + gl, image, _ol_webgl_.CLAMP_TO_EDGE, _ol_webgl_.CLAMP_TO_EDGE); texturePerImage[uid] = texture; } textures[i] = texture; @@ -271,12 +271,12 @@ _ol_render_webgl_TextureReplay_.prototype.createTextures = function(textures, im */ _ol_render_webgl_TextureReplay_.prototype.setUpProgram = function(gl, context, size, pixelRatio) { // get the program - var fragmentShader = _ol_render_webgl_texturereplay_defaultshader_.fragment; - var vertexShader = _ol_render_webgl_texturereplay_defaultshader_.vertex; - var program = context.getProgram(fragmentShader, vertexShader); + const fragmentShader = _ol_render_webgl_texturereplay_defaultshader_.fragment; + const vertexShader = _ol_render_webgl_texturereplay_defaultshader_.vertex; + const program = context.getProgram(fragmentShader, vertexShader); // get the locations - var locations; + let locations; if (!this.defaultLocations) { locations = new _ol_render_webgl_texturereplay_defaultshader_Locations_(gl, program); this.defaultLocations = locations; @@ -290,23 +290,23 @@ _ol_render_webgl_TextureReplay_.prototype.setUpProgram = function(gl, context, s // enable the vertex attrib arrays gl.enableVertexAttribArray(locations.a_position); gl.vertexAttribPointer(locations.a_position, 2, _ol_webgl_.FLOAT, - false, 32, 0); + false, 32, 0); gl.enableVertexAttribArray(locations.a_offsets); gl.vertexAttribPointer(locations.a_offsets, 2, _ol_webgl_.FLOAT, - false, 32, 8); + false, 32, 8); gl.enableVertexAttribArray(locations.a_texCoord); gl.vertexAttribPointer(locations.a_texCoord, 2, _ol_webgl_.FLOAT, - false, 32, 16); + false, 32, 16); gl.enableVertexAttribArray(locations.a_opacity); gl.vertexAttribPointer(locations.a_opacity, 1, _ol_webgl_.FLOAT, - false, 32, 24); + false, 32, 24); gl.enableVertexAttribArray(locations.a_rotateWithView); gl.vertexAttribPointer(locations.a_rotateWithView, 1, _ol_webgl_.FLOAT, - false, 32, 28); + false, 32, 28); return locations; }; @@ -328,17 +328,17 @@ _ol_render_webgl_TextureReplay_.prototype.shutDownProgram = function(gl, locatio * @inheritDoc */ _ol_render_webgl_TextureReplay_.prototype.drawReplay = function(gl, context, skippedFeaturesHash, hitDetection) { - var textures = hitDetection ? this.getHitDetectionTextures() : this.getTextures(); - var groupIndices = hitDetection ? this.hitDetectionGroupIndices : this.groupIndices; + const textures = hitDetection ? this.getHitDetectionTextures() : this.getTextures(); + const groupIndices = hitDetection ? this.hitDetectionGroupIndices : this.groupIndices; if (!_ol_obj_.isEmpty(skippedFeaturesHash)) { this.drawReplaySkipping( - gl, context, skippedFeaturesHash, textures, groupIndices); + gl, context, skippedFeaturesHash, textures, groupIndices); } else { - var i, ii, start; + let i, ii, start; for (i = 0, ii = textures.length, start = 0; i < ii; ++i) { gl.bindTexture(_ol_webgl_.TEXTURE_2D, textures[i]); - var end = groupIndices[i]; + const end = groupIndices[i]; this.drawElements(gl, context, start, end); start = end; } @@ -373,22 +373,22 @@ _ol_render_webgl_TextureReplay_.prototype.drawReplay = function(gl, context, ski * @param {Array.} groupIndices Texture group indices. */ _ol_render_webgl_TextureReplay_.prototype.drawReplaySkipping = function(gl, context, skippedFeaturesHash, textures, - groupIndices) { - var featureIndex = 0; + groupIndices) { + let featureIndex = 0; - var i, ii; + let i, ii; for (i = 0, ii = textures.length; i < ii; ++i) { gl.bindTexture(_ol_webgl_.TEXTURE_2D, textures[i]); - var groupStart = (i > 0) ? groupIndices[i - 1] : 0; - var groupEnd = groupIndices[i]; + const groupStart = (i > 0) ? groupIndices[i - 1] : 0; + const groupEnd = groupIndices[i]; - var start = groupStart; - var end = groupStart; + let start = groupStart; + let end = groupStart; while (featureIndex < this.startIndices.length && this.startIndices[featureIndex] <= groupEnd) { - var feature = this.startIndicesFeature[featureIndex]; + const feature = this.startIndicesFeature[featureIndex]; - var featureUid = getUid(feature).toString(); + const featureUid = getUid(feature).toString(); if (skippedFeaturesHash[featureUid] !== undefined) { // feature should be skipped if (start !== end) { @@ -420,10 +420,10 @@ _ol_render_webgl_TextureReplay_.prototype.drawReplaySkipping = function(gl, cont * @inheritDoc */ _ol_render_webgl_TextureReplay_.prototype.drawHitDetectionReplayOneByOne = function(gl, context, skippedFeaturesHash, - featureCallback, opt_hitExtent) { - var i, groupStart, start, end, feature, featureUid; - var featureIndex = this.startIndices.length - 1; - var hitDetectionTextures = this.getHitDetectionTextures(); + featureCallback, opt_hitExtent) { + let i, groupStart, start, end, feature, featureUid; + let featureIndex = this.startIndices.length - 1; + const hitDetectionTextures = this.getHitDetectionTextures(); for (i = hitDetectionTextures.length - 1; i >= 0; --i) { gl.bindTexture(_ol_webgl_.TEXTURE_2D, hitDetectionTextures[i]); groupStart = (i > 0) ? this.hitDetectionGroupIndices[i - 1] : 0; @@ -439,12 +439,12 @@ _ol_render_webgl_TextureReplay_.prototype.drawHitDetectionReplayOneByOne = funct if (skippedFeaturesHash[featureUid] === undefined && feature.getGeometry() && (opt_hitExtent === undefined || intersects( - /** @type {Array} */ (opt_hitExtent), - feature.getGeometry().getExtent()))) { + /** @type {Array} */ (opt_hitExtent), + feature.getGeometry().getExtent()))) { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); this.drawElements(gl, context, start, end); - var result = featureCallback(feature); + const result = featureCallback(feature); if (result) { return result; } diff --git a/src/ol/render/webgl/circlereplay/defaultshader.js b/src/ol/render/webgl/circlereplay/defaultshader.js index a958fdf3a7..97962c7221 100644 --- a/src/ol/render/webgl/circlereplay/defaultshader.js +++ b/src/ol/render/webgl/circlereplay/defaultshader.js @@ -4,7 +4,7 @@ import {DEBUG_WEBGL} from '../../../index.js'; import _ol_webgl_Fragment_ from '../../../webgl/Fragment.js'; import _ol_webgl_Vertex_ from '../../../webgl/Vertex.js'; -var _ol_render_webgl_circlereplay_defaultshader_ = {}; +const _ol_render_webgl_circlereplay_defaultshader_ = {}; _ol_render_webgl_circlereplay_defaultshader_.fragment = new _ol_webgl_Fragment_(DEBUG_WEBGL ? 'precision mediump float;\nvarying vec2 v_center;\nvarying vec2 v_offset;\nvarying float v_halfWidth;\nvarying float v_pixelRatio;\n\n\n\nuniform float u_opacity;\nuniform vec4 u_fillColor;\nuniform vec4 u_strokeColor;\nuniform vec2 u_size;\n\nvoid main(void) {\n vec2 windowCenter = vec2((v_center.x + 1.0) / 2.0 * u_size.x * v_pixelRatio,\n (v_center.y + 1.0) / 2.0 * u_size.y * v_pixelRatio);\n vec2 windowOffset = vec2((v_offset.x + 1.0) / 2.0 * u_size.x * v_pixelRatio,\n (v_offset.y + 1.0) / 2.0 * u_size.y * v_pixelRatio);\n float radius = length(windowCenter - windowOffset);\n float dist = length(windowCenter - gl_FragCoord.xy);\n if (dist > radius + v_halfWidth) {\n if (u_strokeColor.a == 0.0) {\n gl_FragColor = u_fillColor;\n } else {\n gl_FragColor = u_strokeColor;\n }\n gl_FragColor.a = gl_FragColor.a - (dist - (radius + v_halfWidth));\n } else if (u_fillColor.a == 0.0) {\n // Hooray, no fill, just stroke. We can use real antialiasing.\n gl_FragColor = u_strokeColor;\n if (dist < radius - v_halfWidth) {\n gl_FragColor.a = gl_FragColor.a - (radius - v_halfWidth - dist);\n }\n } else {\n gl_FragColor = u_fillColor;\n float strokeDist = radius - v_halfWidth;\n float antialias = 2.0 * v_pixelRatio;\n if (dist > strokeDist) {\n gl_FragColor = u_strokeColor;\n } else if (dist >= strokeDist - antialias) {\n float step = smoothstep(strokeDist - antialias, strokeDist, dist);\n gl_FragColor = mix(u_fillColor, u_strokeColor, step);\n }\n }\n gl_FragColor.a = gl_FragColor.a * u_opacity;\n if (gl_FragColor.a <= 0.0) {\n discard;\n }\n}\n' : diff --git a/src/ol/render/webgl/circlereplay/defaultshader/Locations.js b/src/ol/render/webgl/circlereplay/defaultshader/Locations.js index fc19474dee..67f67f9a6c 100644 --- a/src/ol/render/webgl/circlereplay/defaultshader/Locations.js +++ b/src/ol/render/webgl/circlereplay/defaultshader/Locations.js @@ -10,79 +10,79 @@ import {DEBUG_WEBGL} from '../../../../index.js'; * @param {WebGLProgram} program Program. * @struct */ -var _ol_render_webgl_circlereplay_defaultshader_Locations_ = function(gl, program) { +const _ol_render_webgl_circlereplay_defaultshader_Locations_ = function(gl, program) { /** * @type {WebGLUniformLocation} */ this.u_projectionMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_projectionMatrix' : 'h'); + program, DEBUG_WEBGL ? 'u_projectionMatrix' : 'h'); /** * @type {WebGLUniformLocation} */ this.u_offsetScaleMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_offsetScaleMatrix' : 'i'); + program, DEBUG_WEBGL ? 'u_offsetScaleMatrix' : 'i'); /** * @type {WebGLUniformLocation} */ this.u_offsetRotateMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_offsetRotateMatrix' : 'j'); + program, DEBUG_WEBGL ? 'u_offsetRotateMatrix' : 'j'); /** * @type {WebGLUniformLocation} */ this.u_lineWidth = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_lineWidth' : 'k'); + program, DEBUG_WEBGL ? 'u_lineWidth' : 'k'); /** * @type {WebGLUniformLocation} */ this.u_pixelRatio = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_pixelRatio' : 'l'); + program, DEBUG_WEBGL ? 'u_pixelRatio' : 'l'); /** * @type {WebGLUniformLocation} */ this.u_opacity = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_opacity' : 'm'); + program, DEBUG_WEBGL ? 'u_opacity' : 'm'); /** * @type {WebGLUniformLocation} */ this.u_fillColor = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_fillColor' : 'n'); + program, DEBUG_WEBGL ? 'u_fillColor' : 'n'); /** * @type {WebGLUniformLocation} */ this.u_strokeColor = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_strokeColor' : 'o'); + program, DEBUG_WEBGL ? 'u_strokeColor' : 'o'); /** * @type {WebGLUniformLocation} */ this.u_size = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_size' : 'p'); + program, DEBUG_WEBGL ? 'u_size' : 'p'); /** * @type {number} */ this.a_position = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_position' : 'e'); + program, DEBUG_WEBGL ? 'a_position' : 'e'); /** * @type {number} */ this.a_instruction = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_instruction' : 'f'); + program, DEBUG_WEBGL ? 'a_instruction' : 'f'); /** * @type {number} */ this.a_radius = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_radius' : 'g'); + program, DEBUG_WEBGL ? 'a_radius' : 'g'); }; export default _ol_render_webgl_circlereplay_defaultshader_Locations_; diff --git a/src/ol/render/webgl/linestringreplay/defaultshader.js b/src/ol/render/webgl/linestringreplay/defaultshader.js index 49005b4d39..bfd67e3b89 100644 --- a/src/ol/render/webgl/linestringreplay/defaultshader.js +++ b/src/ol/render/webgl/linestringreplay/defaultshader.js @@ -4,7 +4,7 @@ import {DEBUG_WEBGL} from '../../../index.js'; import _ol_webgl_Fragment_ from '../../../webgl/Fragment.js'; import _ol_webgl_Vertex_ from '../../../webgl/Vertex.js'; -var _ol_render_webgl_linestringreplay_defaultshader_ = {}; +const _ol_render_webgl_linestringreplay_defaultshader_ = {}; _ol_render_webgl_linestringreplay_defaultshader_.fragment = new _ol_webgl_Fragment_(DEBUG_WEBGL ? 'precision mediump float;\nvarying float v_round;\nvarying vec2 v_roundVertex;\nvarying float v_halfWidth;\n\n\n\nuniform float u_opacity;\nuniform vec4 u_color;\nuniform vec2 u_size;\nuniform float u_pixelRatio;\n\nvoid main(void) {\n if (v_round > 0.0) {\n vec2 windowCoords = vec2((v_roundVertex.x + 1.0) / 2.0 * u_size.x * u_pixelRatio,\n (v_roundVertex.y + 1.0) / 2.0 * u_size.y * u_pixelRatio);\n if (length(windowCoords - gl_FragCoord.xy) > v_halfWidth * u_pixelRatio) {\n discard;\n }\n }\n gl_FragColor = u_color;\n float alpha = u_color.a * u_opacity;\n if (alpha == 0.0) {\n discard;\n }\n gl_FragColor.a = alpha;\n}\n' : diff --git a/src/ol/render/webgl/linestringreplay/defaultshader/Locations.js b/src/ol/render/webgl/linestringreplay/defaultshader/Locations.js index e2a20f8da4..e84cb17708 100644 --- a/src/ol/render/webgl/linestringreplay/defaultshader/Locations.js +++ b/src/ol/render/webgl/linestringreplay/defaultshader/Locations.js @@ -10,85 +10,85 @@ import {DEBUG_WEBGL} from '../../../../index.js'; * @param {WebGLProgram} program Program. * @struct */ -var _ol_render_webgl_linestringreplay_defaultshader_Locations_ = function(gl, program) { +const _ol_render_webgl_linestringreplay_defaultshader_Locations_ = function(gl, program) { /** * @type {WebGLUniformLocation} */ this.u_projectionMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_projectionMatrix' : 'h'); + program, DEBUG_WEBGL ? 'u_projectionMatrix' : 'h'); /** * @type {WebGLUniformLocation} */ this.u_offsetScaleMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_offsetScaleMatrix' : 'i'); + program, DEBUG_WEBGL ? 'u_offsetScaleMatrix' : 'i'); /** * @type {WebGLUniformLocation} */ this.u_offsetRotateMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_offsetRotateMatrix' : 'j'); + program, DEBUG_WEBGL ? 'u_offsetRotateMatrix' : 'j'); /** * @type {WebGLUniformLocation} */ this.u_lineWidth = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_lineWidth' : 'k'); + program, DEBUG_WEBGL ? 'u_lineWidth' : 'k'); /** * @type {WebGLUniformLocation} */ this.u_miterLimit = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_miterLimit' : 'l'); + program, DEBUG_WEBGL ? 'u_miterLimit' : 'l'); /** * @type {WebGLUniformLocation} */ this.u_opacity = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_opacity' : 'm'); + program, DEBUG_WEBGL ? 'u_opacity' : 'm'); /** * @type {WebGLUniformLocation} */ this.u_color = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_color' : 'n'); + program, DEBUG_WEBGL ? 'u_color' : 'n'); /** * @type {WebGLUniformLocation} */ this.u_size = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_size' : 'o'); + program, DEBUG_WEBGL ? 'u_size' : 'o'); /** * @type {WebGLUniformLocation} */ this.u_pixelRatio = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_pixelRatio' : 'p'); + program, DEBUG_WEBGL ? 'u_pixelRatio' : 'p'); /** * @type {number} */ this.a_lastPos = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_lastPos' : 'd'); + program, DEBUG_WEBGL ? 'a_lastPos' : 'd'); /** * @type {number} */ this.a_position = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_position' : 'e'); + program, DEBUG_WEBGL ? 'a_position' : 'e'); /** * @type {number} */ this.a_nextPos = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_nextPos' : 'f'); + program, DEBUG_WEBGL ? 'a_nextPos' : 'f'); /** * @type {number} */ this.a_direction = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_direction' : 'g'); + program, DEBUG_WEBGL ? 'a_direction' : 'g'); }; export default _ol_render_webgl_linestringreplay_defaultshader_Locations_; diff --git a/src/ol/render/webgl/polygonreplay/defaultshader.js b/src/ol/render/webgl/polygonreplay/defaultshader.js index 33230ab722..260b360c75 100644 --- a/src/ol/render/webgl/polygonreplay/defaultshader.js +++ b/src/ol/render/webgl/polygonreplay/defaultshader.js @@ -4,7 +4,7 @@ import {DEBUG_WEBGL} from '../../../index.js'; import _ol_webgl_Fragment_ from '../../../webgl/Fragment.js'; import _ol_webgl_Vertex_ from '../../../webgl/Vertex.js'; -var _ol_render_webgl_polygonreplay_defaultshader_ = {}; +const _ol_render_webgl_polygonreplay_defaultshader_ = {}; _ol_render_webgl_polygonreplay_defaultshader_.fragment = new _ol_webgl_Fragment_(DEBUG_WEBGL ? 'precision mediump float;\n\n\n\nuniform vec4 u_color;\nuniform float u_opacity;\n\nvoid main(void) {\n gl_FragColor = u_color;\n float alpha = u_color.a * u_opacity;\n if (alpha == 0.0) {\n discard;\n }\n gl_FragColor.a = alpha;\n}\n' : diff --git a/src/ol/render/webgl/polygonreplay/defaultshader/Locations.js b/src/ol/render/webgl/polygonreplay/defaultshader/Locations.js index 70f9e6f67a..991e479338 100644 --- a/src/ol/render/webgl/polygonreplay/defaultshader/Locations.js +++ b/src/ol/render/webgl/polygonreplay/defaultshader/Locations.js @@ -10,43 +10,43 @@ import {DEBUG_WEBGL} from '../../../../index.js'; * @param {WebGLProgram} program Program. * @struct */ -var _ol_render_webgl_polygonreplay_defaultshader_Locations_ = function(gl, program) { +const _ol_render_webgl_polygonreplay_defaultshader_Locations_ = function(gl, program) { /** * @type {WebGLUniformLocation} */ this.u_projectionMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_projectionMatrix' : 'b'); + program, DEBUG_WEBGL ? 'u_projectionMatrix' : 'b'); /** * @type {WebGLUniformLocation} */ this.u_offsetScaleMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_offsetScaleMatrix' : 'c'); + program, DEBUG_WEBGL ? 'u_offsetScaleMatrix' : 'c'); /** * @type {WebGLUniformLocation} */ this.u_offsetRotateMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_offsetRotateMatrix' : 'd'); + program, DEBUG_WEBGL ? 'u_offsetRotateMatrix' : 'd'); /** * @type {WebGLUniformLocation} */ this.u_color = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_color' : 'e'); + program, DEBUG_WEBGL ? 'u_color' : 'e'); /** * @type {WebGLUniformLocation} */ this.u_opacity = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_opacity' : 'f'); + program, DEBUG_WEBGL ? 'u_opacity' : 'f'); /** * @type {number} */ this.a_position = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_position' : 'a'); + program, DEBUG_WEBGL ? 'a_position' : 'a'); }; export default _ol_render_webgl_polygonreplay_defaultshader_Locations_; diff --git a/src/ol/render/webgl/texturereplay/defaultshader.js b/src/ol/render/webgl/texturereplay/defaultshader.js index 6d0f10c62f..8401d4c2a1 100644 --- a/src/ol/render/webgl/texturereplay/defaultshader.js +++ b/src/ol/render/webgl/texturereplay/defaultshader.js @@ -4,7 +4,7 @@ import {DEBUG_WEBGL} from '../../../index.js'; import _ol_webgl_Fragment_ from '../../../webgl/Fragment.js'; import _ol_webgl_Vertex_ from '../../../webgl/Vertex.js'; -var _ol_render_webgl_texturereplay_defaultshader_ = {}; +const _ol_render_webgl_texturereplay_defaultshader_ = {}; _ol_render_webgl_texturereplay_defaultshader_.fragment = new _ol_webgl_Fragment_(DEBUG_WEBGL ? 'precision mediump float;\nvarying vec2 v_texCoord;\nvarying float v_opacity;\n\nuniform float u_opacity;\nuniform sampler2D u_image;\n\nvoid main(void) {\n vec4 texColor = texture2D(u_image, v_texCoord);\n gl_FragColor.rgb = texColor.rgb;\n float alpha = texColor.a * v_opacity * u_opacity;\n if (alpha == 0.0) {\n discard;\n }\n gl_FragColor.a = alpha;\n}\n' : diff --git a/src/ol/render/webgl/texturereplay/defaultshader/Locations.js b/src/ol/render/webgl/texturereplay/defaultshader/Locations.js index 97f3511498..101e687703 100644 --- a/src/ol/render/webgl/texturereplay/defaultshader/Locations.js +++ b/src/ol/render/webgl/texturereplay/defaultshader/Locations.js @@ -10,67 +10,67 @@ import {DEBUG_WEBGL} from '../../../../index.js'; * @param {WebGLProgram} program Program. * @struct */ -var _ol_render_webgl_texturereplay_defaultshader_Locations_ = function(gl, program) { +const _ol_render_webgl_texturereplay_defaultshader_Locations_ = function(gl, program) { /** * @type {WebGLUniformLocation} */ this.u_projectionMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_projectionMatrix' : 'h'); + program, DEBUG_WEBGL ? 'u_projectionMatrix' : 'h'); /** * @type {WebGLUniformLocation} */ this.u_offsetScaleMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_offsetScaleMatrix' : 'i'); + program, DEBUG_WEBGL ? 'u_offsetScaleMatrix' : 'i'); /** * @type {WebGLUniformLocation} */ this.u_offsetRotateMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_offsetRotateMatrix' : 'j'); + program, DEBUG_WEBGL ? 'u_offsetRotateMatrix' : 'j'); /** * @type {WebGLUniformLocation} */ this.u_opacity = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_opacity' : 'k'); + program, DEBUG_WEBGL ? 'u_opacity' : 'k'); /** * @type {WebGLUniformLocation} */ this.u_image = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_image' : 'l'); + program, DEBUG_WEBGL ? 'u_image' : 'l'); /** * @type {number} */ this.a_position = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_position' : 'c'); + program, DEBUG_WEBGL ? 'a_position' : 'c'); /** * @type {number} */ this.a_texCoord = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_texCoord' : 'd'); + program, DEBUG_WEBGL ? 'a_texCoord' : 'd'); /** * @type {number} */ this.a_offsets = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_offsets' : 'e'); + program, DEBUG_WEBGL ? 'a_offsets' : 'e'); /** * @type {number} */ this.a_opacity = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_opacity' : 'f'); + program, DEBUG_WEBGL ? 'a_opacity' : 'f'); /** * @type {number} */ this.a_rotateWithView = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_rotateWithView' : 'g'); + program, DEBUG_WEBGL ? 'a_rotateWithView' : 'g'); }; export default _ol_render_webgl_texturereplay_defaultshader_Locations_; diff --git a/src/ol/renderer/Layer.js b/src/ol/renderer/Layer.js index 8a1fb707de..5b09bdd627 100644 --- a/src/ol/renderer/Layer.js +++ b/src/ol/renderer/Layer.js @@ -16,7 +16,7 @@ import SourceState from '../source/State.js'; * @param {ol.layer.Layer} layer Layer. * @struct */ -var LayerRenderer = function(layer) { +const LayerRenderer = function(layer) { Observable.call(this); @@ -97,7 +97,7 @@ LayerRenderer.prototype.getLayer = function() { * @private */ LayerRenderer.prototype.handleImageChange_ = function(event) { - var image = /** @type {ol.Image} */ (event.target); + const image = /** @type {ol.Image} */ (event.target); if (image.getState() === ImageState.LOADED) { this.renderIfReadyAndVisible(); } @@ -113,7 +113,7 @@ LayerRenderer.prototype.handleImageChange_ = function(event) { * @protected */ LayerRenderer.prototype.loadImage = function(image) { - var imageState = image.getState(); + let imageState = image.getState(); if (imageState != ImageState.LOADED && imageState != ImageState.ERROR) { _ol_events_.listen(image, EventType.CHANGE, this.handleImageChange_, this); } @@ -129,7 +129,7 @@ LayerRenderer.prototype.loadImage = function(image) { * @protected */ LayerRenderer.prototype.renderIfReadyAndVisible = function() { - var layer = this.getLayer(); + const layer = this.getLayer(); if (layer.getVisible() && layer.getSourceState() == SourceState.READY) { this.changed(); } @@ -148,16 +148,16 @@ LayerRenderer.prototype.scheduleExpireCache = function(frameState, tileSource) { * @param {ol.PluggableMap} map Map. * @param {olx.FrameState} frameState Frame state. */ - var postRenderFunction = function(tileSource, map, frameState) { - var tileSourceKey = getUid(tileSource).toString(); + const postRenderFunction = function(tileSource, map, frameState) { + const tileSourceKey = getUid(tileSource).toString(); if (tileSourceKey in frameState.usedTiles) { tileSource.expireCache(frameState.viewState.projection, - frameState.usedTiles[tileSourceKey]); + frameState.usedTiles[tileSourceKey]); } }.bind(null, tileSource); frameState.postRenderFunctions.push( - /** @type {ol.PostRenderFunction} */ (postRenderFunction) + /** @type {ol.PostRenderFunction} */ (postRenderFunction) ); } }; @@ -172,8 +172,8 @@ LayerRenderer.prototype.scheduleExpireCache = function(frameState, tileSource) { */ LayerRenderer.prototype.updateUsedTiles = function(usedTiles, tileSource, z, tileRange) { // FIXME should we use tilesToDrawByZ instead? - var tileSourceKey = getUid(tileSource).toString(); - var zKey = z.toString(); + const tileSourceKey = getUid(tileSource).toString(); + const zKey = z.toString(); if (tileSourceKey in usedTiles) { if (zKey in usedTiles[tileSourceKey]) { usedTiles[tileSourceKey][zKey].extend(tileRange); @@ -208,16 +208,16 @@ LayerRenderer.prototype.updateUsedTiles = function(usedTiles, tileSource, z, til * @template T */ LayerRenderer.prototype.manageTilePyramid = function( - frameState, tileSource, tileGrid, pixelRatio, projection, extent, - currentZ, preload, opt_tileCallback, opt_this) { - var tileSourceKey = getUid(tileSource).toString(); + frameState, tileSource, tileGrid, pixelRatio, projection, extent, + currentZ, preload, opt_tileCallback, opt_this) { + const tileSourceKey = getUid(tileSource).toString(); if (!(tileSourceKey in frameState.wantedTiles)) { frameState.wantedTiles[tileSourceKey] = {}; } - var wantedTiles = frameState.wantedTiles[tileSourceKey]; - var tileQueue = frameState.tileQueue; - var minZoom = tileGrid.getMinZoom(); - var tile, tileRange, tileResolution, x, y, z; + const wantedTiles = frameState.wantedTiles[tileSourceKey]; + const tileQueue = frameState.tileQueue; + const minZoom = tileGrid.getMinZoom(); + let tile, tileRange, tileResolution, x, y, z; for (z = minZoom; z <= currentZ; ++z) { tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z, tileRange); tileResolution = tileGrid.getResolution(z); diff --git a/src/ol/renderer/Map.js b/src/ol/renderer/Map.js index fc3956f357..261dadcbaf 100644 --- a/src/ol/renderer/Map.js +++ b/src/ol/renderer/Map.js @@ -20,7 +20,7 @@ import _ol_transform_ from '../transform.js'; * @param {ol.PluggableMap} map Map. * @struct */ -var MapRenderer = function(container, map) { +const MapRenderer = function(container, map) { Disposable.call(this); @@ -53,18 +53,18 @@ inherits(MapRenderer, Disposable); * @protected */ MapRenderer.prototype.calculateMatrices2D = function(frameState) { - var viewState = frameState.viewState; - var coordinateToPixelTransform = frameState.coordinateToPixelTransform; - var pixelToCoordinateTransform = frameState.pixelToCoordinateTransform; + const viewState = frameState.viewState; + const coordinateToPixelTransform = frameState.coordinateToPixelTransform; + const pixelToCoordinateTransform = frameState.pixelToCoordinateTransform; _ol_transform_.compose(coordinateToPixelTransform, - frameState.size[0] / 2, frameState.size[1] / 2, - 1 / viewState.resolution, -1 / viewState.resolution, - -viewState.rotation, - -viewState.center[0], -viewState.center[1]); + frameState.size[0] / 2, frameState.size[1] / 2, + 1 / viewState.resolution, -1 / viewState.resolution, + -viewState.rotation, + -viewState.center[0], -viewState.center[1]); _ol_transform_.invert( - _ol_transform_.setFromArray(pixelToCoordinateTransform, coordinateToPixelTransform)); + _ol_transform_.setFromArray(pixelToCoordinateTransform, coordinateToPixelTransform)); }; @@ -72,7 +72,7 @@ MapRenderer.prototype.calculateMatrices2D = function(frameState) { * Removes all layer renderers. */ MapRenderer.prototype.removeLayerRenderers = function() { - for (var key in this.layerRenderers_) { + for (const key in this.layerRenderers_) { this.removeLayerRendererByKey_(key).dispose(); } }; @@ -104,10 +104,10 @@ MapRenderer.expireIconCache_ = function(map, frameState) { * @template S,T,U */ MapRenderer.prototype.forEachFeatureAtCoordinate = function(coordinate, frameState, hitTolerance, callback, thisArg, - layerFilter, thisArg2) { - var result; - var viewState = frameState.viewState; - var viewResolution = viewState.resolution; + layerFilter, thisArg2) { + let result; + const viewState = frameState.viewState; + const viewResolution = viewState.resolution; /** * @param {ol.Feature|ol.render.Feature} feature Feature. @@ -115,39 +115,39 @@ MapRenderer.prototype.forEachFeatureAtCoordinate = function(coordinate, frameSta * @return {?} Callback result. */ function forEachFeatureAtCoordinate(feature, layer) { - var key = getUid(feature).toString(); - var managed = frameState.layerStates[getUid(layer)].managed; + const key = getUid(feature).toString(); + const managed = frameState.layerStates[getUid(layer)].managed; if (!(key in frameState.skippedFeatureUids && !managed)) { return callback.call(thisArg, feature, managed ? layer : null); } } - var projection = viewState.projection; + const projection = viewState.projection; - var translatedCoordinate = coordinate; + let translatedCoordinate = coordinate; if (projection.canWrapX()) { - var projectionExtent = projection.getExtent(); - var worldWidth = getWidth(projectionExtent); - var x = coordinate[0]; + const projectionExtent = projection.getExtent(); + const worldWidth = getWidth(projectionExtent); + const x = coordinate[0]; if (x < projectionExtent[0] || x > projectionExtent[2]) { - var worldsAway = Math.ceil((projectionExtent[0] - x) / worldWidth); + const worldsAway = Math.ceil((projectionExtent[0] - x) / worldWidth); translatedCoordinate = [x + worldWidth * worldsAway, coordinate[1]]; } } - var layerStates = frameState.layerStatesArray; - var numLayers = layerStates.length; - var i; + const layerStates = frameState.layerStatesArray; + const numLayers = layerStates.length; + let i; for (i = numLayers - 1; i >= 0; --i) { - var layerState = layerStates[i]; - var layer = layerState.layer; + const layerState = layerStates[i]; + const layer = layerState.layer; if (Layer.visibleAtResolution(layerState, viewResolution) && layerFilter.call(thisArg2, layer)) { - var layerRenderer = this.getLayerRenderer(layer); + const layerRenderer = this.getLayerRenderer(layer); if (layer.getSource()) { result = layerRenderer.forEachFeatureAtCoordinate( - layer.getSource().getWrapX() ? translatedCoordinate : coordinate, - frameState, hitTolerance, forEachFeatureAtCoordinate, thisArg); + layer.getSource().getWrapX() ? translatedCoordinate : coordinate, + frameState, hitTolerance, forEachFeatureAtCoordinate, thisArg); } if (result) { return result; @@ -174,7 +174,7 @@ MapRenderer.prototype.forEachFeatureAtCoordinate = function(coordinate, frameSta * @template S,T,U */ MapRenderer.prototype.forEachLayerAtPixel = function(pixel, frameState, callback, thisArg, - layerFilter, thisArg2) {}; + layerFilter, thisArg2) {}; /** @@ -190,8 +190,8 @@ MapRenderer.prototype.forEachLayerAtPixel = function(pixel, frameState, callback * @template U */ MapRenderer.prototype.hasFeatureAtCoordinate = function(coordinate, frameState, hitTolerance, layerFilter, thisArg) { - var hasFeature = this.forEachFeatureAtCoordinate( - coordinate, frameState, hitTolerance, TRUE, this, layerFilter, thisArg); + const hasFeature = this.forEachFeatureAtCoordinate( + coordinate, frameState, hitTolerance, TRUE, this, layerFilter, thisArg); return hasFeature !== undefined; }; @@ -203,15 +203,15 @@ MapRenderer.prototype.hasFeatureAtCoordinate = function(coordinate, frameState, * @return {ol.renderer.Layer} Layer renderer. */ MapRenderer.prototype.getLayerRenderer = function(layer) { - var layerKey = getUid(layer).toString(); + const layerKey = getUid(layer).toString(); if (layerKey in this.layerRenderers_) { return this.layerRenderers_[layerKey]; } else { - var layerRendererPlugins = getLayerRendererPlugins(); - var renderer; - var type = this.getType(); - for (var i = 0, ii = layerRendererPlugins.length; i < ii; ++i) { - var plugin = layerRendererPlugins[i]; + const layerRendererPlugins = getLayerRendererPlugins(); + let renderer; + const type = this.getType(); + for (let i = 0, ii = layerRendererPlugins.length; i < ii; ++i) { + const plugin = layerRendererPlugins[i]; if (plugin['handles'](type, layer)) { renderer = plugin['create'](this, layer); break; @@ -220,7 +220,7 @@ MapRenderer.prototype.getLayerRenderer = function(layer) { if (renderer) { this.layerRenderers_[layerKey] = renderer; this.layerRendererListeners_[layerKey] = _ol_events_.listen(renderer, - EventType.CHANGE, this.handleLayerRendererChange_, this); + EventType.CHANGE, this.handleLayerRendererChange_, this); } else { throw new Error('Unable to create renderer for layer: ' + layer.getType()); } @@ -278,7 +278,7 @@ MapRenderer.prototype.handleLayerRendererChange_ = function() { * @private */ MapRenderer.prototype.removeLayerRendererByKey_ = function(layerKey) { - var layerRenderer = this.layerRenderers_[layerKey]; + const layerRenderer = this.layerRenderers_[layerKey]; delete this.layerRenderers_[layerKey]; _ol_events_.unlistenByKey(this.layerRendererListeners_[layerKey]); @@ -301,7 +301,7 @@ MapRenderer.prototype.renderFrame = nullFunction; * @private */ MapRenderer.prototype.removeUnusedLayerRenderers_ = function(map, frameState) { - var layerKey; + let layerKey; for (layerKey in this.layerRenderers_) { if (!frameState || !(layerKey in frameState.layerStates)) { this.removeLayerRendererByKey_(layerKey).dispose(); @@ -316,7 +316,7 @@ MapRenderer.prototype.removeUnusedLayerRenderers_ = function(map, frameState) { */ MapRenderer.prototype.scheduleExpireIconCache = function(frameState) { frameState.postRenderFunctions.push( - /** @type {ol.PostRenderFunction} */ (MapRenderer.expireIconCache_) + /** @type {ol.PostRenderFunction} */ (MapRenderer.expireIconCache_) ); }; @@ -326,11 +326,11 @@ MapRenderer.prototype.scheduleExpireIconCache = function(frameState) { * @protected */ MapRenderer.prototype.scheduleRemoveUnusedLayerRenderers = function(frameState) { - var layerKey; + let layerKey; for (layerKey in this.layerRenderers_) { if (!(layerKey in frameState.layerStates)) { frameState.postRenderFunctions.push( - /** @type {ol.PostRenderFunction} */ (this.removeUnusedLayerRenderers_.bind(this)) + /** @type {ol.PostRenderFunction} */ (this.removeUnusedLayerRenderers_.bind(this)) ); return; } diff --git a/src/ol/renderer/canvas/ImageLayer.js b/src/ol/renderer/canvas/ImageLayer.js index 84e04f9e68..3a5f3b18da 100644 --- a/src/ol/renderer/canvas/ImageLayer.js +++ b/src/ol/renderer/canvas/ImageLayer.js @@ -21,7 +21,7 @@ import _ol_transform_ from '../../transform.js'; * @param {ol.layer.Image} imageLayer Single image layer. * @api */ -var CanvasImageLayerRenderer = function(imageLayer) { +const CanvasImageLayerRenderer = function(imageLayer) { IntermediateCanvasRenderer.call(this, imageLayer); @@ -73,11 +73,11 @@ CanvasImageLayerRenderer['handles'] = function(type, layer) { * @return {ol.renderer.canvas.ImageLayer} The layer renderer. */ CanvasImageLayerRenderer['create'] = function(mapRenderer, layer) { - var renderer = new CanvasImageLayerRenderer(/** @type {ol.layer.Image} */ (layer)); + const renderer = new CanvasImageLayerRenderer(/** @type {ol.layer.Image} */ (layer)); if (layer.getType() === LayerType.VECTOR) { - var candidates = getLayerRendererPlugins(); - for (var i = 0, ii = candidates.length; i < ii; ++i) { - var candidate = /** @type {Object.} */ (candidates[i]); + const candidates = getLayerRendererPlugins(); + for (let i = 0, ii = candidates.length; i < ii; ++i) { + const candidate = /** @type {Object.} */ (candidates[i]); if (candidate !== CanvasImageLayerRenderer && candidate['handles'](RendererType.CANVAS, layer)) { renderer.setVectorRenderer(candidate['create'](mapRenderer, layer)); } @@ -108,36 +108,36 @@ CanvasImageLayerRenderer.prototype.getImageTransform = function() { */ CanvasImageLayerRenderer.prototype.prepareFrame = function(frameState, layerState) { - var pixelRatio = frameState.pixelRatio; - var size = frameState.size; - var viewState = frameState.viewState; - var viewCenter = viewState.center; - var viewResolution = viewState.resolution; + const pixelRatio = frameState.pixelRatio; + const size = frameState.size; + const viewState = frameState.viewState; + const viewCenter = viewState.center; + const viewResolution = viewState.resolution; - var image; - var imageLayer = /** @type {ol.layer.Image} */ (this.getLayer()); - var imageSource = imageLayer.getSource(); + let image; + const imageLayer = /** @type {ol.layer.Image} */ (this.getLayer()); + const imageSource = imageLayer.getSource(); - var hints = frameState.viewHints; + const hints = frameState.viewHints; - var renderedExtent = frameState.extent; + let renderedExtent = frameState.extent; if (layerState.extent !== undefined) { renderedExtent = getIntersection(renderedExtent, layerState.extent); } if (!hints[ViewHint.ANIMATING] && !hints[ViewHint.INTERACTING] && !isEmpty(renderedExtent)) { - var projection = viewState.projection; + let projection = viewState.projection; if (!ENABLE_RASTER_REPROJECTION) { - var sourceProjection = imageSource.getProjection(); + const sourceProjection = imageSource.getProjection(); if (sourceProjection) { projection = sourceProjection; } } - var vectorRenderer = this.vectorRenderer_; + const vectorRenderer = this.vectorRenderer_; if (vectorRenderer) { - var context = vectorRenderer.context; - var imageFrameState = /** @type {olx.FrameState} */ (_ol_obj_.assign({}, frameState, { + const context = vectorRenderer.context; + const imageFrameState = /** @type {olx.FrameState} */ (_ol_obj_.assign({}, frameState, { size: [ getWidth(renderedExtent) / viewResolution, getHeight(renderedExtent) / viewResolution @@ -146,7 +146,7 @@ CanvasImageLayerRenderer.prototype.prepareFrame = function(frameState, layerStat rotation: 0 })) })); - var skippedFeatures = Object.keys(imageFrameState.skippedFeatureUids).sort(); + const skippedFeatures = Object.keys(imageFrameState.skippedFeatureUids).sort(); if (vectorRenderer.prepareFrame(imageFrameState, layerState) && (vectorRenderer.replayGroupChanged || !equals(skippedFeatures, this.skippedFeatures_))) { @@ -158,9 +158,9 @@ CanvasImageLayerRenderer.prototype.prepareFrame = function(frameState, layerStat } } else { image = imageSource.getImage( - renderedExtent, viewResolution, pixelRatio, projection); + renderedExtent, viewResolution, pixelRatio, projection); if (image) { - var loaded = this.loadImage(image); + const loaded = this.loadImage(image); if (loaded) { this.image_ = image; } @@ -170,22 +170,22 @@ CanvasImageLayerRenderer.prototype.prepareFrame = function(frameState, layerStat if (this.image_) { image = this.image_; - var imageExtent = image.getExtent(); - var imageResolution = image.getResolution(); - var imagePixelRatio = image.getPixelRatio(); - var scale = pixelRatio * imageResolution / + const imageExtent = image.getExtent(); + const imageResolution = image.getResolution(); + const imagePixelRatio = image.getPixelRatio(); + const scale = pixelRatio * imageResolution / (viewResolution * imagePixelRatio); - var transform = _ol_transform_.compose(this.imageTransform_, - pixelRatio * size[0] / 2, pixelRatio * size[1] / 2, - scale, scale, - 0, - imagePixelRatio * (imageExtent[0] - viewCenter[0]) / imageResolution, - imagePixelRatio * (viewCenter[1] - imageExtent[3]) / imageResolution); + const transform = _ol_transform_.compose(this.imageTransform_, + pixelRatio * size[0] / 2, pixelRatio * size[1] / 2, + scale, scale, + 0, + imagePixelRatio * (imageExtent[0] - viewCenter[0]) / imageResolution, + imagePixelRatio * (viewCenter[1] - imageExtent[3]) / imageResolution); _ol_transform_.compose(this.coordinateToCanvasPixelTransform, - pixelRatio * size[0] / 2 - transform[4], pixelRatio * size[1] / 2 - transform[5], - pixelRatio / viewResolution, -pixelRatio / viewResolution, - 0, - -viewCenter[0], -viewCenter[1]); + pixelRatio * size[0] / 2 - transform[4], pixelRatio * size[1] / 2 - transform[5], + pixelRatio / viewResolution, -pixelRatio / viewResolution, + 0, + -viewCenter[0], -viewCenter[1]); this.renderedResolution = imageResolution * pixelRatio / imagePixelRatio; } diff --git a/src/ol/renderer/canvas/IntermediateCanvas.js b/src/ol/renderer/canvas/IntermediateCanvas.js index a3f1827ddf..a240d57da2 100644 --- a/src/ol/renderer/canvas/IntermediateCanvas.js +++ b/src/ol/renderer/canvas/IntermediateCanvas.js @@ -14,7 +14,7 @@ import _ol_transform_ from '../../transform.js'; * @extends {ol.renderer.canvas.Layer} * @param {ol.layer.Layer} layer Layer. */ -var IntermediateCanvasRenderer = function(layer) { +const IntermediateCanvasRenderer = function(layer) { CanvasLayerRenderer.call(this, layer); @@ -42,33 +42,33 @@ IntermediateCanvasRenderer.prototype.composeFrame = function(frameState, layerSt this.preCompose(context, frameState); - var image = this.getImage(); + const image = this.getImage(); if (image) { // clipped rendering if layer extent is set - var extent = layerState.extent; - var clipped = extent !== undefined && + const extent = layerState.extent; + const clipped = extent !== undefined && !containsExtent(extent, frameState.extent) && intersects(extent, frameState.extent); if (clipped) { this.clip(context, frameState, /** @type {ol.Extent} */ (extent)); } - var imageTransform = this.getImageTransform(); + const imageTransform = this.getImageTransform(); // for performance reasons, context.save / context.restore is not used // to save and restore the transformation matrix and the opacity. // see http://jsperf.com/context-save-restore-versus-variable - var alpha = context.globalAlpha; + const alpha = context.globalAlpha; context.globalAlpha = layerState.opacity; // for performance reasons, context.setTransform is only used // when the view is rotated. see http://jsperf.com/canvas-transform - var dx = imageTransform[4]; - var dy = imageTransform[5]; - var dw = image.width * imageTransform[0]; - var dh = image.height * imageTransform[3]; + const dx = imageTransform[4]; + const dy = imageTransform[5]; + const dw = image.width * imageTransform[0]; + const dh = image.height * imageTransform[3]; context.drawImage(image, 0, 0, +image.width, +image.height, - Math.round(dx), Math.round(dy), Math.round(dw), Math.round(dh)); + Math.round(dx), Math.round(dy), Math.round(dw), Math.round(dh)); context.globalAlpha = alpha; if (clipped) { @@ -98,20 +98,20 @@ IntermediateCanvasRenderer.prototype.getImageTransform = function() {}; * @inheritDoc */ IntermediateCanvasRenderer.prototype.forEachFeatureAtCoordinate = function(coordinate, frameState, hitTolerance, callback, thisArg) { - var layer = this.getLayer(); - var source = layer.getSource(); - var resolution = frameState.viewState.resolution; - var rotation = frameState.viewState.rotation; - var skippedFeatureUids = frameState.skippedFeatureUids; + const layer = this.getLayer(); + const source = layer.getSource(); + const resolution = frameState.viewState.resolution; + const rotation = frameState.viewState.rotation; + const skippedFeatureUids = frameState.skippedFeatureUids; return source.forEachFeatureAtCoordinate( - coordinate, resolution, rotation, hitTolerance, skippedFeatureUids, - /** + coordinate, resolution, rotation, hitTolerance, skippedFeatureUids, + /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @return {?} Callback result. */ - function(feature) { - return callback.call(thisArg, feature, layer); - }); + function(feature) { + return callback.call(thisArg, feature, layer); + }); }; @@ -128,7 +128,7 @@ IntermediateCanvasRenderer.prototype.forEachLayerAtCoordinate = function(coordin // so that for example also transparent polygons are detected return CanvasLayerRenderer.prototype.forEachLayerAtCoordinate.apply(this, arguments); } else { - var pixel = _ol_transform_.apply(this.coordinateToCanvasPixelTransform, coordinate.slice()); + const pixel = _ol_transform_.apply(this.coordinateToCanvasPixelTransform, coordinate.slice()); _ol_coordinate_.scale(pixel, frameState.viewState.resolution / this.renderedResolution); if (!this.hitCanvasContext_) { @@ -138,7 +138,7 @@ IntermediateCanvasRenderer.prototype.forEachLayerAtCoordinate = function(coordin this.hitCanvasContext_.clearRect(0, 0, 1, 1); this.hitCanvasContext_.drawImage(this.getImage(), pixel[0], pixel[1], 1, 1, 0, 0, 1, 1); - var imageData = this.hitCanvasContext_.getImageData(0, 0, 1, 1).data; + const imageData = this.hitCanvasContext_.getImageData(0, 0, 1, 1).data; if (imageData[3] > 0) { return callback.call(thisArg, this.getLayer(), imageData); } else { diff --git a/src/ol/renderer/canvas/Layer.js b/src/ol/renderer/canvas/Layer.js index 52b9c5c723..eca2a6320b 100644 --- a/src/ol/renderer/canvas/Layer.js +++ b/src/ol/renderer/canvas/Layer.js @@ -17,7 +17,7 @@ import _ol_transform_ from '../../transform.js'; * @extends {ol.renderer.Layer} * @param {ol.layer.Layer} layer Layer. */ -var CanvasLayerRenderer = function(layer) { +const CanvasLayerRenderer = function(layer) { LayerRenderer.call(this, layer); @@ -45,14 +45,14 @@ inherits(CanvasLayerRenderer, LayerRenderer); * @protected */ CanvasLayerRenderer.prototype.clip = function(context, frameState, extent) { - var pixelRatio = frameState.pixelRatio; - var width = frameState.size[0] * pixelRatio; - var height = frameState.size[1] * pixelRatio; - var rotation = frameState.viewState.rotation; - var topLeft = getTopLeft(/** @type {ol.Extent} */ (extent)); - var topRight = getTopRight(/** @type {ol.Extent} */ (extent)); - var bottomRight = getBottomRight(/** @type {ol.Extent} */ (extent)); - var bottomLeft = getBottomLeft(/** @type {ol.Extent} */ (extent)); + const pixelRatio = frameState.pixelRatio; + const width = frameState.size[0] * pixelRatio; + const height = frameState.size[1] * pixelRatio; + const rotation = frameState.viewState.rotation; + const topLeft = getTopLeft(/** @type {ol.Extent} */ (extent)); + const topRight = getTopRight(/** @type {ol.Extent} */ (extent)); + const bottomRight = getBottomRight(/** @type {ol.Extent} */ (extent)); + const bottomLeft = getBottomLeft(/** @type {ol.Extent} */ (extent)); _ol_transform_.apply(frameState.coordinateToPixelTransform, topLeft); _ol_transform_.apply(frameState.coordinateToPixelTransform, topRight); @@ -79,19 +79,19 @@ CanvasLayerRenderer.prototype.clip = function(context, frameState, extent) { * @private */ CanvasLayerRenderer.prototype.dispatchComposeEvent_ = function(type, context, frameState, opt_transform) { - var layer = this.getLayer(); + const layer = this.getLayer(); if (layer.hasListener(type)) { - var width = frameState.size[0] * frameState.pixelRatio; - var height = frameState.size[1] * frameState.pixelRatio; - var rotation = frameState.viewState.rotation; + const width = frameState.size[0] * frameState.pixelRatio; + const height = frameState.size[1] * frameState.pixelRatio; + const rotation = frameState.viewState.rotation; _ol_render_canvas_.rotateAtOffset(context, -rotation, width / 2, height / 2); - var transform = opt_transform !== undefined ? + const transform = opt_transform !== undefined ? opt_transform : this.getTransform(frameState, 0); - var render = new CanvasImmediateRenderer( - context, frameState.pixelRatio, frameState.extent, transform, - frameState.viewState.rotation); - var composeEvent = new RenderEvent(type, render, frameState, - context, null); + const render = new CanvasImmediateRenderer( + context, frameState.pixelRatio, frameState.extent, transform, + frameState.viewState.rotation); + const composeEvent = new RenderEvent(type, render, frameState, + context, null); layer.dispatchEvent(composeEvent); _ol_render_canvas_.rotateAtOffset(context, rotation, width / 2, height / 2); } @@ -108,7 +108,7 @@ CanvasLayerRenderer.prototype.dispatchComposeEvent_ = function(type, context, fr * @template S,T,U */ CanvasLayerRenderer.prototype.forEachLayerAtCoordinate = function(coordinate, frameState, callback, thisArg) { - var hasFeature = this.forEachFeatureAtCoordinate(coordinate, frameState, 0, TRUE, this); + const hasFeature = this.forEachFeatureAtCoordinate(coordinate, frameState, 0, TRUE, this); if (hasFeature) { return callback.call(thisArg, this.getLayer(), null); @@ -159,15 +159,15 @@ CanvasLayerRenderer.prototype.dispatchRenderEvent = function(context, frameState * @return {!ol.Transform} Transform. */ CanvasLayerRenderer.prototype.getTransform = function(frameState, offsetX) { - var viewState = frameState.viewState; - var pixelRatio = frameState.pixelRatio; - var dx1 = pixelRatio * frameState.size[0] / 2; - var dy1 = pixelRatio * frameState.size[1] / 2; - var sx = pixelRatio / viewState.resolution; - var sy = -sx; - var angle = -viewState.rotation; - var dx2 = -viewState.center[0] + offsetX; - var dy2 = -viewState.center[1]; + const viewState = frameState.viewState; + const pixelRatio = frameState.pixelRatio; + const dx1 = pixelRatio * frameState.size[0] / 2; + const dy1 = pixelRatio * frameState.size[1] / 2; + const sx = pixelRatio / viewState.resolution; + const sy = -sx; + const angle = -viewState.rotation; + const dx2 = -viewState.center[0] + offsetX; + const dy2 = -viewState.center[1]; return _ol_transform_.compose(this.transform_, dx1, dy1, sx, sy, angle, dx2, dy2); }; diff --git a/src/ol/renderer/canvas/Map.js b/src/ol/renderer/canvas/Map.js index eea47a7186..0b655c7c0e 100644 --- a/src/ol/renderer/canvas/Map.js +++ b/src/ol/renderer/canvas/Map.js @@ -24,7 +24,7 @@ import SourceState from '../../source/State.js'; * @param {ol.PluggableMap} map Map. * @api */ -var CanvasMapRenderer = function(container, map) { +const CanvasMapRenderer = function(container, map) { MapRenderer.call(this, container, map); @@ -90,20 +90,20 @@ CanvasMapRenderer['create'] = function(container, map) { * @private */ CanvasMapRenderer.prototype.dispatchComposeEvent_ = function(type, frameState) { - var map = this.getMap(); - var context = this.context_; + const map = this.getMap(); + const context = this.context_; if (map.hasListener(type)) { - var extent = frameState.extent; - var pixelRatio = frameState.pixelRatio; - var viewState = frameState.viewState; - var rotation = viewState.rotation; + const extent = frameState.extent; + const pixelRatio = frameState.pixelRatio; + const viewState = frameState.viewState; + const rotation = viewState.rotation; - var transform = this.getTransform(frameState); + const transform = this.getTransform(frameState); - var vectorContext = new CanvasImmediateRenderer(context, pixelRatio, - extent, transform, rotation); - var composeEvent = new RenderEvent(type, vectorContext, - frameState, context, null); + const vectorContext = new CanvasImmediateRenderer(context, pixelRatio, + extent, transform, rotation); + const composeEvent = new RenderEvent(type, vectorContext, + frameState, context, null); map.dispatchEvent(composeEvent); } }; @@ -115,14 +115,14 @@ CanvasMapRenderer.prototype.dispatchComposeEvent_ = function(type, frameState) { * @return {!ol.Transform} Transform. */ CanvasMapRenderer.prototype.getTransform = function(frameState) { - var viewState = frameState.viewState; - var dx1 = this.canvas_.width / 2; - var dy1 = this.canvas_.height / 2; - var sx = frameState.pixelRatio / viewState.resolution; - var sy = -sx; - var angle = -viewState.rotation; - var dx2 = -viewState.center[0]; - var dy2 = -viewState.center[1]; + const viewState = frameState.viewState; + const dx1 = this.canvas_.width / 2; + const dy1 = this.canvas_.height / 2; + const sx = frameState.pixelRatio / viewState.resolution; + const sy = -sx; + const angle = -viewState.rotation; + const dx2 = -viewState.center[0]; + const dy2 = -viewState.center[1]; return _ol_transform_.compose(this.transform_, dx1, dy1, sx, sy, angle, dx2, dy2); }; @@ -148,10 +148,10 @@ CanvasMapRenderer.prototype.renderFrame = function(frameState) { return; } - var context = this.context_; - var pixelRatio = frameState.pixelRatio; - var width = Math.round(frameState.size[0] * pixelRatio); - var height = Math.round(frameState.size[1] * pixelRatio); + const context = this.context_; + const pixelRatio = frameState.pixelRatio; + const width = Math.round(frameState.size[0] * pixelRatio); + const height = Math.round(frameState.size[1] * pixelRatio); if (this.canvas_.width != width || this.canvas_.height != height) { this.canvas_.width = width; this.canvas_.height = height; @@ -159,13 +159,13 @@ CanvasMapRenderer.prototype.renderFrame = function(frameState) { context.clearRect(0, 0, width, height); } - var rotation = frameState.viewState.rotation; + const rotation = frameState.viewState.rotation; this.calculateMatrices2D(frameState); this.dispatchComposeEvent_(RenderEventType.PRECOMPOSE, frameState); - var layerStatesArray = frameState.layerStatesArray; + const layerStatesArray = frameState.layerStatesArray; stableSort(layerStatesArray, MapRenderer.sortByZIndex); if (rotation) { @@ -173,8 +173,8 @@ CanvasMapRenderer.prototype.renderFrame = function(frameState) { _ol_render_canvas_.rotateAtOffset(context, rotation, width / 2, height / 2); } - var viewResolution = frameState.viewState.resolution; - var i, ii, layer, layerRenderer, layerState; + const viewResolution = frameState.viewState.resolution; + let i, ii, layer, layerRenderer, layerState; for (i = 0, ii = layerStatesArray.length; i < ii; ++i) { layerState = layerStatesArray[i]; layer = layerState.layer; @@ -208,26 +208,26 @@ CanvasMapRenderer.prototype.renderFrame = function(frameState) { * @inheritDoc */ CanvasMapRenderer.prototype.forEachLayerAtPixel = function(pixel, frameState, callback, thisArg, - layerFilter, thisArg2) { - var result; - var viewState = frameState.viewState; - var viewResolution = viewState.resolution; + layerFilter, thisArg2) { + let result; + const viewState = frameState.viewState; + const viewResolution = viewState.resolution; - var layerStates = frameState.layerStatesArray; - var numLayers = layerStates.length; + const layerStates = frameState.layerStatesArray; + const numLayers = layerStates.length; - var coordinate = _ol_transform_.apply( - frameState.pixelToCoordinateTransform, pixel.slice()); + const coordinate = _ol_transform_.apply( + frameState.pixelToCoordinateTransform, pixel.slice()); - var i; + let i; for (i = numLayers - 1; i >= 0; --i) { - var layerState = layerStates[i]; - var layer = layerState.layer; + const layerState = layerStates[i]; + const layer = layerState.layer; if (Layer.visibleAtResolution(layerState, viewResolution) && layerFilter.call(thisArg2, layer)) { - var layerRenderer = /** @type {ol.renderer.canvas.Layer} */ (this.getLayerRenderer(layer)); + const layerRenderer = /** @type {ol.renderer.canvas.Layer} */ (this.getLayerRenderer(layer)); result = layerRenderer.forEachLayerAtCoordinate( - coordinate, frameState, callback, thisArg); + coordinate, frameState, callback, thisArg); if (result) { return result; } diff --git a/src/ol/renderer/canvas/TileLayer.js b/src/ol/renderer/canvas/TileLayer.js index b848a5b6b6..d845ed31d1 100644 --- a/src/ol/renderer/canvas/TileLayer.js +++ b/src/ol/renderer/canvas/TileLayer.js @@ -18,7 +18,7 @@ import _ol_transform_ from '../../transform.js'; * @param {ol.layer.Tile|ol.layer.VectorTile} tileLayer Tile layer. * @api */ -var CanvasTileLayerRenderer = function(tileLayer) { +const CanvasTileLayerRenderer = function(tileLayer) { IntermediateCanvasRenderer.call(this, tileLayer); @@ -109,8 +109,8 @@ CanvasTileLayerRenderer['create'] = function(mapRenderer, layer) { * @return {boolean} Tile is drawable. */ CanvasTileLayerRenderer.prototype.isDrawableTile_ = function(tile) { - var tileState = tile.getState(); - var useInterimTilesOnError = this.getLayer().getUseInterimTilesOnError(); + const tileState = tile.getState(); + const useInterimTilesOnError = this.getLayer().getUseInterimTilesOnError(); return tileState == TileState.LOADED || tileState == TileState.EMPTY || tileState == TileState.ERROR && !useInterimTilesOnError; @@ -121,21 +121,21 @@ CanvasTileLayerRenderer.prototype.isDrawableTile_ = function(tile) { */ CanvasTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState) { - var pixelRatio = frameState.pixelRatio; - var size = frameState.size; - var viewState = frameState.viewState; - var projection = viewState.projection; - var viewResolution = viewState.resolution; - var viewCenter = viewState.center; + const pixelRatio = frameState.pixelRatio; + const size = frameState.size; + const viewState = frameState.viewState; + const projection = viewState.projection; + const viewResolution = viewState.resolution; + const viewCenter = viewState.center; - var tileLayer = this.getLayer(); - var tileSource = /** @type {ol.source.Tile} */ (tileLayer.getSource()); - var sourceRevision = tileSource.getRevision(); - var tileGrid = tileSource.getTileGridForProjection(projection); - var z = tileGrid.getZForResolution(viewResolution, this.zDirection); - var tileResolution = tileGrid.getResolution(z); - var oversampling = Math.round(viewResolution / tileResolution) || 1; - var extent = frameState.extent; + const tileLayer = this.getLayer(); + const tileSource = /** @type {ol.source.Tile} */ (tileLayer.getSource()); + const sourceRevision = tileSource.getRevision(); + const tileGrid = tileSource.getTileGridForProjection(projection); + const z = tileGrid.getZForResolution(viewResolution, this.zDirection); + const tileResolution = tileGrid.getResolution(z); + let oversampling = Math.round(viewResolution / tileResolution) || 1; + let extent = frameState.extent; if (layerState.extent !== undefined) { extent = getIntersection(extent, layerState.extent); @@ -145,24 +145,24 @@ CanvasTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState return false; } - var tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z); - var imageExtent = tileGrid.getTileRangeExtent(z, tileRange); + const tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z); + const imageExtent = tileGrid.getTileRangeExtent(z, tileRange); - var tilePixelRatio = tileSource.getTilePixelRatio(pixelRatio); + const tilePixelRatio = tileSource.getTilePixelRatio(pixelRatio); /** * @type {Object.>} */ - var tilesToDrawByZ = {}; + const tilesToDrawByZ = {}; tilesToDrawByZ[z] = {}; - var findLoadedTiles = this.createLoadedTileFinder( - tileSource, projection, tilesToDrawByZ); + const findLoadedTiles = this.createLoadedTileFinder( + tileSource, projection, tilesToDrawByZ); - var tmpExtent = this.tmpExtent; - var tmpTileRange = this.tmpTileRange_; - var newTiles = false; - var tile, x, y; + const tmpExtent = this.tmpExtent; + const tmpTileRange = this.tmpTileRange_; + let newTiles = false; + let tile, x, y; for (x = tileRange.minX; x <= tileRange.maxX; ++x) { for (y = tileRange.minY; y <= tileRange.maxY; ++y) { tile = tileSource.getTile(z, x, y, pixelRatio, projection); @@ -179,10 +179,10 @@ CanvasTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState tile = tile.getInterimTile(); } if (this.isDrawableTile_(tile)) { - var uid = getUid(this); + const uid = getUid(this); if (tile.getState() == TileState.LOADED) { tilesToDrawByZ[z][tile.tileCoord.toString()] = tile; - var inTransition = tile.inTransition(uid); + const inTransition = tile.inTransition(uid); if (!newTiles && (inTransition || this.renderedTiles.indexOf(tile) === -1)) { newTiles = true; } @@ -193,23 +193,23 @@ CanvasTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState } } - var childTileRange = tileGrid.getTileCoordChildTileRange( - tile.tileCoord, tmpTileRange, tmpExtent); - var covered = false; + const childTileRange = tileGrid.getTileCoordChildTileRange( + tile.tileCoord, tmpTileRange, tmpExtent); + let covered = false; if (childTileRange) { covered = findLoadedTiles(z + 1, childTileRange); } if (!covered) { tileGrid.forEachTileCoordParentTileRange( - tile.tileCoord, findLoadedTiles, null, tmpTileRange, tmpExtent); + tile.tileCoord, findLoadedTiles, null, tmpTileRange, tmpExtent); } } } - var renderedResolution = tileResolution * pixelRatio / tilePixelRatio * oversampling; - var hints = frameState.viewHints; - var animatingOrInteracting = hints[ViewHint.ANIMATING] || hints[ViewHint.INTERACTING]; + const renderedResolution = tileResolution * pixelRatio / tilePixelRatio * oversampling; + const hints = frameState.viewHints; + const animatingOrInteracting = hints[ViewHint.ANIMATING] || hints[ViewHint.INTERACTING]; if (!(this.renderedResolution && Date.now() - frameState.time > 16 && animatingOrInteracting) && ( newTiles || !(this.renderedExtent_ && containsExtent(this.renderedExtent_, extent)) || @@ -218,12 +218,12 @@ CanvasTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState !animatingOrInteracting && renderedResolution != this.renderedResolution )) { - var context = this.context; + const context = this.context; if (context) { - var tilePixelSize = tileSource.getTilePixelSize(z, pixelRatio, projection); - var width = Math.round(tileRange.getWidth() * tilePixelSize[0] / oversampling); - var height = Math.round(tileRange.getHeight() * tilePixelSize[1] / oversampling); - var canvas = context.canvas; + const tilePixelSize = tileSource.getTilePixelSize(z, pixelRatio, projection); + const width = Math.round(tileRange.getWidth() * tilePixelSize[0] / oversampling); + const height = Math.round(tileRange.getHeight() * tilePixelSize[1] / oversampling); + const canvas = context.canvas; if (canvas.width != width || canvas.height != height) { this.oversampling_ = oversampling; canvas.width = width; @@ -238,7 +238,7 @@ CanvasTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState this.renderedTiles.length = 0; /** @type {Array.} */ - var zs = Object.keys(tilesToDrawByZ).map(Number); + const zs = Object.keys(tilesToDrawByZ).map(Number); zs.sort(function(a, b) { if (a === z) { return 1; @@ -248,8 +248,8 @@ CanvasTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState return a > b ? 1 : a < b ? -1 : 0; } }); - var currentResolution, currentScale, currentTilePixelSize, currentZ, i, ii; - var tileExtent, tileGutter, tilesToDraw, w, h; + let currentResolution, currentScale, currentTilePixelSize, currentZ, i, ii; + let tileExtent, tileGutter, tilesToDraw, w, h; for (i = 0, ii = zs.length; i < ii; ++i) { currentZ = zs[i]; currentTilePixelSize = tileSource.getTilePixelSize(currentZ, pixelRatio, projection); @@ -257,7 +257,7 @@ CanvasTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState currentScale = currentResolution / tileResolution; tileGutter = tilePixelRatio * tileSource.getGutter(projection); tilesToDraw = tilesToDrawByZ[currentZ]; - for (var tileCoordKey in tilesToDraw) { + for (const tileCoordKey in tilesToDraw) { tile = tilesToDraw[tileCoordKey]; tileExtent = tileGrid.getTileCoordExtent(tile.getTileCoord(), tmpExtent); x = (tileExtent[0] - imageExtent[0]) / tileResolution * tilePixelRatio / oversampling; @@ -274,23 +274,23 @@ CanvasTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState this.renderedExtent_ = imageExtent; } - var scale = this.renderedResolution / viewResolution; - var transform = _ol_transform_.compose(this.imageTransform_, - pixelRatio * size[0] / 2, pixelRatio * size[1] / 2, - scale, scale, - 0, - (this.renderedExtent_[0] - viewCenter[0]) / this.renderedResolution * pixelRatio, - (viewCenter[1] - this.renderedExtent_[3]) / this.renderedResolution * pixelRatio); + const scale = this.renderedResolution / viewResolution; + const transform = _ol_transform_.compose(this.imageTransform_, + pixelRatio * size[0] / 2, pixelRatio * size[1] / 2, + scale, scale, + 0, + (this.renderedExtent_[0] - viewCenter[0]) / this.renderedResolution * pixelRatio, + (viewCenter[1] - this.renderedExtent_[3]) / this.renderedResolution * pixelRatio); _ol_transform_.compose(this.coordinateToCanvasPixelTransform, - pixelRatio * size[0] / 2 - transform[4], pixelRatio * size[1] / 2 - transform[5], - pixelRatio / viewResolution, -pixelRatio / viewResolution, - 0, - -viewCenter[0], -viewCenter[1]); + pixelRatio * size[0] / 2 - transform[4], pixelRatio * size[1] / 2 - transform[5], + pixelRatio / viewResolution, -pixelRatio / viewResolution, + 0, + -viewCenter[0], -viewCenter[1]); this.updateUsedTiles(frameState.usedTiles, tileSource, z, tileRange); this.manageTilePyramid(frameState, tileSource, tileGrid, pixelRatio, - projection, extent, z, tileLayer.getPreload()); + projection, extent, z, tileLayer.getPreload()); this.scheduleExpireCache(frameState, tileSource); return this.renderedTiles.length > 0; @@ -309,22 +309,22 @@ CanvasTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState * @param {boolean} transition Apply an alpha transition. */ CanvasTileLayerRenderer.prototype.drawTileImage = function(tile, frameState, layerState, x, y, w, h, gutter, transition) { - var image = tile.getImage(this.getLayer()); + const image = tile.getImage(this.getLayer()); if (!image) { return; } - var uid = getUid(this); - var alpha = transition ? tile.getAlpha(uid, frameState.time) : 1; + const uid = getUid(this); + const alpha = transition ? tile.getAlpha(uid, frameState.time) : 1; if (alpha === 1 && !this.getLayer().getSource().getOpaque(frameState.viewState.projection)) { this.context.clearRect(x, y, w, h); } - var alphaChanged = alpha !== this.context.globalAlpha; + const alphaChanged = alpha !== this.context.globalAlpha; if (alphaChanged) { this.context.save(); this.context.globalAlpha = alpha; } this.context.drawImage(image, gutter, gutter, - image.width - 2 * gutter, image.height - 2 * gutter, x, y, w, h); + image.width - 2 * gutter, image.height - 2 * gutter, x, y, w, h); if (alphaChanged) { this.context.restore(); @@ -341,7 +341,7 @@ CanvasTileLayerRenderer.prototype.drawTileImage = function(tile, frameState, lay * @inheritDoc */ CanvasTileLayerRenderer.prototype.getImage = function() { - var context = this.context; + const context = this.context; return context ? context.canvas : null; }; diff --git a/src/ol/renderer/canvas/VectorLayer.js b/src/ol/renderer/canvas/VectorLayer.js index 5086577d6c..40b6f88193 100644 --- a/src/ol/renderer/canvas/VectorLayer.js +++ b/src/ol/renderer/canvas/VectorLayer.js @@ -22,7 +22,7 @@ import _ol_renderer_vector_ from '../vector.js'; * @param {ol.layer.Vector} vectorLayer Vector layer. * @api */ -var CanvasVectorLayerRenderer = function(vectorLayer) { +const CanvasVectorLayerRenderer = function(vectorLayer) { CanvasLayerRenderer.call(this, vectorLayer); @@ -122,42 +122,42 @@ CanvasVectorLayerRenderer.prototype.disposeInternal = function() { */ CanvasVectorLayerRenderer.prototype.composeFrame = function(frameState, layerState, context) { - var extent = frameState.extent; - var pixelRatio = frameState.pixelRatio; - var skippedFeatureUids = layerState.managed ? + const extent = frameState.extent; + const pixelRatio = frameState.pixelRatio; + const skippedFeatureUids = layerState.managed ? frameState.skippedFeatureUids : {}; - var viewState = frameState.viewState; - var projection = viewState.projection; - var rotation = viewState.rotation; - var projectionExtent = projection.getExtent(); - var vectorSource = /** @type {ol.source.Vector} */ (this.getLayer().getSource()); + const viewState = frameState.viewState; + const projection = viewState.projection; + const rotation = viewState.rotation; + const projectionExtent = projection.getExtent(); + const vectorSource = /** @type {ol.source.Vector} */ (this.getLayer().getSource()); - var transform = this.getTransform(frameState, 0); + let transform = this.getTransform(frameState, 0); this.preCompose(context, frameState, transform); // clipped rendering if layer extent is set - var clipExtent = layerState.extent; - var clipped = clipExtent !== undefined; + const clipExtent = layerState.extent; + const clipped = clipExtent !== undefined; if (clipped) { this.clip(context, frameState, /** @type {ol.Extent} */ (clipExtent)); } - var replayGroup = this.replayGroup_; + const replayGroup = this.replayGroup_; if (replayGroup && !replayGroup.isEmpty()) { if (this.declutterTree_) { this.declutterTree_.clear(); } - var layer = /** @type {ol.layer.Vector} */ (this.getLayer()); - var drawOffsetX = 0; - var drawOffsetY = 0; - var replayContext; - var transparentLayer = layerState.opacity !== 1; - var hasRenderListeners = layer.hasListener(RenderEventType.RENDER); + const layer = /** @type {ol.layer.Vector} */ (this.getLayer()); + let drawOffsetX = 0; + let drawOffsetY = 0; + let replayContext; + const transparentLayer = layerState.opacity !== 1; + const hasRenderListeners = layer.hasListener(RenderEventType.RENDER); if (transparentLayer || hasRenderListeners) { - var drawWidth = context.canvas.width; - var drawHeight = context.canvas.height; + let drawWidth = context.canvas.width; + let drawHeight = context.canvas.height; if (rotation) { - var drawSize = Math.round(Math.sqrt(drawWidth * drawWidth + drawHeight * drawHeight)); + const drawSize = Math.round(Math.sqrt(drawWidth * drawWidth + drawHeight * drawHeight)); drawOffsetX = (drawSize - drawWidth) / 2; drawOffsetY = (drawSize - drawHeight) / 2; drawWidth = drawHeight = drawSize; @@ -170,7 +170,7 @@ CanvasVectorLayerRenderer.prototype.composeFrame = function(frameState, layerSta replayContext = context; } - var alpha = replayContext.globalAlpha; + const alpha = replayContext.globalAlpha; if (!transparentLayer) { // for performance reasons, context.save / context.restore is not used // to save and restore the transformation matrix and the opacity. @@ -182,17 +182,17 @@ CanvasVectorLayerRenderer.prototype.composeFrame = function(frameState, layerSta replayContext.translate(drawOffsetX, drawOffsetY); } - var width = frameState.size[0] * pixelRatio; - var height = frameState.size[1] * pixelRatio; + const width = frameState.size[0] * pixelRatio; + const height = frameState.size[1] * pixelRatio; _ol_render_canvas_.rotateAtOffset(replayContext, -rotation, - width / 2, height / 2); + width / 2, height / 2); replayGroup.replay(replayContext, transform, rotation, skippedFeatureUids); if (vectorSource.getWrapX() && projection.canWrapX() && !containsExtent(projectionExtent, extent)) { - var startX = extent[0]; - var worldWidth = getWidth(projectionExtent); - var world = 0; - var offsetX; + let startX = extent[0]; + const worldWidth = getWidth(projectionExtent); + let world = 0; + let offsetX; while (startX < projectionExtent[0]) { --world; offsetX = worldWidth * world; @@ -213,14 +213,14 @@ CanvasVectorLayerRenderer.prototype.composeFrame = function(frameState, layerSta transform = this.getTransform(frameState, 0); } _ol_render_canvas_.rotateAtOffset(replayContext, rotation, - width / 2, height / 2); + width / 2, height / 2); if (replayContext != context) { if (hasRenderListeners) { this.dispatchRenderEvent(replayContext, frameState, transform); } if (transparentLayer) { - var mainContextAlpha = context.globalAlpha; + const mainContextAlpha = context.globalAlpha; context.globalAlpha = layerState.opacity; context.drawImage(replayContext.canvas, -drawOffsetX, -drawOffsetY); context.globalAlpha = mainContextAlpha; @@ -250,24 +250,24 @@ CanvasVectorLayerRenderer.prototype.forEachFeatureAtCoordinate = function(coordi if (!this.replayGroup_) { return undefined; } else { - var resolution = frameState.viewState.resolution; - var rotation = frameState.viewState.rotation; - var layer = /** @type {ol.layer.Vector} */ (this.getLayer()); + const resolution = frameState.viewState.resolution; + const rotation = frameState.viewState.rotation; + const layer = /** @type {ol.layer.Vector} */ (this.getLayer()); /** @type {Object.} */ - var features = {}; - var result = this.replayGroup_.forEachFeatureAtCoordinate(coordinate, resolution, - rotation, hitTolerance, {}, - /** + const features = {}; + const result = this.replayGroup_.forEachFeatureAtCoordinate(coordinate, resolution, + rotation, hitTolerance, {}, + /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @return {?} Callback result. */ - function(feature) { - var key = getUid(feature).toString(); - if (!(key in features)) { - features[key] = true; - return callback.call(thisArg, feature, layer); - } - }, null); + function(feature) { + const key = getUid(feature).toString(); + if (!(key in features)) { + features[key] = true; + return callback.call(thisArg, feature, layer); + } + }, null); return result; } }; @@ -277,7 +277,7 @@ CanvasVectorLayerRenderer.prototype.forEachFeatureAtCoordinate = function(coordi * @param {ol.events.Event} event Event. */ CanvasVectorLayerRenderer.prototype.handleFontsChanged_ = function(event) { - var layer = this.getLayer(); + const layer = this.getLayer(); if (layer.getVisible() && this.replayGroup_) { layer.changed(); } @@ -298,35 +298,35 @@ CanvasVectorLayerRenderer.prototype.handleStyleImageChange_ = function(event) { * @inheritDoc */ CanvasVectorLayerRenderer.prototype.prepareFrame = function(frameState, layerState) { - var vectorLayer = /** @type {ol.layer.Vector} */ (this.getLayer()); - var vectorSource = vectorLayer.getSource(); + const vectorLayer = /** @type {ol.layer.Vector} */ (this.getLayer()); + const vectorSource = vectorLayer.getSource(); - var animating = frameState.viewHints[ViewHint.ANIMATING]; - var interacting = frameState.viewHints[ViewHint.INTERACTING]; - var updateWhileAnimating = vectorLayer.getUpdateWhileAnimating(); - var updateWhileInteracting = vectorLayer.getUpdateWhileInteracting(); + const animating = frameState.viewHints[ViewHint.ANIMATING]; + const interacting = frameState.viewHints[ViewHint.INTERACTING]; + const updateWhileAnimating = vectorLayer.getUpdateWhileAnimating(); + const updateWhileInteracting = vectorLayer.getUpdateWhileInteracting(); if (!this.dirty_ && (!updateWhileAnimating && animating) || (!updateWhileInteracting && interacting)) { return true; } - var frameStateExtent = frameState.extent; - var viewState = frameState.viewState; - var projection = viewState.projection; - var resolution = viewState.resolution; - var pixelRatio = frameState.pixelRatio; - var vectorLayerRevision = vectorLayer.getRevision(); - var vectorLayerRenderBuffer = vectorLayer.getRenderBuffer(); - var vectorLayerRenderOrder = vectorLayer.getRenderOrder(); + const frameStateExtent = frameState.extent; + const viewState = frameState.viewState; + const projection = viewState.projection; + const resolution = viewState.resolution; + const pixelRatio = frameState.pixelRatio; + const vectorLayerRevision = vectorLayer.getRevision(); + const vectorLayerRenderBuffer = vectorLayer.getRenderBuffer(); + let vectorLayerRenderOrder = vectorLayer.getRenderOrder(); if (vectorLayerRenderOrder === undefined) { vectorLayerRenderOrder = _ol_renderer_vector_.defaultOrder; } - var extent = buffer(frameStateExtent, - vectorLayerRenderBuffer * resolution); - var projectionExtent = viewState.projection.getExtent(); + const extent = buffer(frameStateExtent, + vectorLayerRenderBuffer * resolution); + const projectionExtent = viewState.projection.getExtent(); if (vectorSource.getWrapX() && viewState.projection.canWrapX() && !containsExtent(projectionExtent, frameState.extent)) { @@ -335,8 +335,8 @@ CanvasVectorLayerRenderer.prototype.prepareFrame = function(frameState, layerSta // to +540°, we add at least 1 world width on each side of the projection // extent. If the viewport is wider than the world, we need to add half of // the viewport width to make sure we cover the whole viewport. - var worldWidth = getWidth(projectionExtent); - var gutter = Math.max(getWidth(extent) / 2, worldWidth); + const worldWidth = getWidth(projectionExtent); + const gutter = Math.max(getWidth(extent) / 2, worldWidth); extent[0] = projectionExtent[0] - gutter; extent[2] = projectionExtent[2] + gutter; } @@ -354,17 +354,17 @@ CanvasVectorLayerRenderer.prototype.prepareFrame = function(frameState, layerSta this.dirty_ = false; - var replayGroup = new _ol_render_canvas_ReplayGroup_( - _ol_renderer_vector_.getTolerance(resolution, pixelRatio), extent, resolution, - pixelRatio, vectorSource.getOverlaps(), this.declutterTree_, vectorLayer.getRenderBuffer()); + const replayGroup = new _ol_render_canvas_ReplayGroup_( + _ol_renderer_vector_.getTolerance(resolution, pixelRatio), extent, resolution, + pixelRatio, vectorSource.getOverlaps(), this.declutterTree_, vectorLayer.getRenderBuffer()); vectorSource.loadFeatures(extent, resolution, projection); /** * @param {ol.Feature} feature Feature. * @this {ol.renderer.canvas.VectorLayer} */ - var renderFeature = function(feature) { - var styles; - var styleFunction = feature.getStyleFunction(); + const renderFeature = function(feature) { + let styles; + let styleFunction = feature.getStyleFunction(); if (styleFunction) { styles = styleFunction.call(feature, resolution); } else { @@ -374,23 +374,23 @@ CanvasVectorLayerRenderer.prototype.prepareFrame = function(frameState, layerSta } } if (styles) { - var dirty = this.renderFeature( - feature, resolution, pixelRatio, styles, replayGroup); + const dirty = this.renderFeature( + feature, resolution, pixelRatio, styles, replayGroup); this.dirty_ = this.dirty_ || dirty; } }.bind(this); if (vectorLayerRenderOrder) { /** @type {Array.} */ - var features = []; + const features = []; vectorSource.forEachFeatureInExtent(extent, - /** + /** * @param {ol.Feature} feature Feature. */ - function(feature) { - features.push(feature); - }, this); + function(feature) { + features.push(feature); + }, this); features.sort(vectorLayerRenderOrder); - for (var i = 0, ii = features.length; i < ii; ++i) { + for (let i = 0, ii = features.length; i < ii; ++i) { renderFeature(features[i]); } } else { @@ -422,19 +422,19 @@ CanvasVectorLayerRenderer.prototype.renderFeature = function(feature, resolution if (!styles) { return false; } - var loading = false; + let loading = false; if (Array.isArray(styles)) { - for (var i = 0, ii = styles.length; i < ii; ++i) { + for (let i = 0, ii = styles.length; i < ii; ++i) { loading = _ol_renderer_vector_.renderFeature( - replayGroup, feature, styles[i], - _ol_renderer_vector_.getSquaredTolerance(resolution, pixelRatio), - this.handleStyleImageChange_, this) || loading; + replayGroup, feature, styles[i], + _ol_renderer_vector_.getSquaredTolerance(resolution, pixelRatio), + this.handleStyleImageChange_, this) || loading; } } else { loading = _ol_renderer_vector_.renderFeature( - replayGroup, feature, styles, - _ol_renderer_vector_.getSquaredTolerance(resolution, pixelRatio), - this.handleStyleImageChange_, this); + replayGroup, feature, styles, + _ol_renderer_vector_.getSquaredTolerance(resolution, pixelRatio), + this.handleStyleImageChange_, this); } return loading; }; diff --git a/src/ol/renderer/canvas/VectorTileLayer.js b/src/ol/renderer/canvas/VectorTileLayer.js index e8401edb67..64dd440c24 100644 --- a/src/ol/renderer/canvas/VectorTileLayer.js +++ b/src/ol/renderer/canvas/VectorTileLayer.js @@ -27,7 +27,7 @@ import _ol_transform_ from '../../transform.js'; * @param {ol.layer.VectorTile} layer VectorTile layer. * @api */ -var CanvasVectorTileLayerRenderer = function(layer) { +const CanvasVectorTileLayerRenderer = function(layer) { /** * @type {CanvasRenderingContext2D} @@ -128,11 +128,11 @@ CanvasVectorTileLayerRenderer.prototype.disposeInternal = function() { * @inheritDoc */ CanvasVectorTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState) { - var layer = this.getLayer(); - var layerRevision = layer.getRevision(); + const layer = this.getLayer(); + const layerRevision = layer.getRevision(); if (this.renderedLayerRevision_ != layerRevision) { this.renderedTiles.length = 0; - var renderMode = layer.getRenderMode(); + const renderMode = layer.getRenderMode(); if (!this.context && renderMode != _ol_layer_VectorTileRenderType_.VECTOR) { this.context = createCanvasContext2D(); } @@ -151,57 +151,57 @@ CanvasVectorTileLayerRenderer.prototype.prepareFrame = function(frameState, laye * @private */ CanvasVectorTileLayerRenderer.prototype.createReplayGroup_ = function( - tile, frameState) { - var layer = this.getLayer(); - var pixelRatio = frameState.pixelRatio; - var projection = frameState.viewState.projection; - var revision = layer.getRevision(); - var renderOrder = /** @type {ol.RenderOrderFunction} */ + tile, frameState) { + const layer = this.getLayer(); + const pixelRatio = frameState.pixelRatio; + const projection = frameState.viewState.projection; + const revision = layer.getRevision(); + const renderOrder = /** @type {ol.RenderOrderFunction} */ (layer.getRenderOrder()) || null; - var replayState = tile.getReplayState(layer); + const replayState = tile.getReplayState(layer); if (!replayState.dirty && replayState.renderedRevision == revision && replayState.renderedRenderOrder == renderOrder) { return; } - var source = /** @type {ol.source.VectorTile} */ (layer.getSource()); - var sourceTileGrid = source.getTileGrid(); - var tileGrid = source.getTileGridForProjection(projection); - var resolution = tileGrid.getResolution(tile.tileCoord[0]); - var tileExtent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord); + const source = /** @type {ol.source.VectorTile} */ (layer.getSource()); + const sourceTileGrid = source.getTileGrid(); + const tileGrid = source.getTileGridForProjection(projection); + const resolution = tileGrid.getResolution(tile.tileCoord[0]); + const tileExtent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord); - var zIndexKeys = {}; - for (var t = 0, tt = tile.tileKeys.length; t < tt; ++t) { - var sourceTile = tile.getTile(tile.tileKeys[t]); + const zIndexKeys = {}; + for (let t = 0, tt = tile.tileKeys.length; t < tt; ++t) { + const sourceTile = tile.getTile(tile.tileKeys[t]); if (sourceTile.getState() == TileState.ERROR) { continue; } - var sourceTileCoord = sourceTile.tileCoord; - var sourceTileExtent = sourceTileGrid.getTileCoordExtent(sourceTileCoord); - var sharedExtent = getIntersection(tileExtent, sourceTileExtent); - var bufferedExtent = equals(sourceTileExtent, sharedExtent) ? null : + const sourceTileCoord = sourceTile.tileCoord; + const sourceTileExtent = sourceTileGrid.getTileCoordExtent(sourceTileCoord); + const sharedExtent = getIntersection(tileExtent, sourceTileExtent); + const bufferedExtent = equals(sourceTileExtent, sharedExtent) ? null : buffer(sharedExtent, layer.getRenderBuffer() * resolution); - var tileProjection = sourceTile.getProjection(); - var reproject = false; + const tileProjection = sourceTile.getProjection(); + let reproject = false; if (!equivalentProjection(projection, tileProjection)) { reproject = true; sourceTile.setProjection(projection); } replayState.dirty = false; - var replayGroup = new _ol_render_canvas_ReplayGroup_(0, sharedExtent, resolution, - pixelRatio, source.getOverlaps(), this.declutterTree_, layer.getRenderBuffer()); - var squaredTolerance = _ol_renderer_vector_.getSquaredTolerance( - resolution, pixelRatio); + const replayGroup = new _ol_render_canvas_ReplayGroup_(0, sharedExtent, resolution, + pixelRatio, source.getOverlaps(), this.declutterTree_, layer.getRenderBuffer()); + const squaredTolerance = _ol_renderer_vector_.getSquaredTolerance( + resolution, pixelRatio); /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @this {ol.renderer.canvas.VectorTileLayer} */ - var renderFeature = function(feature) { - var styles; - var styleFunction = feature.getStyleFunction(); + const renderFeature = function(feature) { + let styles; + let styleFunction = feature.getStyleFunction(); if (styleFunction) { styles = styleFunction.call(/** @type {ol.Feature} */ (feature), resolution); } else { @@ -211,20 +211,19 @@ CanvasVectorTileLayerRenderer.prototype.createReplayGroup_ = function( } } if (styles) { - var dirty = this.renderFeature(feature, squaredTolerance, styles, - replayGroup); + const dirty = this.renderFeature(feature, squaredTolerance, styles, + replayGroup); this.dirty_ = this.dirty_ || dirty; replayState.dirty = replayState.dirty || dirty; } }; - var features = sourceTile.getFeatures(); + const features = sourceTile.getFeatures(); if (renderOrder && renderOrder !== replayState.renderedRenderOrder) { features.sort(renderOrder); } - var feature; - for (var i = 0, ii = features.length; i < ii; ++i) { - feature = features[i]; + for (let i = 0, ii = features.length; i < ii; ++i) { + const feature = features[i]; if (reproject) { if (tileProjection.getUnits() == Units.TILE_PIXELS) { // projected tile extent @@ -239,7 +238,7 @@ CanvasVectorTileLayerRenderer.prototype.createReplayGroup_ = function( } } replayGroup.finish(); - for (var r in replayGroup.getReplays()) { + for (const r in replayGroup.getReplays()) { zIndexKeys[r] = true; } sourceTile.setReplayGroup(layer, tile.tileCoord.toString(), replayGroup); @@ -253,8 +252,8 @@ CanvasVectorTileLayerRenderer.prototype.createReplayGroup_ = function( * @inheritDoc */ CanvasVectorTileLayerRenderer.prototype.drawTileImage = function( - tile, frameState, layerState, x, y, w, h, gutter, transition) { - var vectorImageTile = /** @type {ol.VectorImageTile} */ (tile); + tile, frameState, layerState, x, y, w, h, gutter, transition) { + const vectorImageTile = /** @type {ol.VectorImageTile} */ (tile); this.createReplayGroup_(vectorImageTile, frameState); if (this.context) { this.renderTileImage_(vectorImageTile, frameState, layerState); @@ -267,21 +266,21 @@ CanvasVectorTileLayerRenderer.prototype.drawTileImage = function( * @inheritDoc */ CanvasVectorTileLayerRenderer.prototype.forEachFeatureAtCoordinate = function(coordinate, frameState, hitTolerance, callback, thisArg) { - var resolution = frameState.viewState.resolution; - var rotation = frameState.viewState.rotation; + const resolution = frameState.viewState.resolution; + const rotation = frameState.viewState.rotation; hitTolerance = hitTolerance == undefined ? 0 : hitTolerance; - var layer = this.getLayer(); + const layer = this.getLayer(); /** @type {Object.} */ - var features = {}; + const features = {}; /** @type {Array.} */ - var renderedTiles = this.renderedTiles; + const renderedTiles = this.renderedTiles; - var source = /** @type {ol.source.VectorTile} */ (layer.getSource()); - var tileGrid = source.getTileGridForProjection(frameState.viewState.projection); - var bufferedExtent, found; - var i, ii, replayGroup; - var tile, tileCoord, tileExtent; + const source = /** @type {ol.source.VectorTile} */ (layer.getSource()); + const tileGrid = source.getTileGridForProjection(frameState.viewState.projection); + let bufferedExtent, found; + let i, ii, replayGroup; + let tile, tileCoord, tileExtent; for (i = 0, ii = renderedTiles.length; i < ii; ++i) { tile = renderedTiles[i]; tileCoord = tile.wrappedTileCoord; @@ -290,25 +289,25 @@ CanvasVectorTileLayerRenderer.prototype.forEachFeatureAtCoordinate = function(co if (!containsCoordinate(bufferedExtent, coordinate)) { continue; } - for (var t = 0, tt = tile.tileKeys.length; t < tt; ++t) { - var sourceTile = tile.getTile(tile.tileKeys[t]); + for (let t = 0, tt = tile.tileKeys.length; t < tt; ++t) { + const sourceTile = tile.getTile(tile.tileKeys[t]); if (sourceTile.getState() == TileState.ERROR) { continue; } replayGroup = sourceTile.getReplayGroup(layer, tile.tileCoord.toString()); found = found || replayGroup.forEachFeatureAtCoordinate( - coordinate, resolution, rotation, hitTolerance, {}, - /** + coordinate, resolution, rotation, hitTolerance, {}, + /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @return {?} Callback result. */ - function(feature) { - var key = getUid(feature).toString(); - if (!(key in features)) { - features[key] = true; - return callback.call(thisArg, feature, layer); - } - }, null); + function(feature) { + const key = getUid(feature).toString(); + if (!(key in features)) { + features[key] = true; + return callback.call(thisArg, feature, layer); + } + }, null); } } return found; @@ -322,26 +321,26 @@ CanvasVectorTileLayerRenderer.prototype.forEachFeatureAtCoordinate = function(co * @private */ CanvasVectorTileLayerRenderer.prototype.getReplayTransform_ = function(tile, frameState) { - var layer = this.getLayer(); - var source = /** @type {ol.source.VectorTile} */ (layer.getSource()); - var tileGrid = source.getTileGrid(); - var tileCoord = tile.tileCoord; - var tileResolution = tileGrid.getResolution(tileCoord[0]); - var viewState = frameState.viewState; - var pixelRatio = frameState.pixelRatio; - var renderResolution = viewState.resolution / pixelRatio; - var tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent); - var center = viewState.center; - var origin = getTopLeft(tileExtent); - var size = frameState.size; - var offsetX = Math.round(pixelRatio * size[0] / 2); - var offsetY = Math.round(pixelRatio * size[1] / 2); + const layer = this.getLayer(); + const source = /** @type {ol.source.VectorTile} */ (layer.getSource()); + const tileGrid = source.getTileGrid(); + const tileCoord = tile.tileCoord; + const tileResolution = tileGrid.getResolution(tileCoord[0]); + const viewState = frameState.viewState; + const pixelRatio = frameState.pixelRatio; + const renderResolution = viewState.resolution / pixelRatio; + const tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent); + const center = viewState.center; + const origin = getTopLeft(tileExtent); + const size = frameState.size; + const offsetX = Math.round(pixelRatio * size[0] / 2); + const offsetY = Math.round(pixelRatio * size[1] / 2); return _ol_transform_.compose(this.tmpTransform_, - offsetX, offsetY, - tileResolution / renderResolution, tileResolution / renderResolution, - viewState.rotation, - (origin[0] - center[0]) / tileResolution, - (center[1] - origin[1]) / tileResolution); + offsetX, offsetY, + tileResolution / renderResolution, tileResolution / renderResolution, + viewState.rotation, + (origin[0] - center[0]) / tileResolution, + (center[1] - origin[1]) / tileResolution); }; @@ -349,7 +348,7 @@ CanvasVectorTileLayerRenderer.prototype.getReplayTransform_ = function(tile, fra * @param {ol.events.Event} event Event. */ CanvasVectorTileLayerRenderer.prototype.handleFontsChanged_ = function(event) { - var layer = this.getLayer(); + const layer = this.getLayer(); if (layer.getVisible() && this.renderedLayerRevision_ !== undefined) { layer.changed(); } @@ -370,15 +369,15 @@ CanvasVectorTileLayerRenderer.prototype.handleStyleImageChange_ = function(event * @inheritDoc */ CanvasVectorTileLayerRenderer.prototype.postCompose = function(context, frameState, layerState) { - var layer = this.getLayer(); - var declutterReplays = layer.getDeclutter() ? {} : null; - var source = /** @type {ol.source.VectorTile} */ (layer.getSource()); - var renderMode = layer.getRenderMode(); - var replayTypes = CanvasVectorTileLayerRenderer.VECTOR_REPLAYS[renderMode]; - var pixelRatio = frameState.pixelRatio; - var rotation = frameState.viewState.rotation; - var size = frameState.size; - var offsetX, offsetY; + const layer = this.getLayer(); + const declutterReplays = layer.getDeclutter() ? {} : null; + const source = /** @type {ol.source.VectorTile} */ (layer.getSource()); + const renderMode = layer.getRenderMode(); + const replayTypes = CanvasVectorTileLayerRenderer.VECTOR_REPLAYS[renderMode]; + const pixelRatio = frameState.pixelRatio; + const rotation = frameState.viewState.rotation; + const size = frameState.size; + let offsetX, offsetY; if (rotation) { offsetX = Math.round(pixelRatio * size[0] / 2); offsetY = Math.round(pixelRatio * size[1] / 2); @@ -387,39 +386,39 @@ CanvasVectorTileLayerRenderer.prototype.postCompose = function(context, frameSta if (declutterReplays) { this.declutterTree_.clear(); } - var tiles = this.renderedTiles; - var tileGrid = source.getTileGridForProjection(frameState.viewState.projection); - var clips = []; - var zs = []; - for (var i = tiles.length - 1; i >= 0; --i) { - var tile = /** @type {ol.VectorImageTile} */ (tiles[i]); + const tiles = this.renderedTiles; + const tileGrid = source.getTileGridForProjection(frameState.viewState.projection); + const clips = []; + const zs = []; + for (let i = tiles.length - 1; i >= 0; --i) { + const tile = /** @type {ol.VectorImageTile} */ (tiles[i]); if (tile.getState() == TileState.ABORT) { continue; } - var tileCoord = tile.tileCoord; - var worldOffset = tileGrid.getTileCoordExtent(tileCoord)[0] - + const tileCoord = tile.tileCoord; + const worldOffset = tileGrid.getTileCoordExtent(tileCoord)[0] - tileGrid.getTileCoordExtent(tile.wrappedTileCoord)[0]; - var transform = undefined; - for (var t = 0, tt = tile.tileKeys.length; t < tt; ++t) { - var sourceTile = tile.getTile(tile.tileKeys[t]); + let transform = undefined; + for (let t = 0, tt = tile.tileKeys.length; t < tt; ++t) { + const sourceTile = tile.getTile(tile.tileKeys[t]); if (sourceTile.getState() == TileState.ERROR) { continue; } - var replayGroup = sourceTile.getReplayGroup(layer, tileCoord.toString()); + const replayGroup = sourceTile.getReplayGroup(layer, tileCoord.toString()); if (renderMode != _ol_layer_VectorTileRenderType_.VECTOR && !replayGroup.hasReplays(replayTypes)) { continue; } if (!transform) { transform = this.getTransform(frameState, worldOffset); } - var currentZ = sourceTile.tileCoord[0]; - var currentClip = replayGroup.getClipCoords(transform); + const currentZ = sourceTile.tileCoord[0]; + const currentClip = replayGroup.getClipCoords(transform); context.save(); context.globalAlpha = layerState.opacity; // Create a clip mask for regions in this low resolution tile that are // already filled by a higher resolution tile - for (var j = 0, jj = clips.length; j < jj; ++j) { - var clip = clips[j]; + for (let j = 0, jj = clips.length; j < jj; ++j) { + const clip = clips[j]; if (currentZ < zs[j]) { context.beginPath(); // counter-clockwise (outer ring) for current tile @@ -446,7 +445,7 @@ CanvasVectorTileLayerRenderer.prototype.postCompose = function(context, frameSta } if (rotation) { _ol_render_canvas_.rotateAtOffset(context, rotation, - /** @type {number} */ (offsetX), /** @type {number} */ (offsetY)); + /** @type {number} */ (offsetX), /** @type {number} */ (offsetY)); } CanvasTileLayerRenderer.prototype.postCompose.apply(this, arguments); }; @@ -464,17 +463,17 @@ CanvasVectorTileLayerRenderer.prototype.renderFeature = function(feature, square if (!styles) { return false; } - var loading = false; + let loading = false; if (Array.isArray(styles)) { - for (var i = 0, ii = styles.length; i < ii; ++i) { + for (let i = 0, ii = styles.length; i < ii; ++i) { loading = _ol_renderer_vector_.renderFeature( - replayGroup, feature, styles[i], squaredTolerance, - this.handleStyleImageChange_, this) || loading; + replayGroup, feature, styles[i], squaredTolerance, + this.handleStyleImageChange_, this) || loading; } } else { loading = _ol_renderer_vector_.renderFeature( - replayGroup, feature, styles, squaredTolerance, - this.handleStyleImageChange_, this); + replayGroup, feature, styles, squaredTolerance, + this.handleStyleImageChange_, this); } return loading; }; @@ -487,34 +486,34 @@ CanvasVectorTileLayerRenderer.prototype.renderFeature = function(feature, square * @private */ CanvasVectorTileLayerRenderer.prototype.renderTileImage_ = function( - tile, frameState, layerState) { - var layer = this.getLayer(); - var replayState = tile.getReplayState(layer); - var revision = layer.getRevision(); - var replays = CanvasVectorTileLayerRenderer.IMAGE_REPLAYS[layer.getRenderMode()]; + tile, frameState, layerState) { + const layer = this.getLayer(); + const replayState = tile.getReplayState(layer); + const revision = layer.getRevision(); + const replays = CanvasVectorTileLayerRenderer.IMAGE_REPLAYS[layer.getRenderMode()]; if (replays && replayState.renderedTileRevision !== revision) { replayState.renderedTileRevision = revision; - var tileCoord = tile.wrappedTileCoord; - var z = tileCoord[0]; - var pixelRatio = frameState.pixelRatio; - var source = /** @type {ol.source.VectorTile} */ (layer.getSource()); - var tileGrid = source.getTileGridForProjection(frameState.viewState.projection); - var resolution = tileGrid.getResolution(z); - var context = tile.getContext(layer); - var size = source.getTilePixelSize(z, pixelRatio, frameState.viewState.projection); + const tileCoord = tile.wrappedTileCoord; + const z = tileCoord[0]; + const pixelRatio = frameState.pixelRatio; + const source = /** @type {ol.source.VectorTile} */ (layer.getSource()); + const tileGrid = source.getTileGridForProjection(frameState.viewState.projection); + const resolution = tileGrid.getResolution(z); + const context = tile.getContext(layer); + const size = source.getTilePixelSize(z, pixelRatio, frameState.viewState.projection); context.canvas.width = size[0]; context.canvas.height = size[1]; - var tileExtent = tileGrid.getTileCoordExtent(tileCoord); - for (var i = 0, ii = tile.tileKeys.length; i < ii; ++i) { - var sourceTile = tile.getTile(tile.tileKeys[i]); + const tileExtent = tileGrid.getTileCoordExtent(tileCoord); + for (let i = 0, ii = tile.tileKeys.length; i < ii; ++i) { + const sourceTile = tile.getTile(tile.tileKeys[i]); if (sourceTile.getState() == TileState.ERROR) { continue; } - var pixelScale = pixelRatio / resolution; - var transform = _ol_transform_.reset(this.tmpTransform_); + const pixelScale = pixelRatio / resolution; + const transform = _ol_transform_.reset(this.tmpTransform_); _ol_transform_.scale(transform, pixelScale, -pixelScale); _ol_transform_.translate(transform, -tileExtent[0], -tileExtent[3]); - var replayGroup = sourceTile.getReplayGroup(layer, tile.tileCoord.toString()); + const replayGroup = sourceTile.getReplayGroup(layer, tile.tileCoord.toString()); replayGroup.replay(context, transform, 0, {}, replays); } } diff --git a/src/ol/renderer/vector.js b/src/ol/renderer/vector.js index d8cf16b012..70a2d767ee 100644 --- a/src/ol/renderer/vector.js +++ b/src/ol/renderer/vector.js @@ -5,13 +5,13 @@ import {getUid} from '../index.js'; import ImageState from '../ImageState.js'; import GeometryType from '../geom/GeometryType.js'; import ReplayType from '../render/ReplayType.js'; -var _ol_renderer_vector_ = {}; +const _ol_renderer_vector_ = {}; /** * @type {number} Tolerance for geometry simplification in device pixels. */ -var SIMPLIFY_TOLERANCE = 0.5; +const SIMPLIFY_TOLERANCE = 0.5; /** @@ -30,7 +30,7 @@ _ol_renderer_vector_.defaultOrder = function(feature1, feature2) { * @return {number} Squared pixel tolerance. */ _ol_renderer_vector_.getSquaredTolerance = function(resolution, pixelRatio) { - var tolerance = _ol_renderer_vector_.getTolerance(resolution, pixelRatio); + const tolerance = _ol_renderer_vector_.getTolerance(resolution, pixelRatio); return tolerance * tolerance; }; @@ -53,16 +53,16 @@ _ol_renderer_vector_.getTolerance = function(resolution, pixelRatio) { * @private */ _ol_renderer_vector_.renderCircleGeometry_ = function(replayGroup, geometry, style, feature) { - var fillStyle = style.getFill(); - var strokeStyle = style.getStroke(); + const fillStyle = style.getFill(); + const strokeStyle = style.getStroke(); if (fillStyle || strokeStyle) { - var circleReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.CIRCLE); + const circleReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.CIRCLE); circleReplay.setFillStrokeStyle(fillStyle, strokeStyle); circleReplay.drawCircle(geometry, feature); } - var textStyle = style.getText(); + const textStyle = style.getText(); if (textStyle) { - var textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); + const textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); textReplay.setTextStyle(textStyle, replayGroup.addDeclutter(false)); textReplay.drawText(geometry, feature); } @@ -80,12 +80,11 @@ _ol_renderer_vector_.renderCircleGeometry_ = function(replayGroup, geometry, sty * @template T */ _ol_renderer_vector_.renderFeature = function( - replayGroup, feature, style, squaredTolerance, listener, thisArg) { - var loading = false; - var imageStyle, imageState; - imageStyle = style.getImage(); + replayGroup, feature, style, squaredTolerance, listener, thisArg) { + let loading = false; + const imageStyle = style.getImage(); if (imageStyle) { - imageState = imageStyle.getImageState(); + let imageState = imageStyle.getImageState(); if (imageState == ImageState.LOADED || imageState == ImageState.ERROR) { imageStyle.unlistenImageChange(listener, thisArg); } else { @@ -98,7 +97,7 @@ _ol_renderer_vector_.renderFeature = function( } } _ol_renderer_vector_.renderFeature_(replayGroup, feature, style, - squaredTolerance); + squaredTolerance); return loading; }; @@ -112,17 +111,17 @@ _ol_renderer_vector_.renderFeature = function( * @private */ _ol_renderer_vector_.renderFeature_ = function( - replayGroup, feature, style, squaredTolerance) { - var geometry = style.getGeometryFunction()(feature); + replayGroup, feature, style, squaredTolerance) { + const geometry = style.getGeometryFunction()(feature); if (!geometry) { return; } - var simplifiedGeometry = geometry.getSimplifiedGeometry(squaredTolerance); - var renderer = style.getRenderer(); + const simplifiedGeometry = geometry.getSimplifiedGeometry(squaredTolerance); + const renderer = style.getRenderer(); if (renderer) { _ol_renderer_vector_.renderGeometry_(replayGroup, simplifiedGeometry, style, feature); } else { - var geometryRenderer = + const geometryRenderer = _ol_renderer_vector_.GEOMETRY_RENDERERS_[simplifiedGeometry.getType()]; geometryRenderer(replayGroup, simplifiedGeometry, style, feature); } @@ -138,13 +137,13 @@ _ol_renderer_vector_.renderFeature_ = function( */ _ol_renderer_vector_.renderGeometry_ = function(replayGroup, geometry, style, feature) { if (geometry.getType() == GeometryType.GEOMETRY_COLLECTION) { - var geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries(); - for (var i = 0, ii = geometries.length; i < ii; ++i) { + const geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries(); + for (let i = 0, ii = geometries.length; i < ii; ++i) { _ol_renderer_vector_.renderGeometry_(replayGroup, geometries[i], style, feature); } return; } - var replay = replayGroup.getReplay(style.getZIndex(), ReplayType.DEFAULT); + const replay = replayGroup.getReplay(style.getZIndex(), ReplayType.DEFAULT); replay.drawCustom(/** @type {ol.geom.SimpleGeometry} */ (geometry), feature, style.getRenderer()); }; @@ -157,10 +156,10 @@ _ol_renderer_vector_.renderGeometry_ = function(replayGroup, geometry, style, fe * @private */ _ol_renderer_vector_.renderGeometryCollectionGeometry_ = function(replayGroup, geometry, style, feature) { - var geometries = geometry.getGeometriesArray(); - var i, ii; + const geometries = geometry.getGeometriesArray(); + let i, ii; for (i = 0, ii = geometries.length; i < ii; ++i) { - var geometryRenderer = + const geometryRenderer = _ol_renderer_vector_.GEOMETRY_RENDERERS_[geometries[i].getType()]; geometryRenderer(replayGroup, geometries[i], style, feature); } @@ -175,15 +174,15 @@ _ol_renderer_vector_.renderGeometryCollectionGeometry_ = function(replayGroup, g * @private */ _ol_renderer_vector_.renderLineStringGeometry_ = function(replayGroup, geometry, style, feature) { - var strokeStyle = style.getStroke(); + const strokeStyle = style.getStroke(); if (strokeStyle) { - var lineStringReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.LINE_STRING); + const lineStringReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.LINE_STRING); lineStringReplay.setFillStrokeStyle(null, strokeStyle); lineStringReplay.drawLineString(geometry, feature); } - var textStyle = style.getText(); + const textStyle = style.getText(); if (textStyle) { - var textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); + const textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); textReplay.setTextStyle(textStyle, replayGroup.addDeclutter(false)); textReplay.drawText(geometry, feature); } @@ -198,15 +197,15 @@ _ol_renderer_vector_.renderLineStringGeometry_ = function(replayGroup, geometry, * @private */ _ol_renderer_vector_.renderMultiLineStringGeometry_ = function(replayGroup, geometry, style, feature) { - var strokeStyle = style.getStroke(); + const strokeStyle = style.getStroke(); if (strokeStyle) { - var lineStringReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.LINE_STRING); + const lineStringReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.LINE_STRING); lineStringReplay.setFillStrokeStyle(null, strokeStyle); lineStringReplay.drawMultiLineString(geometry, feature); } - var textStyle = style.getText(); + const textStyle = style.getText(); if (textStyle) { - var textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); + const textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); textReplay.setTextStyle(textStyle, replayGroup.addDeclutter(false)); textReplay.drawText(geometry, feature); } @@ -221,16 +220,16 @@ _ol_renderer_vector_.renderMultiLineStringGeometry_ = function(replayGroup, geom * @private */ _ol_renderer_vector_.renderMultiPolygonGeometry_ = function(replayGroup, geometry, style, feature) { - var fillStyle = style.getFill(); - var strokeStyle = style.getStroke(); + const fillStyle = style.getFill(); + const strokeStyle = style.getStroke(); if (strokeStyle || fillStyle) { - var polygonReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.POLYGON); + const polygonReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.POLYGON); polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle); polygonReplay.drawMultiPolygon(geometry, feature); } - var textStyle = style.getText(); + const textStyle = style.getText(); if (textStyle) { - var textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); + const textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); textReplay.setTextStyle(textStyle, replayGroup.addDeclutter(false)); textReplay.drawText(geometry, feature); } @@ -245,18 +244,18 @@ _ol_renderer_vector_.renderMultiPolygonGeometry_ = function(replayGroup, geometr * @private */ _ol_renderer_vector_.renderPointGeometry_ = function(replayGroup, geometry, style, feature) { - var imageStyle = style.getImage(); + const imageStyle = style.getImage(); if (imageStyle) { if (imageStyle.getImageState() != ImageState.LOADED) { return; } - var imageReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.IMAGE); + const imageReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.IMAGE); imageReplay.setImageStyle(imageStyle, replayGroup.addDeclutter(false)); imageReplay.drawPoint(geometry, feature); } - var textStyle = style.getText(); + const textStyle = style.getText(); if (textStyle) { - var textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); + const textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); textReplay.setTextStyle(textStyle, replayGroup.addDeclutter(!!imageStyle)); textReplay.drawText(geometry, feature); } @@ -271,18 +270,18 @@ _ol_renderer_vector_.renderPointGeometry_ = function(replayGroup, geometry, styl * @private */ _ol_renderer_vector_.renderMultiPointGeometry_ = function(replayGroup, geometry, style, feature) { - var imageStyle = style.getImage(); + const imageStyle = style.getImage(); if (imageStyle) { if (imageStyle.getImageState() != ImageState.LOADED) { return; } - var imageReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.IMAGE); + const imageReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.IMAGE); imageReplay.setImageStyle(imageStyle, replayGroup.addDeclutter(false)); imageReplay.drawMultiPoint(geometry, feature); } - var textStyle = style.getText(); + const textStyle = style.getText(); if (textStyle) { - var textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); + const textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); textReplay.setTextStyle(textStyle, replayGroup.addDeclutter(!!imageStyle)); textReplay.drawText(geometry, feature); } @@ -297,16 +296,16 @@ _ol_renderer_vector_.renderMultiPointGeometry_ = function(replayGroup, geometry, * @private */ _ol_renderer_vector_.renderPolygonGeometry_ = function(replayGroup, geometry, style, feature) { - var fillStyle = style.getFill(); - var strokeStyle = style.getStroke(); + const fillStyle = style.getFill(); + const strokeStyle = style.getStroke(); if (fillStyle || strokeStyle) { - var polygonReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.POLYGON); + const polygonReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.POLYGON); polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle); polygonReplay.drawPolygon(geometry, feature); } - var textStyle = style.getText(); + const textStyle = style.getText(); if (textStyle) { - var textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); + const textReplay = replayGroup.getReplay(style.getZIndex(), ReplayType.TEXT); textReplay.setTextStyle(textStyle, replayGroup.addDeclutter(false)); textReplay.drawText(geometry, feature); } diff --git a/src/ol/renderer/webgl/ImageLayer.js b/src/ol/renderer/webgl/ImageLayer.js index 46ee8e5b28..d6f52ad253 100644 --- a/src/ol/renderer/webgl/ImageLayer.js +++ b/src/ol/renderer/webgl/ImageLayer.js @@ -21,7 +21,7 @@ import _ol_webgl_Context_ from '../../webgl/Context.js'; * @param {ol.layer.Image} imageLayer Tile layer. * @api */ -var WebGLImageLayerRenderer = function(mapRenderer, imageLayer) { +const WebGLImageLayerRenderer = function(mapRenderer, imageLayer) { WebGLLayerRenderer.call(this, mapRenderer, imageLayer); @@ -68,8 +68,8 @@ WebGLImageLayerRenderer['handles'] = function(type, layer) { */ WebGLImageLayerRenderer['create'] = function(mapRenderer, layer) { return new WebGLImageLayerRenderer( - /** @type {ol.renderer.webgl.Map} */ (mapRenderer), - /** @type {ol.layer.Image} */ (layer) + /** @type {ol.renderer.webgl.Map} */ (mapRenderer), + /** @type {ol.layer.Image} */ (layer) ); }; @@ -85,11 +85,11 @@ WebGLImageLayerRenderer.prototype.createTexture_ = function(image) { // http://www.khronos.org/webgl/wiki/WebGL_and_OpenGL_Differences#Non-Power_of_Two_Texture_Support // http://learningwebgl.com/blog/?p=2101 - var imageElement = image.getImage(); - var gl = this.mapRenderer.getGL(); + const imageElement = image.getImage(); + const gl = this.mapRenderer.getGL(); return _ol_webgl_Context_.createTexture( - gl, imageElement, _ol_webgl_.CLAMP_TO_EDGE, _ol_webgl_.CLAMP_TO_EDGE); + gl, imageElement, _ol_webgl_.CLAMP_TO_EDGE, _ol_webgl_.CLAMP_TO_EDGE); }; @@ -97,21 +97,21 @@ WebGLImageLayerRenderer.prototype.createTexture_ = function(image) { * @inheritDoc */ WebGLImageLayerRenderer.prototype.forEachFeatureAtCoordinate = function(coordinate, frameState, hitTolerance, callback, thisArg) { - var layer = this.getLayer(); - var source = layer.getSource(); - var resolution = frameState.viewState.resolution; - var rotation = frameState.viewState.rotation; - var skippedFeatureUids = frameState.skippedFeatureUids; + const layer = this.getLayer(); + const source = layer.getSource(); + const resolution = frameState.viewState.resolution; + const rotation = frameState.viewState.rotation; + const skippedFeatureUids = frameState.skippedFeatureUids; return source.forEachFeatureAtCoordinate( - coordinate, resolution, rotation, hitTolerance, skippedFeatureUids, + coordinate, resolution, rotation, hitTolerance, skippedFeatureUids, - /** + /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @return {?} Callback result. */ - function(feature) { - return callback.call(thisArg, feature, layer); - }); + function(feature) { + return callback.call(thisArg, feature, layer); + }); }; @@ -120,38 +120,38 @@ WebGLImageLayerRenderer.prototype.forEachFeatureAtCoordinate = function(coordina */ WebGLImageLayerRenderer.prototype.prepareFrame = function(frameState, layerState, context) { - var gl = this.mapRenderer.getGL(); + const gl = this.mapRenderer.getGL(); - var pixelRatio = frameState.pixelRatio; - var viewState = frameState.viewState; - var viewCenter = viewState.center; - var viewResolution = viewState.resolution; - var viewRotation = viewState.rotation; + const pixelRatio = frameState.pixelRatio; + const viewState = frameState.viewState; + const viewCenter = viewState.center; + const viewResolution = viewState.resolution; + const viewRotation = viewState.rotation; - var image = this.image_; - var texture = this.texture; - var imageLayer = /** @type {ol.layer.Image} */ (this.getLayer()); - var imageSource = imageLayer.getSource(); + let image = this.image_; + let texture = this.texture; + const imageLayer = /** @type {ol.layer.Image} */ (this.getLayer()); + const imageSource = imageLayer.getSource(); - var hints = frameState.viewHints; + const hints = frameState.viewHints; - var renderedExtent = frameState.extent; + let renderedExtent = frameState.extent; if (layerState.extent !== undefined) { renderedExtent = getIntersection(renderedExtent, layerState.extent); } if (!hints[ViewHint.ANIMATING] && !hints[ViewHint.INTERACTING] && !isEmpty(renderedExtent)) { - var projection = viewState.projection; + let projection = viewState.projection; if (!ENABLE_RASTER_REPROJECTION) { - var sourceProjection = imageSource.getProjection(); + const sourceProjection = imageSource.getProjection(); if (sourceProjection) { projection = sourceProjection; } } - var image_ = imageSource.getImage(renderedExtent, viewResolution, - pixelRatio, projection); + const image_ = imageSource.getImage(renderedExtent, viewResolution, + pixelRatio, projection); if (image_) { - var loaded = this.loadImage(image_); + const loaded = this.loadImage(image_); if (loaded) { image = image_; texture = this.createTexture_(image_); @@ -160,13 +160,13 @@ WebGLImageLayerRenderer.prototype.prepareFrame = function(frameState, layerState * @param {WebGLRenderingContext} gl GL. * @param {WebGLTexture} texture Texture. */ - var postRenderFunction = function(gl, texture) { + const postRenderFunction = function(gl, texture) { if (!gl.isContextLost()) { gl.deleteTexture(texture); } }.bind(null, gl, this.texture); frameState.postRenderFunctions.push( - /** @type {ol.PostRenderFunction} */ (postRenderFunction) + /** @type {ol.PostRenderFunction} */ (postRenderFunction) ); } } @@ -174,15 +174,15 @@ WebGLImageLayerRenderer.prototype.prepareFrame = function(frameState, layerState } if (image) { - var canvas = this.mapRenderer.getContext().getCanvas(); + const canvas = this.mapRenderer.getContext().getCanvas(); this.updateProjectionMatrix_(canvas.width, canvas.height, - pixelRatio, viewCenter, viewResolution, viewRotation, - image.getExtent()); + pixelRatio, viewCenter, viewResolution, viewRotation, + image.getExtent()); this.hitTransformationMatrix_ = null; // Translate and scale to flip the Y coord. - var texCoordMatrix = this.texCoordMatrix; + const texCoordMatrix = this.texCoordMatrix; _ol_transform_.reset(texCoordMatrix); _ol_transform_.scale(texCoordMatrix, 1, -1); _ol_transform_.translate(texCoordMatrix, 0, -1); @@ -206,23 +206,23 @@ WebGLImageLayerRenderer.prototype.prepareFrame = function(frameState, layerState * @private */ WebGLImageLayerRenderer.prototype.updateProjectionMatrix_ = function(canvasWidth, canvasHeight, pixelRatio, - viewCenter, viewResolution, viewRotation, imageExtent) { + viewCenter, viewResolution, viewRotation, imageExtent) { - var canvasExtentWidth = canvasWidth * viewResolution; - var canvasExtentHeight = canvasHeight * viewResolution; + const canvasExtentWidth = canvasWidth * viewResolution; + const canvasExtentHeight = canvasHeight * viewResolution; - var projectionMatrix = this.projectionMatrix; + const projectionMatrix = this.projectionMatrix; _ol_transform_.reset(projectionMatrix); _ol_transform_.scale(projectionMatrix, - pixelRatio * 2 / canvasExtentWidth, - pixelRatio * 2 / canvasExtentHeight); + pixelRatio * 2 / canvasExtentWidth, + pixelRatio * 2 / canvasExtentHeight); _ol_transform_.rotate(projectionMatrix, -viewRotation); _ol_transform_.translate(projectionMatrix, - imageExtent[0] - viewCenter[0], - imageExtent[1] - viewCenter[1]); + imageExtent[0] - viewCenter[0], + imageExtent[1] - viewCenter[1]); _ol_transform_.scale(projectionMatrix, - (imageExtent[2] - imageExtent[0]) / 2, - (imageExtent[3] - imageExtent[1]) / 2); + (imageExtent[2] - imageExtent[0]) / 2, + (imageExtent[3] - imageExtent[1]) / 2); _ol_transform_.translate(projectionMatrix, 1, 1); }; @@ -232,7 +232,7 @@ WebGLImageLayerRenderer.prototype.updateProjectionMatrix_ = function(canvasWidth * @inheritDoc */ WebGLImageLayerRenderer.prototype.hasFeatureAtCoordinate = function(coordinate, frameState) { - var hasFeature = this.forEachFeatureAtCoordinate(coordinate, frameState, 0, TRUE, this); + const hasFeature = this.forEachFeatureAtCoordinate(coordinate, frameState, 0, TRUE, this); return hasFeature !== undefined; }; @@ -248,9 +248,9 @@ WebGLImageLayerRenderer.prototype.forEachLayerAtPixel = function(pixel, frameSta if (this.getLayer().getSource().forEachFeatureAtCoordinate !== nullFunction) { // for ImageCanvas sources use the original hit-detection logic, // so that for example also transparent polygons are detected - var coordinate = _ol_transform_.apply( - frameState.pixelToCoordinateTransform, pixel.slice()); - var hasFeature = this.forEachFeatureAtCoordinate(coordinate, frameState, 0, TRUE, this); + const coordinate = _ol_transform_.apply( + frameState.pixelToCoordinateTransform, pixel.slice()); + const hasFeature = this.forEachFeatureAtCoordinate(coordinate, frameState, 0, TRUE, this); if (hasFeature) { return callback.call(thisArg, this.getLayer(), null); @@ -258,16 +258,16 @@ WebGLImageLayerRenderer.prototype.forEachLayerAtPixel = function(pixel, frameSta return undefined; } } else { - var imageSize = + const imageSize = [this.image_.getImage().width, this.image_.getImage().height]; if (!this.hitTransformationMatrix_) { this.hitTransformationMatrix_ = this.getHitTransformationMatrix_( - frameState.size, imageSize); + frameState.size, imageSize); } - var pixelOnFrameBuffer = _ol_transform_.apply( - this.hitTransformationMatrix_, pixel.slice()); + const pixelOnFrameBuffer = _ol_transform_.apply( + this.hitTransformationMatrix_, pixel.slice()); if (pixelOnFrameBuffer[0] < 0 || pixelOnFrameBuffer[0] > imageSize[0] || pixelOnFrameBuffer[1] < 0 || pixelOnFrameBuffer[1] > imageSize[1]) { @@ -281,9 +281,9 @@ WebGLImageLayerRenderer.prototype.forEachLayerAtPixel = function(pixel, frameSta this.hitCanvasContext_.clearRect(0, 0, 1, 1); this.hitCanvasContext_.drawImage(this.image_.getImage(), - pixelOnFrameBuffer[0], pixelOnFrameBuffer[1], 1, 1, 0, 0, 1, 1); + pixelOnFrameBuffer[0], pixelOnFrameBuffer[1], 1, 1, 0, 0, 1, 1); - var imageData = this.hitCanvasContext_.getImageData(0, 0, 1, 1).data; + const imageData = this.hitCanvasContext_.getImageData(0, 0, 1, 1).data; if (imageData[3] > 0) { return callback.call(thisArg, this.getLayer(), imageData); } else { @@ -304,7 +304,7 @@ WebGLImageLayerRenderer.prototype.forEachLayerAtPixel = function(pixel, frameSta WebGLImageLayerRenderer.prototype.getHitTransformationMatrix_ = function(mapSize, imageSize) { // the first matrix takes a map pixel, flips the y-axis and scales to // a range between -1 ... 1 - var mapCoordTransform = _ol_transform_.create(); + const mapCoordTransform = _ol_transform_.create(); _ol_transform_.translate(mapCoordTransform, -1, -1); _ol_transform_.scale(mapCoordTransform, 2 / mapSize[0], 2 / mapSize[1]); _ol_transform_.translate(mapCoordTransform, 0, mapSize[1]); @@ -312,10 +312,10 @@ WebGLImageLayerRenderer.prototype.getHitTransformationMatrix_ = function(mapSize // the second matrix is the inverse of the projection matrix used in the // shader for drawing - var projectionMatrixInv = _ol_transform_.invert(this.projectionMatrix.slice()); + const projectionMatrixInv = _ol_transform_.invert(this.projectionMatrix.slice()); // the third matrix scales to the image dimensions and flips the y-axis again - var transform = _ol_transform_.create(); + const transform = _ol_transform_.create(); _ol_transform_.translate(transform, 0, imageSize[1]); _ol_transform_.scale(transform, 1, -1); _ol_transform_.scale(transform, imageSize[0] / 2, imageSize[1] / 2); diff --git a/src/ol/renderer/webgl/Layer.js b/src/ol/renderer/webgl/Layer.js index 31ea973144..9c60d8b200 100644 --- a/src/ol/renderer/webgl/Layer.js +++ b/src/ol/renderer/webgl/Layer.js @@ -21,7 +21,7 @@ import _ol_webgl_Context_ from '../../webgl/Context.js'; * @param {ol.renderer.webgl.Map} mapRenderer Map renderer. * @param {ol.layer.Layer} layer Layer. */ -var WebGLLayerRenderer = function(mapRenderer, layer) { +const WebGLLayerRenderer = function(mapRenderer, layer) { LayerRenderer.call(this, layer); @@ -96,7 +96,7 @@ inherits(WebGLLayerRenderer, LayerRenderer); */ WebGLLayerRenderer.prototype.bindFramebuffer = function(frameState, framebufferDimension) { - var gl = this.mapRenderer.getGL(); + const gl = this.mapRenderer.getGL(); if (this.framebufferDimension === undefined || this.framebufferDimension != framebufferDimension) { @@ -105,7 +105,7 @@ WebGLLayerRenderer.prototype.bindFramebuffer = function(frameState, framebufferD * @param {WebGLFramebuffer} framebuffer Framebuffer. * @param {WebGLTexture} texture Texture. */ - var postRenderFunction = function(gl, framebuffer, texture) { + const postRenderFunction = function(gl, framebuffer, texture) { if (!gl.isContextLost()) { gl.deleteFramebuffer(framebuffer); gl.deleteTexture(texture); @@ -113,16 +113,16 @@ WebGLLayerRenderer.prototype.bindFramebuffer = function(frameState, framebufferD }.bind(null, gl, this.framebuffer, this.texture); frameState.postRenderFunctions.push( - /** @type {ol.PostRenderFunction} */ (postRenderFunction) + /** @type {ol.PostRenderFunction} */ (postRenderFunction) ); - var texture = _ol_webgl_Context_.createEmptyTexture( - gl, framebufferDimension, framebufferDimension); + const texture = _ol_webgl_Context_.createEmptyTexture( + gl, framebufferDimension, framebufferDimension); - var framebuffer = gl.createFramebuffer(); + const framebuffer = gl.createFramebuffer(); gl.bindFramebuffer(_ol_webgl_.FRAMEBUFFER, framebuffer); gl.framebufferTexture2D(_ol_webgl_.FRAMEBUFFER, - _ol_webgl_.COLOR_ATTACHMENT0, _ol_webgl_.TEXTURE_2D, texture, 0); + _ol_webgl_.COLOR_ATTACHMENT0, _ol_webgl_.TEXTURE_2D, texture, 0); this.texture = texture; this.framebuffer = framebuffer; @@ -146,14 +146,14 @@ WebGLLayerRenderer.prototype.composeFrame = function(frameState, layerState, con context.bindBuffer(_ol_webgl_.ARRAY_BUFFER, this.arrayBuffer_); - var gl = context.getGL(); + const gl = context.getGL(); - var fragmentShader = _ol_renderer_webgl_defaultmapshader_.fragment; - var vertexShader = _ol_renderer_webgl_defaultmapshader_.vertex; + const fragmentShader = _ol_renderer_webgl_defaultmapshader_.fragment; + const vertexShader = _ol_renderer_webgl_defaultmapshader_.vertex; - var program = context.getProgram(fragmentShader, vertexShader); + const program = context.getProgram(fragmentShader, vertexShader); - var locations; + let locations; if (!this.defaultLocations_) { locations = new _ol_renderer_webgl_defaultmapshader_Locations_(gl, program); this.defaultLocations_ = locations; @@ -164,17 +164,17 @@ WebGLLayerRenderer.prototype.composeFrame = function(frameState, layerState, con if (context.useProgram(program)) { gl.enableVertexAttribArray(locations.a_position); gl.vertexAttribPointer( - locations.a_position, 2, _ol_webgl_.FLOAT, false, 16, 0); + locations.a_position, 2, _ol_webgl_.FLOAT, false, 16, 0); gl.enableVertexAttribArray(locations.a_texCoord); gl.vertexAttribPointer( - locations.a_texCoord, 2, _ol_webgl_.FLOAT, false, 16, 8); + locations.a_texCoord, 2, _ol_webgl_.FLOAT, false, 16, 8); gl.uniform1i(locations.u_texture, 0); } gl.uniformMatrix4fv(locations.u_texCoordMatrix, false, - fromTransform(this.tmpMat4_, this.getTexCoordMatrix())); + fromTransform(this.tmpMat4_, this.getTexCoordMatrix())); gl.uniformMatrix4fv(locations.u_projectionMatrix, false, - fromTransform(this.tmpMat4_, this.getProjectionMatrix())); + fromTransform(this.tmpMat4_, this.getProjectionMatrix())); gl.uniform1f(locations.u_opacity, layerState.opacity); gl.bindTexture(_ol_webgl_.TEXTURE_2D, this.getTexture()); gl.drawArrays(_ol_webgl_.TRIANGLE_STRIP, 0, 4); @@ -190,20 +190,20 @@ WebGLLayerRenderer.prototype.composeFrame = function(frameState, layerState, con * @private */ WebGLLayerRenderer.prototype.dispatchComposeEvent_ = function(type, context, frameState) { - var layer = this.getLayer(); + const layer = this.getLayer(); if (layer.hasListener(type)) { - var viewState = frameState.viewState; - var resolution = viewState.resolution; - var pixelRatio = frameState.pixelRatio; - var extent = frameState.extent; - var center = viewState.center; - var rotation = viewState.rotation; - var size = frameState.size; + const viewState = frameState.viewState; + const resolution = viewState.resolution; + const pixelRatio = frameState.pixelRatio; + const extent = frameState.extent; + const center = viewState.center; + const rotation = viewState.rotation; + const size = frameState.size; - var render = new _ol_render_webgl_Immediate_( - context, center, resolution, rotation, size, extent, pixelRatio); - var composeEvent = new RenderEvent( - type, render, frameState, null, context); + const render = new _ol_render_webgl_Immediate_( + context, center, resolution, rotation, size, extent, pixelRatio); + const composeEvent = new RenderEvent( + type, render, frameState, null, context); layer.dispatchEvent(composeEvent); } }; diff --git a/src/ol/renderer/webgl/Map.js b/src/ol/renderer/webgl/Map.js index 6e58c1ba97..ca1ca57a0d 100644 --- a/src/ol/renderer/webgl/Map.js +++ b/src/ol/renderer/webgl/Map.js @@ -25,7 +25,7 @@ import ContextEventType from '../../webgl/ContextEventType.js'; /** * @type {number} Texture cache high water mark. */ -var WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK = 1024; +const WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK = 1024; /** @@ -35,7 +35,7 @@ var WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK = 1024; * @param {ol.PluggableMap} map Map. * @api */ -var WebGLMapRenderer = function(container, map) { +const WebGLMapRenderer = function(container, map) { MapRenderer.call(this, container, map); /** @@ -93,9 +93,9 @@ var WebGLMapRenderer = function(container, map) { this.context_ = new _ol_webgl_Context_(this.canvas_, this.gl_); _ol_events_.listen(this.canvas_, ContextEventType.LOST, - this.handleWebGLContextLost, this); + this.handleWebGLContextLost, this); _ol_events_.listen(this.canvas_, ContextEventType.RESTORED, - this.handleWebGLContextRestored, this); + this.handleWebGLContextRestored, this); /** * @private @@ -114,26 +114,26 @@ var WebGLMapRenderer = function(container, map) { * @type {ol.structs.PriorityQueue.} */ this.tileTextureQueue_ = new PriorityQueue( - /** + /** * @param {Array.<*>} element Element. * @return {number} Priority. * @this {ol.renderer.webgl.Map} */ - (function(element) { - var tileCenter = /** @type {ol.Coordinate} */ (element[1]); - var tileResolution = /** @type {number} */ (element[2]); - var deltaX = tileCenter[0] - this.focus_[0]; - var deltaY = tileCenter[1] - this.focus_[1]; - return 65536 * Math.log(tileResolution) + + (function(element) { + const tileCenter = /** @type {ol.Coordinate} */ (element[1]); + const tileResolution = /** @type {number} */ (element[2]); + const deltaX = tileCenter[0] - this.focus_[0]; + const deltaY = tileCenter[1] - this.focus_[1]; + return 65536 * Math.log(tileResolution) + Math.sqrt(deltaX * deltaX + deltaY * deltaY) / tileResolution; - }).bind(this), - /** + }).bind(this), + /** * @param {Array.<*>} element Element. * @return {string} Key. */ - function(element) { - return /** @type {ol.Tile} */ (element[0]).getKey(); - }); + function(element) { + return /** @type {ol.Tile} */ (element[0]).getKey(); + }); /** @@ -146,12 +146,12 @@ var WebGLMapRenderer = function(container, map) { function(map, frameState) { if (!this.tileTextureQueue_.isEmpty()) { this.tileTextureQueue_.reprioritize(); - var element = this.tileTextureQueue_.dequeue(); - var tile = /** @type {ol.Tile} */ (element[0]); - var tileSize = /** @type {ol.Size} */ (element[3]); - var tileGutter = /** @type {number} */ (element[4]); + const element = this.tileTextureQueue_.dequeue(); + const tile = /** @type {ol.Tile} */ (element[0]); + const tileSize = /** @type {ol.Size} */ (element[3]); + const tileGutter = /** @type {number} */ (element[4]); this.bindTileTexture( - tile, tileSize, tileGutter, _ol_webgl_.LINEAR, _ol_webgl_.LINEAR); + tile, tileSize, tileGutter, _ol_webgl_.LINEAR, _ol_webgl_.LINEAR); } return false; }.bind(this); @@ -198,27 +198,27 @@ WebGLMapRenderer['create'] = function(container, map) { * @param {number} minFilter Min filter. */ WebGLMapRenderer.prototype.bindTileTexture = function(tile, tileSize, tileGutter, magFilter, minFilter) { - var gl = this.getGL(); - var tileKey = tile.getKey(); + const gl = this.getGL(); + const tileKey = tile.getKey(); if (this.textureCache_.containsKey(tileKey)) { - var textureCacheEntry = this.textureCache_.get(tileKey); + const textureCacheEntry = this.textureCache_.get(tileKey); gl.bindTexture(_ol_webgl_.TEXTURE_2D, textureCacheEntry.texture); if (textureCacheEntry.magFilter != magFilter) { gl.texParameteri( - _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_MAG_FILTER, magFilter); + _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_MAG_FILTER, magFilter); textureCacheEntry.magFilter = magFilter; } if (textureCacheEntry.minFilter != minFilter) { gl.texParameteri( - _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_MIN_FILTER, minFilter); + _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_MIN_FILTER, minFilter); textureCacheEntry.minFilter = minFilter; } } else { - var texture = gl.createTexture(); + const texture = gl.createTexture(); gl.bindTexture(_ol_webgl_.TEXTURE_2D, texture); if (tileGutter > 0) { - var clipTileCanvas = this.clipTileContext_.canvas; - var clipTileContext = this.clipTileContext_; + const clipTileCanvas = this.clipTileContext_.canvas; + const clipTileContext = this.clipTileContext_; if (this.clipTileCanvasWidth_ !== tileSize[0] || this.clipTileCanvasHeight_ !== tileSize[1]) { clipTileCanvas.width = tileSize[0]; @@ -229,23 +229,23 @@ WebGLMapRenderer.prototype.bindTileTexture = function(tile, tileSize, tileGutter clipTileContext.clearRect(0, 0, tileSize[0], tileSize[1]); } clipTileContext.drawImage(tile.getImage(), tileGutter, tileGutter, - tileSize[0], tileSize[1], 0, 0, tileSize[0], tileSize[1]); + tileSize[0], tileSize[1], 0, 0, tileSize[0], tileSize[1]); gl.texImage2D(_ol_webgl_.TEXTURE_2D, 0, - _ol_webgl_.RGBA, _ol_webgl_.RGBA, - _ol_webgl_.UNSIGNED_BYTE, clipTileCanvas); + _ol_webgl_.RGBA, _ol_webgl_.RGBA, + _ol_webgl_.UNSIGNED_BYTE, clipTileCanvas); } else { gl.texImage2D(_ol_webgl_.TEXTURE_2D, 0, - _ol_webgl_.RGBA, _ol_webgl_.RGBA, - _ol_webgl_.UNSIGNED_BYTE, tile.getImage()); + _ol_webgl_.RGBA, _ol_webgl_.RGBA, + _ol_webgl_.UNSIGNED_BYTE, tile.getImage()); } gl.texParameteri( - _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_MAG_FILTER, magFilter); + _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_MAG_FILTER, magFilter); gl.texParameteri( - _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_MIN_FILTER, minFilter); + _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_MIN_FILTER, minFilter); gl.texParameteri(_ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_WRAP_S, - _ol_webgl_.CLAMP_TO_EDGE); + _ol_webgl_.CLAMP_TO_EDGE); gl.texParameteri(_ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_WRAP_T, - _ol_webgl_.CLAMP_TO_EDGE); + _ol_webgl_.CLAMP_TO_EDGE); this.textureCache_.set(tileKey, { texture: texture, magFilter: magFilter, @@ -261,23 +261,23 @@ WebGLMapRenderer.prototype.bindTileTexture = function(tile, tileSize, tileGutter * @private */ WebGLMapRenderer.prototype.dispatchComposeEvent_ = function(type, frameState) { - var map = this.getMap(); + const map = this.getMap(); if (map.hasListener(type)) { - var context = this.context_; + const context = this.context_; - var extent = frameState.extent; - var size = frameState.size; - var viewState = frameState.viewState; - var pixelRatio = frameState.pixelRatio; + const extent = frameState.extent; + const size = frameState.size; + const viewState = frameState.viewState; + const pixelRatio = frameState.pixelRatio; - var resolution = viewState.resolution; - var center = viewState.center; - var rotation = viewState.rotation; + const resolution = viewState.resolution; + const center = viewState.center; + const rotation = viewState.rotation; - var vectorContext = new _ol_render_webgl_Immediate_(context, - center, resolution, rotation, size, extent, pixelRatio); - var composeEvent = new RenderEvent(type, vectorContext, - frameState, null, context); + const vectorContext = new _ol_render_webgl_Immediate_(context, + center, resolution, rotation, size, extent, pixelRatio); + const composeEvent = new RenderEvent(type, vectorContext, + frameState, null, context); map.dispatchEvent(composeEvent); } }; @@ -287,18 +287,18 @@ WebGLMapRenderer.prototype.dispatchComposeEvent_ = function(type, frameState) { * @inheritDoc */ WebGLMapRenderer.prototype.disposeInternal = function() { - var gl = this.getGL(); + const gl = this.getGL(); if (!gl.isContextLost()) { this.textureCache_.forEach( - /** + /** * @param {?ol.WebglTextureCacheEntry} textureCacheEntry * Texture cache entry. */ - function(textureCacheEntry) { - if (textureCacheEntry) { - gl.deleteTexture(textureCacheEntry.texture); - } - }); + function(textureCacheEntry) { + if (textureCacheEntry) { + gl.deleteTexture(textureCacheEntry.texture); + } + }); } this.context_.dispose(); MapRenderer.prototype.disposeInternal.call(this); @@ -311,8 +311,8 @@ WebGLMapRenderer.prototype.disposeInternal = function() { * @private */ WebGLMapRenderer.prototype.expireCache_ = function(map, frameState) { - var gl = this.getGL(); - var textureCacheEntry; + const gl = this.getGL(); + let textureCacheEntry; while (this.textureCache_.getCount() - this.textureCacheFrameMarkerCount_ > WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK) { textureCacheEntry = this.textureCache_.peekLast(); @@ -371,9 +371,9 @@ WebGLMapRenderer.prototype.handleWebGLContextLost = function(event) { this.textureCache_.clear(); this.textureCacheFrameMarkerCount_ = 0; - var renderers = this.getLayerRenderers(); - for (var id in renderers) { - var renderer = /** @type {ol.renderer.webgl.Layer} */ (renderers[id]); + const renderers = this.getLayerRenderers(); + for (const id in renderers) { + const renderer = /** @type {ol.renderer.webgl.Layer} */ (renderers[id]); renderer.handleWebGLContextLost(); } }; @@ -392,11 +392,11 @@ WebGLMapRenderer.prototype.handleWebGLContextRestored = function() { * @private */ WebGLMapRenderer.prototype.initializeGL_ = function() { - var gl = this.gl_; + const gl = this.gl_; gl.activeTexture(_ol_webgl_.TEXTURE0); gl.blendFuncSeparate( - _ol_webgl_.SRC_ALPHA, _ol_webgl_.ONE_MINUS_SRC_ALPHA, - _ol_webgl_.ONE, _ol_webgl_.ONE_MINUS_SRC_ALPHA); + _ol_webgl_.SRC_ALPHA, _ol_webgl_.ONE_MINUS_SRC_ALPHA, + _ol_webgl_.ONE, _ol_webgl_.ONE_MINUS_SRC_ALPHA); gl.disable(_ol_webgl_.CULL_FACE); gl.disable(_ol_webgl_.DEPTH_TEST); gl.disable(_ol_webgl_.SCISSOR_TEST); @@ -418,8 +418,8 @@ WebGLMapRenderer.prototype.isTileTextureLoaded = function(tile) { */ WebGLMapRenderer.prototype.renderFrame = function(frameState) { - var context = this.getContext(); - var gl = this.getGL(); + const context = this.getContext(); + const gl = this.getGL(); if (gl.isContextLost()) { return false; @@ -441,12 +441,12 @@ WebGLMapRenderer.prototype.renderFrame = function(frameState) { this.dispatchComposeEvent_(RenderEventType.PRECOMPOSE, frameState); /** @type {Array.} */ - var layerStatesToDraw = []; - var layerStatesArray = frameState.layerStatesArray; + const layerStatesToDraw = []; + const layerStatesArray = frameState.layerStatesArray; stableSort(layerStatesArray, MapRenderer.sortByZIndex); - var viewResolution = frameState.viewState.resolution; - var i, ii, layerRenderer, layerState; + const viewResolution = frameState.viewState.resolution; + let i, ii, layerRenderer, layerState; for (i = 0, ii = layerStatesArray.length; i < ii; ++i) { layerState = layerStatesArray[i]; if (Layer.visibleAtResolution(layerState, viewResolution) && @@ -458,8 +458,8 @@ WebGLMapRenderer.prototype.renderFrame = function(frameState) { } } - var width = frameState.size[0] * frameState.pixelRatio; - var height = frameState.size[1] * frameState.pixelRatio; + const width = frameState.size[0] * frameState.pixelRatio; + const height = frameState.size[1] * frameState.pixelRatio; if (this.canvas_.width != width || this.canvas_.height != height) { this.canvas_.width = width; this.canvas_.height = height; @@ -488,7 +488,7 @@ WebGLMapRenderer.prototype.renderFrame = function(frameState) { if (this.textureCache_.getCount() - this.textureCacheFrameMarkerCount_ > WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK) { frameState.postRenderFunctions.push( - /** @type {ol.PostRenderFunction} */ (this.expireCache_.bind(this)) + /** @type {ol.PostRenderFunction} */ (this.expireCache_.bind(this)) ); } @@ -509,26 +509,26 @@ WebGLMapRenderer.prototype.renderFrame = function(frameState) { * @inheritDoc */ WebGLMapRenderer.prototype.forEachFeatureAtCoordinate = function(coordinate, frameState, hitTolerance, callback, thisArg, - layerFilter, thisArg2) { - var result; + layerFilter, thisArg2) { + let result; if (this.getGL().isContextLost()) { return false; } - var viewState = frameState.viewState; + const viewState = frameState.viewState; - var layerStates = frameState.layerStatesArray; - var numLayers = layerStates.length; - var i; + const layerStates = frameState.layerStatesArray; + const numLayers = layerStates.length; + let i; for (i = numLayers - 1; i >= 0; --i) { - var layerState = layerStates[i]; - var layer = layerState.layer; + const layerState = layerStates[i]; + const layer = layerState.layer; if (Layer.visibleAtResolution(layerState, viewState.resolution) && layerFilter.call(thisArg2, layer)) { - var layerRenderer = this.getLayerRenderer(layer); + const layerRenderer = this.getLayerRenderer(layer); result = layerRenderer.forEachFeatureAtCoordinate( - coordinate, frameState, hitTolerance, callback, thisArg); + coordinate, frameState, hitTolerance, callback, thisArg); if (result) { return result; } @@ -542,23 +542,23 @@ WebGLMapRenderer.prototype.forEachFeatureAtCoordinate = function(coordinate, fra * @inheritDoc */ WebGLMapRenderer.prototype.hasFeatureAtCoordinate = function(coordinate, frameState, hitTolerance, layerFilter, thisArg) { - var hasFeature = false; + let hasFeature = false; if (this.getGL().isContextLost()) { return false; } - var viewState = frameState.viewState; + const viewState = frameState.viewState; - var layerStates = frameState.layerStatesArray; - var numLayers = layerStates.length; - var i; + const layerStates = frameState.layerStatesArray; + const numLayers = layerStates.length; + let i; for (i = numLayers - 1; i >= 0; --i) { - var layerState = layerStates[i]; - var layer = layerState.layer; + const layerState = layerStates[i]; + const layer = layerState.layer; if (Layer.visibleAtResolution(layerState, viewState.resolution) && layerFilter.call(thisArg, layer)) { - var layerRenderer = this.getLayerRenderer(layer); + const layerRenderer = this.getLayerRenderer(layer); hasFeature = layerRenderer.hasFeatureAtCoordinate(coordinate, frameState); if (hasFeature) { @@ -574,25 +574,25 @@ WebGLMapRenderer.prototype.hasFeatureAtCoordinate = function(coordinate, frameSt * @inheritDoc */ WebGLMapRenderer.prototype.forEachLayerAtPixel = function(pixel, frameState, callback, thisArg, - layerFilter, thisArg2) { + layerFilter, thisArg2) { if (this.getGL().isContextLost()) { return false; } - var viewState = frameState.viewState; - var result; + const viewState = frameState.viewState; + let result; - var layerStates = frameState.layerStatesArray; - var numLayers = layerStates.length; - var i; + const layerStates = frameState.layerStatesArray; + const numLayers = layerStates.length; + let i; for (i = numLayers - 1; i >= 0; --i) { - var layerState = layerStates[i]; - var layer = layerState.layer; + const layerState = layerStates[i]; + const layer = layerState.layer; if (Layer.visibleAtResolution(layerState, viewState.resolution) && layerFilter.call(thisArg, layer)) { - var layerRenderer = /** @type {ol.renderer.webgl.Layer} */ (this.getLayerRenderer(layer)); + const layerRenderer = /** @type {ol.renderer.webgl.Layer} */ (this.getLayerRenderer(layer)); result = layerRenderer.forEachLayerAtPixel( - pixel, frameState, callback, thisArg); + pixel, frameState, callback, thisArg); if (result) { return result; } diff --git a/src/ol/renderer/webgl/TileLayer.js b/src/ol/renderer/webgl/TileLayer.js index 826ac6b56a..6444483e62 100644 --- a/src/ol/renderer/webgl/TileLayer.js +++ b/src/ol/renderer/webgl/TileLayer.js @@ -27,7 +27,7 @@ import _ol_webgl_Buffer_ from '../../webgl/Buffer.js'; * @param {ol.layer.Tile} tileLayer Tile layer. * @api */ -var WebGLTileLayerRenderer = function(mapRenderer, tileLayer) { +const WebGLTileLayerRenderer = function(mapRenderer, tileLayer) { WebGLLayerRenderer.call(this, mapRenderer, tileLayer); @@ -108,8 +108,8 @@ WebGLTileLayerRenderer['handles'] = function(type, layer) { */ WebGLTileLayerRenderer['create'] = function(mapRenderer, layer) { return new WebGLTileLayerRenderer( - /** @type {ol.renderer.webgl.Map} */ (mapRenderer), - /** @type {ol.layer.Tile} */ (layer) + /** @type {ol.renderer.webgl.Map} */ (mapRenderer), + /** @type {ol.layer.Tile} */ (layer) ); }; @@ -118,7 +118,7 @@ WebGLTileLayerRenderer['create'] = function(mapRenderer, layer) { * @inheritDoc */ WebGLTileLayerRenderer.prototype.disposeInternal = function() { - var context = this.mapRenderer.getContext(); + const context = this.mapRenderer.getContext(); context.deleteBuffer(this.renderArrayBuffer_); WebGLLayerRenderer.prototype.disposeInternal.call(this); }; @@ -128,7 +128,7 @@ WebGLTileLayerRenderer.prototype.disposeInternal = function() { * @inheritDoc */ WebGLTileLayerRenderer.prototype.createLoadedTileFinder = function(source, projection, tiles) { - var mapRenderer = this.mapRenderer; + const mapRenderer = this.mapRenderer; return ( /** @@ -138,7 +138,7 @@ WebGLTileLayerRenderer.prototype.createLoadedTileFinder = function(source, proje */ function(zoom, tileRange) { function callback(tile) { - var loaded = mapRenderer.isTileTextureLoaded(tile); + const loaded = mapRenderer.isTileTextureLoaded(tile); if (loaded) { if (!tiles[zoom]) { tiles[zoom] = {}; @@ -166,47 +166,47 @@ WebGLTileLayerRenderer.prototype.handleWebGLContextLost = function() { */ WebGLTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState, context) { - var mapRenderer = this.mapRenderer; - var gl = context.getGL(); + const mapRenderer = this.mapRenderer; + const gl = context.getGL(); - var viewState = frameState.viewState; - var projection = viewState.projection; + const viewState = frameState.viewState; + const projection = viewState.projection; - var tileLayer = /** @type {ol.layer.Tile} */ (this.getLayer()); - var tileSource = tileLayer.getSource(); - var tileGrid = tileSource.getTileGridForProjection(projection); - var z = tileGrid.getZForResolution(viewState.resolution); - var tileResolution = tileGrid.getResolution(z); + const tileLayer = /** @type {ol.layer.Tile} */ (this.getLayer()); + const tileSource = tileLayer.getSource(); + const tileGrid = tileSource.getTileGridForProjection(projection); + const z = tileGrid.getZForResolution(viewState.resolution); + const tileResolution = tileGrid.getResolution(z); - var tilePixelSize = + const tilePixelSize = tileSource.getTilePixelSize(z, frameState.pixelRatio, projection); - var pixelRatio = tilePixelSize[0] / + const pixelRatio = tilePixelSize[0] / _ol_size_.toSize(tileGrid.getTileSize(z), this.tmpSize_)[0]; - var tilePixelResolution = tileResolution / pixelRatio; - var tileGutter = tileSource.getTilePixelRatio(pixelRatio) * tileSource.getGutter(projection); + const tilePixelResolution = tileResolution / pixelRatio; + const tileGutter = tileSource.getTilePixelRatio(pixelRatio) * tileSource.getGutter(projection); - var center = viewState.center; - var extent = frameState.extent; - var tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z); + const center = viewState.center; + const extent = frameState.extent; + const tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z); - var framebufferExtent; + let framebufferExtent; if (this.renderedTileRange_ && this.renderedTileRange_.equals(tileRange) && this.renderedRevision_ == tileSource.getRevision()) { framebufferExtent = this.renderedFramebufferExtent_; } else { - var tileRangeSize = tileRange.getSize(); + const tileRangeSize = tileRange.getSize(); - var maxDimension = Math.max( - tileRangeSize[0] * tilePixelSize[0], - tileRangeSize[1] * tilePixelSize[1]); - var framebufferDimension = roundUpToPowerOfTwo(maxDimension); - var framebufferExtentDimension = tilePixelResolution * framebufferDimension; - var origin = tileGrid.getOrigin(z); - var minX = origin[0] + + const maxDimension = Math.max( + tileRangeSize[0] * tilePixelSize[0], + tileRangeSize[1] * tilePixelSize[1]); + const framebufferDimension = roundUpToPowerOfTwo(maxDimension); + const framebufferExtentDimension = tilePixelResolution * framebufferDimension; + const origin = tileGrid.getOrigin(z); + const minX = origin[0] + tileRange.minX * tilePixelSize[0] * tilePixelResolution; - var minY = origin[1] + + const minY = origin[1] + tileRange.minY * tilePixelSize[1] * tilePixelResolution; framebufferExtent = [ minX, minY, @@ -220,7 +220,7 @@ WebGLTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState, gl.clear(_ol_webgl_.COLOR_BUFFER_BIT); gl.disable(_ol_webgl_.BLEND); - var program = context.getProgram(this.fragmentShader_, this.vertexShader_); + const program = context.getProgram(this.fragmentShader_, this.vertexShader_); context.useProgram(program); if (!this.locations_) { this.locations_ = new _ol_renderer_webgl_tilelayershader_Locations_(gl, program); @@ -229,27 +229,27 @@ WebGLTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState, context.bindBuffer(_ol_webgl_.ARRAY_BUFFER, this.renderArrayBuffer_); gl.enableVertexAttribArray(this.locations_.a_position); gl.vertexAttribPointer( - this.locations_.a_position, 2, _ol_webgl_.FLOAT, false, 16, 0); + this.locations_.a_position, 2, _ol_webgl_.FLOAT, false, 16, 0); gl.enableVertexAttribArray(this.locations_.a_texCoord); gl.vertexAttribPointer( - this.locations_.a_texCoord, 2, _ol_webgl_.FLOAT, false, 16, 8); + this.locations_.a_texCoord, 2, _ol_webgl_.FLOAT, false, 16, 8); gl.uniform1i(this.locations_.u_texture, 0); /** * @type {Object.>} */ - var tilesToDrawByZ = {}; + const tilesToDrawByZ = {}; tilesToDrawByZ[z] = {}; - var findLoadedTiles = this.createLoadedTileFinder( - tileSource, projection, tilesToDrawByZ); + const findLoadedTiles = this.createLoadedTileFinder( + tileSource, projection, tilesToDrawByZ); - var useInterimTilesOnError = tileLayer.getUseInterimTilesOnError(); - var allTilesLoaded = true; - var tmpExtent = createEmpty(); - var tmpTileRange = new TileRange(0, 0, 0, 0); - var childTileRange, drawable, fullyLoaded, tile, tileState; - var x, y, tileExtent; + const useInterimTilesOnError = tileLayer.getUseInterimTilesOnError(); + let allTilesLoaded = true; + const tmpExtent = createEmpty(); + const tmpTileRange = new TileRange(0, 0, 0, 0); + let childTileRange, drawable, fullyLoaded, tile, tileState; + let x, y, tileExtent; for (x = tileRange.minX; x <= tileRange.maxX; ++x) { for (y = tileRange.minY; y <= tileRange.maxY; ++y) { @@ -282,10 +282,10 @@ WebGLTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState, allTilesLoaded = false; fullyLoaded = tileGrid.forEachTileCoordParentTileRange( - tile.tileCoord, findLoadedTiles, null, tmpTileRange, tmpExtent); + tile.tileCoord, findLoadedTiles, null, tmpTileRange, tmpExtent); if (!fullyLoaded) { childTileRange = tileGrid.getTileCoordChildTileRange( - tile.tileCoord, tmpTileRange, tmpExtent); + tile.tileCoord, tmpTileRange, tmpExtent); if (childTileRange) { findLoadedTiles(z + 1, childTileRange); } @@ -296,10 +296,10 @@ WebGLTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState, } /** @type {Array.} */ - var zs = Object.keys(tilesToDrawByZ).map(Number); + const zs = Object.keys(tilesToDrawByZ).map(Number); zs.sort(numberSafeCompareFunction); - var u_tileOffset = new Float32Array(4); - var i, ii, tileKey, tilesToDraw; + const u_tileOffset = new Float32Array(4); + let i, ii, tileKey, tilesToDraw; for (i = 0, ii = zs.length; i < ii; ++i) { tilesToDraw = tilesToDrawByZ[zs[i]]; for (tileKey in tilesToDraw) { @@ -315,7 +315,7 @@ WebGLTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState, framebufferExtentDimension - 1; gl.uniform4fv(this.locations_.u_tileOffset, u_tileOffset); mapRenderer.bindTileTexture(tile, tilePixelSize, - tileGutter * pixelRatio, _ol_webgl_.LINEAR, _ol_webgl_.LINEAR); + tileGutter * pixelRatio, _ol_webgl_.LINEAR, _ol_webgl_.LINEAR); gl.drawArrays(_ol_webgl_.TRIANGLE_STRIP, 0, 4); } } @@ -334,41 +334,41 @@ WebGLTileLayerRenderer.prototype.prepareFrame = function(frameState, layerState, } this.updateUsedTiles(frameState.usedTiles, tileSource, z, tileRange); - var tileTextureQueue = mapRenderer.getTileTextureQueue(); + const tileTextureQueue = mapRenderer.getTileTextureQueue(); this.manageTilePyramid( - frameState, tileSource, tileGrid, pixelRatio, projection, extent, z, - tileLayer.getPreload(), - /** + frameState, tileSource, tileGrid, pixelRatio, projection, extent, z, + tileLayer.getPreload(), + /** * @param {ol.Tile} tile Tile. */ - function(tile) { - if (tile.getState() == TileState.LOADED && + function(tile) { + if (tile.getState() == TileState.LOADED && !mapRenderer.isTileTextureLoaded(tile) && !tileTextureQueue.isKeyQueued(tile.getKey())) { - tileTextureQueue.enqueue([ - tile, - tileGrid.getTileCoordCenter(tile.tileCoord), - tileGrid.getResolution(tile.tileCoord[0]), - tilePixelSize, tileGutter * pixelRatio - ]); - } - }, this); + tileTextureQueue.enqueue([ + tile, + tileGrid.getTileCoordCenter(tile.tileCoord), + tileGrid.getResolution(tile.tileCoord[0]), + tilePixelSize, tileGutter * pixelRatio + ]); + } + }, this); this.scheduleExpireCache(frameState, tileSource); - var texCoordMatrix = this.texCoordMatrix; + const texCoordMatrix = this.texCoordMatrix; _ol_transform_.reset(texCoordMatrix); _ol_transform_.translate(texCoordMatrix, - (Math.round(center[0] / tileResolution) * tileResolution - framebufferExtent[0]) / + (Math.round(center[0] / tileResolution) * tileResolution - framebufferExtent[0]) / (framebufferExtent[2] - framebufferExtent[0]), - (Math.round(center[1] / tileResolution) * tileResolution - framebufferExtent[1]) / + (Math.round(center[1] / tileResolution) * tileResolution - framebufferExtent[1]) / (framebufferExtent[3] - framebufferExtent[1])); if (viewState.rotation !== 0) { _ol_transform_.rotate(texCoordMatrix, viewState.rotation); } _ol_transform_.scale(texCoordMatrix, - frameState.size[0] * viewState.resolution / + frameState.size[0] * viewState.resolution / (framebufferExtent[2] - framebufferExtent[0]), - frameState.size[1] * viewState.resolution / + frameState.size[1] * viewState.resolution / (framebufferExtent[3] - framebufferExtent[1])); _ol_transform_.translate(texCoordMatrix, -0.5, -0.5); @@ -384,21 +384,21 @@ WebGLTileLayerRenderer.prototype.forEachLayerAtPixel = function(pixel, frameStat return undefined; } - var pixelOnMapScaled = [ + const pixelOnMapScaled = [ pixel[0] / frameState.size[0], (frameState.size[1] - pixel[1]) / frameState.size[1]]; - var pixelOnFrameBufferScaled = _ol_transform_.apply( - this.texCoordMatrix, pixelOnMapScaled.slice()); - var pixelOnFrameBuffer = [ + const pixelOnFrameBufferScaled = _ol_transform_.apply( + this.texCoordMatrix, pixelOnMapScaled.slice()); + const pixelOnFrameBuffer = [ pixelOnFrameBufferScaled[0] * this.framebufferDimension, pixelOnFrameBufferScaled[1] * this.framebufferDimension]; - var gl = this.mapRenderer.getContext().getGL(); + const gl = this.mapRenderer.getContext().getGL(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); - var imageData = new Uint8Array(4); + const imageData = new Uint8Array(4); gl.readPixels(pixelOnFrameBuffer[0], pixelOnFrameBuffer[1], 1, 1, - gl.RGBA, gl.UNSIGNED_BYTE, imageData); + gl.RGBA, gl.UNSIGNED_BYTE, imageData); if (imageData[3] > 0) { return callback.call(thisArg, this.getLayer(), imageData); diff --git a/src/ol/renderer/webgl/VectorLayer.js b/src/ol/renderer/webgl/VectorLayer.js index 44a8a6052d..9ebc78a646 100644 --- a/src/ol/renderer/webgl/VectorLayer.js +++ b/src/ol/renderer/webgl/VectorLayer.js @@ -18,7 +18,7 @@ import _ol_transform_ from '../../transform.js'; * @param {ol.layer.Vector} vectorLayer Vector layer. * @api */ -var WebGLVectorLayerRenderer = function(mapRenderer, vectorLayer) { +const WebGLVectorLayerRenderer = function(mapRenderer, vectorLayer) { WebGLLayerRenderer.call(this, mapRenderer, vectorLayer); @@ -89,8 +89,8 @@ WebGLVectorLayerRenderer['handles'] = function(type, layer) { */ WebGLVectorLayerRenderer['create'] = function(mapRenderer, layer) { return new WebGLVectorLayerRenderer( - /** @type {ol.renderer.webgl.Map} */ (mapRenderer), - /** @type {ol.layer.Vector} */ (layer) + /** @type {ol.renderer.webgl.Map} */ (mapRenderer), + /** @type {ol.layer.Vector} */ (layer) ); }; @@ -100,18 +100,18 @@ WebGLVectorLayerRenderer['create'] = function(mapRenderer, layer) { */ WebGLVectorLayerRenderer.prototype.composeFrame = function(frameState, layerState, context) { this.layerState_ = layerState; - var viewState = frameState.viewState; - var replayGroup = this.replayGroup_; - var size = frameState.size; - var pixelRatio = frameState.pixelRatio; - var gl = this.mapRenderer.getGL(); + const viewState = frameState.viewState; + const replayGroup = this.replayGroup_; + const size = frameState.size; + const pixelRatio = frameState.pixelRatio; + const gl = this.mapRenderer.getGL(); if (replayGroup && !replayGroup.isEmpty()) { gl.enable(gl.SCISSOR_TEST); gl.scissor(0, 0, size[0] * pixelRatio, size[1] * pixelRatio); replayGroup.replay(context, - viewState.center, viewState.resolution, viewState.rotation, - size, pixelRatio, layerState.opacity, - layerState.managed ? frameState.skippedFeatureUids : {}); + viewState.center, viewState.resolution, viewState.rotation, + size, pixelRatio, layerState.opacity, + layerState.managed ? frameState.skippedFeatureUids : {}); gl.disable(gl.SCISSOR_TEST); } @@ -122,9 +122,9 @@ WebGLVectorLayerRenderer.prototype.composeFrame = function(frameState, layerStat * @inheritDoc */ WebGLVectorLayerRenderer.prototype.disposeInternal = function() { - var replayGroup = this.replayGroup_; + const replayGroup = this.replayGroup_; if (replayGroup) { - var context = this.mapRenderer.getContext(); + const context = this.mapRenderer.getContext(); replayGroup.getDeleteResourcesFunction(context)(); this.replayGroup_ = null; } @@ -139,27 +139,27 @@ WebGLVectorLayerRenderer.prototype.forEachFeatureAtCoordinate = function(coordin if (!this.replayGroup_ || !this.layerState_) { return undefined; } else { - var context = this.mapRenderer.getContext(); - var viewState = frameState.viewState; - var layer = this.getLayer(); - var layerState = this.layerState_; + const context = this.mapRenderer.getContext(); + const viewState = frameState.viewState; + const layer = this.getLayer(); + const layerState = this.layerState_; /** @type {Object.} */ - var features = {}; + const features = {}; return this.replayGroup_.forEachFeatureAtCoordinate(coordinate, - context, viewState.center, viewState.resolution, viewState.rotation, - frameState.size, frameState.pixelRatio, layerState.opacity, - {}, - /** + context, viewState.center, viewState.resolution, viewState.rotation, + frameState.size, frameState.pixelRatio, layerState.opacity, + {}, + /** * @param {ol.Feature|ol.render.Feature} feature Feature. * @return {?} Callback result. */ - function(feature) { - var key = getUid(feature).toString(); - if (!(key in features)) { - features[key] = true; - return callback.call(thisArg, feature, layer); - } - }); + function(feature) { + const key = getUid(feature).toString(); + if (!(key in features)) { + features[key] = true; + return callback.call(thisArg, feature, layer); + } + }); } }; @@ -171,13 +171,13 @@ WebGLVectorLayerRenderer.prototype.hasFeatureAtCoordinate = function(coordinate, if (!this.replayGroup_ || !this.layerState_) { return false; } else { - var context = this.mapRenderer.getContext(); - var viewState = frameState.viewState; - var layerState = this.layerState_; + const context = this.mapRenderer.getContext(); + const viewState = frameState.viewState; + const layerState = this.layerState_; return this.replayGroup_.hasFeatureAtCoordinate(coordinate, - context, viewState.center, viewState.resolution, viewState.rotation, - frameState.size, frameState.pixelRatio, layerState.opacity, - frameState.skippedFeatureUids); + context, viewState.center, viewState.resolution, viewState.rotation, + frameState.size, frameState.pixelRatio, layerState.opacity, + frameState.skippedFeatureUids); } }; @@ -186,9 +186,9 @@ WebGLVectorLayerRenderer.prototype.hasFeatureAtCoordinate = function(coordinate, * @inheritDoc */ WebGLVectorLayerRenderer.prototype.forEachLayerAtPixel = function(pixel, frameState, callback, thisArg) { - var coordinate = _ol_transform_.apply( - frameState.pixelToCoordinateTransform, pixel.slice()); - var hasFeature = this.hasFeatureAtCoordinate(coordinate, frameState); + const coordinate = _ol_transform_.apply( + frameState.pixelToCoordinateTransform, pixel.slice()); + const hasFeature = this.hasFeatureAtCoordinate(coordinate, frameState); if (hasFeature) { return callback.call(thisArg, this.getLayer(), null); @@ -212,34 +212,34 @@ WebGLVectorLayerRenderer.prototype.handleStyleImageChange_ = function(event) { * @inheritDoc */ WebGLVectorLayerRenderer.prototype.prepareFrame = function(frameState, layerState, context) { - var vectorLayer = /** @type {ol.layer.Vector} */ (this.getLayer()); - var vectorSource = vectorLayer.getSource(); + const vectorLayer = /** @type {ol.layer.Vector} */ (this.getLayer()); + const vectorSource = vectorLayer.getSource(); - var animating = frameState.viewHints[ViewHint.ANIMATING]; - var interacting = frameState.viewHints[ViewHint.INTERACTING]; - var updateWhileAnimating = vectorLayer.getUpdateWhileAnimating(); - var updateWhileInteracting = vectorLayer.getUpdateWhileInteracting(); + const animating = frameState.viewHints[ViewHint.ANIMATING]; + const interacting = frameState.viewHints[ViewHint.INTERACTING]; + const updateWhileAnimating = vectorLayer.getUpdateWhileAnimating(); + const updateWhileInteracting = vectorLayer.getUpdateWhileInteracting(); if (!this.dirty_ && (!updateWhileAnimating && animating) || (!updateWhileInteracting && interacting)) { return true; } - var frameStateExtent = frameState.extent; - var viewState = frameState.viewState; - var projection = viewState.projection; - var resolution = viewState.resolution; - var pixelRatio = frameState.pixelRatio; - var vectorLayerRevision = vectorLayer.getRevision(); - var vectorLayerRenderBuffer = vectorLayer.getRenderBuffer(); - var vectorLayerRenderOrder = vectorLayer.getRenderOrder(); + const frameStateExtent = frameState.extent; + const viewState = frameState.viewState; + const projection = viewState.projection; + const resolution = viewState.resolution; + const pixelRatio = frameState.pixelRatio; + const vectorLayerRevision = vectorLayer.getRevision(); + const vectorLayerRenderBuffer = vectorLayer.getRenderBuffer(); + let vectorLayerRenderOrder = vectorLayer.getRenderOrder(); if (vectorLayerRenderOrder === undefined) { vectorLayerRenderOrder = _ol_renderer_vector_.defaultOrder; } - var extent = buffer(frameStateExtent, - vectorLayerRenderBuffer * resolution); + const extent = buffer(frameStateExtent, + vectorLayerRenderBuffer * resolution); if (!this.dirty_ && this.renderedResolution_ == resolution && @@ -251,22 +251,22 @@ WebGLVectorLayerRenderer.prototype.prepareFrame = function(frameState, layerStat if (this.replayGroup_) { frameState.postRenderFunctions.push( - this.replayGroup_.getDeleteResourcesFunction(context)); + this.replayGroup_.getDeleteResourcesFunction(context)); } this.dirty_ = false; - var replayGroup = new _ol_render_webgl_ReplayGroup_( - _ol_renderer_vector_.getTolerance(resolution, pixelRatio), - extent, vectorLayer.getRenderBuffer()); + const replayGroup = new _ol_render_webgl_ReplayGroup_( + _ol_renderer_vector_.getTolerance(resolution, pixelRatio), + extent, vectorLayer.getRenderBuffer()); vectorSource.loadFeatures(extent, resolution, projection); /** * @param {ol.Feature} feature Feature. * @this {ol.renderer.webgl.VectorLayer} */ - var renderFeature = function(feature) { - var styles; - var styleFunction = feature.getStyleFunction(); + const renderFeature = function(feature) { + let styles; + let styleFunction = feature.getStyleFunction(); if (styleFunction) { styles = styleFunction.call(feature, resolution); } else { @@ -276,21 +276,21 @@ WebGLVectorLayerRenderer.prototype.prepareFrame = function(frameState, layerStat } } if (styles) { - var dirty = this.renderFeature( - feature, resolution, pixelRatio, styles, replayGroup); + const dirty = this.renderFeature( + feature, resolution, pixelRatio, styles, replayGroup); this.dirty_ = this.dirty_ || dirty; } }; if (vectorLayerRenderOrder) { /** @type {Array.} */ - var features = []; + const features = []; vectorSource.forEachFeatureInExtent(extent, - /** + /** * @param {ol.Feature} feature Feature. */ - function(feature) { - features.push(feature); - }, this); + function(feature) { + features.push(feature); + }, this); features.sort(vectorLayerRenderOrder); features.forEach(renderFeature.bind(this)); } else { @@ -321,19 +321,19 @@ WebGLVectorLayerRenderer.prototype.renderFeature = function(feature, resolution, if (!styles) { return false; } - var loading = false; + let loading = false; if (Array.isArray(styles)) { - for (var i = styles.length - 1, ii = 0; i >= ii; --i) { + for (let i = styles.length - 1, ii = 0; i >= ii; --i) { loading = _ol_renderer_vector_.renderFeature( - replayGroup, feature, styles[i], - _ol_renderer_vector_.getSquaredTolerance(resolution, pixelRatio), - this.handleStyleImageChange_, this) || loading; + replayGroup, feature, styles[i], + _ol_renderer_vector_.getSquaredTolerance(resolution, pixelRatio), + this.handleStyleImageChange_, this) || loading; } } else { loading = _ol_renderer_vector_.renderFeature( - replayGroup, feature, styles, - _ol_renderer_vector_.getSquaredTolerance(resolution, pixelRatio), - this.handleStyleImageChange_, this) || loading; + replayGroup, feature, styles, + _ol_renderer_vector_.getSquaredTolerance(resolution, pixelRatio), + this.handleStyleImageChange_, this) || loading; } return loading; }; diff --git a/src/ol/renderer/webgl/defaultmapshader.js b/src/ol/renderer/webgl/defaultmapshader.js index 6dacbc9ccd..95ffc98257 100644 --- a/src/ol/renderer/webgl/defaultmapshader.js +++ b/src/ol/renderer/webgl/defaultmapshader.js @@ -4,7 +4,7 @@ import {DEBUG_WEBGL} from '../../index.js'; import _ol_webgl_Fragment_ from '../../webgl/Fragment.js'; import _ol_webgl_Vertex_ from '../../webgl/Vertex.js'; -var _ol_renderer_webgl_defaultmapshader_ = {}; +const _ol_renderer_webgl_defaultmapshader_ = {}; _ol_renderer_webgl_defaultmapshader_.fragment = new _ol_webgl_Fragment_(DEBUG_WEBGL ? 'precision mediump float;\nvarying vec2 v_texCoord;\n\n\nuniform float u_opacity;\nuniform sampler2D u_texture;\n\nvoid main(void) {\n vec4 texColor = texture2D(u_texture, v_texCoord);\n gl_FragColor.rgb = texColor.rgb;\n gl_FragColor.a = texColor.a * u_opacity;\n}\n' : diff --git a/src/ol/renderer/webgl/defaultmapshader/Locations.js b/src/ol/renderer/webgl/defaultmapshader/Locations.js index 95d1b9df9a..64ea2e5809 100644 --- a/src/ol/renderer/webgl/defaultmapshader/Locations.js +++ b/src/ol/renderer/webgl/defaultmapshader/Locations.js @@ -10,43 +10,43 @@ import {DEBUG_WEBGL} from '../../../index.js'; * @param {WebGLProgram} program Program. * @struct */ -var _ol_renderer_webgl_defaultmapshader_Locations_ = function(gl, program) { +const _ol_renderer_webgl_defaultmapshader_Locations_ = function(gl, program) { /** * @type {WebGLUniformLocation} */ this.u_texCoordMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_texCoordMatrix' : 'd'); + program, DEBUG_WEBGL ? 'u_texCoordMatrix' : 'd'); /** * @type {WebGLUniformLocation} */ this.u_projectionMatrix = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_projectionMatrix' : 'e'); + program, DEBUG_WEBGL ? 'u_projectionMatrix' : 'e'); /** * @type {WebGLUniformLocation} */ this.u_opacity = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_opacity' : 'f'); + program, DEBUG_WEBGL ? 'u_opacity' : 'f'); /** * @type {WebGLUniformLocation} */ this.u_texture = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_texture' : 'g'); + program, DEBUG_WEBGL ? 'u_texture' : 'g'); /** * @type {number} */ this.a_position = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_position' : 'b'); + program, DEBUG_WEBGL ? 'a_position' : 'b'); /** * @type {number} */ this.a_texCoord = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_texCoord' : 'c'); + program, DEBUG_WEBGL ? 'a_texCoord' : 'c'); }; export default _ol_renderer_webgl_defaultmapshader_Locations_; diff --git a/src/ol/renderer/webgl/tilelayershader.js b/src/ol/renderer/webgl/tilelayershader.js index ba46f5cb1f..d287187297 100644 --- a/src/ol/renderer/webgl/tilelayershader.js +++ b/src/ol/renderer/webgl/tilelayershader.js @@ -4,7 +4,7 @@ import {DEBUG_WEBGL} from '../../index.js'; import _ol_webgl_Fragment_ from '../../webgl/Fragment.js'; import _ol_webgl_Vertex_ from '../../webgl/Vertex.js'; -var _ol_renderer_webgl_tilelayershader_ = {}; +const _ol_renderer_webgl_tilelayershader_ = {}; _ol_renderer_webgl_tilelayershader_.fragment = new _ol_webgl_Fragment_(DEBUG_WEBGL ? 'precision mediump float;\nvarying vec2 v_texCoord;\n\n\nuniform sampler2D u_texture;\n\nvoid main(void) {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n}\n' : diff --git a/src/ol/renderer/webgl/tilelayershader/Locations.js b/src/ol/renderer/webgl/tilelayershader/Locations.js index a4e80c8362..b5269146d9 100644 --- a/src/ol/renderer/webgl/tilelayershader/Locations.js +++ b/src/ol/renderer/webgl/tilelayershader/Locations.js @@ -10,31 +10,31 @@ import {DEBUG_WEBGL} from '../../../index.js'; * @param {WebGLProgram} program Program. * @struct */ -var _ol_renderer_webgl_tilelayershader_Locations_ = function(gl, program) { +const _ol_renderer_webgl_tilelayershader_Locations_ = function(gl, program) { /** * @type {WebGLUniformLocation} */ this.u_tileOffset = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_tileOffset' : 'd'); + program, DEBUG_WEBGL ? 'u_tileOffset' : 'd'); /** * @type {WebGLUniformLocation} */ this.u_texture = gl.getUniformLocation( - program, DEBUG_WEBGL ? 'u_texture' : 'e'); + program, DEBUG_WEBGL ? 'u_texture' : 'e'); /** * @type {number} */ this.a_position = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_position' : 'b'); + program, DEBUG_WEBGL ? 'a_position' : 'b'); /** * @type {number} */ this.a_texCoord = gl.getAttribLocation( - program, DEBUG_WEBGL ? 'a_texCoord' : 'c'); + program, DEBUG_WEBGL ? 'a_texCoord' : 'c'); }; export default _ol_renderer_webgl_tilelayershader_Locations_; diff --git a/src/ol/reproj.js b/src/ol/reproj.js index 8d5690beea..2ee7718d92 100644 --- a/src/ol/reproj.js +++ b/src/ol/reproj.js @@ -5,7 +5,7 @@ import {createCanvasContext2D} from './dom.js'; import {containsCoordinate, createEmpty, extend, getHeight, getTopLeft, getWidth} from './extent.js'; import {solveLinearSystem} from './math.js'; import {getPointResolution, transform} from './proj.js'; -var _ol_reproj_ = {}; +const _ol_reproj_ = {}; /** @@ -21,18 +21,18 @@ var _ol_reproj_ = {}; * @return {number} The best resolution to use. Can be +-Infinity, NaN or 0. */ _ol_reproj_.calculateSourceResolution = function(sourceProj, targetProj, - targetCenter, targetResolution) { + targetCenter, targetResolution) { - var sourceCenter = transform(targetCenter, targetProj, sourceProj); + const sourceCenter = transform(targetCenter, targetProj, sourceProj); // calculate the ideal resolution of the source data - var sourceResolution = getPointResolution(targetProj, targetResolution, targetCenter); + let sourceResolution = getPointResolution(targetProj, targetResolution, targetCenter); - var targetMetersPerUnit = targetProj.getMetersPerUnit(); + const targetMetersPerUnit = targetProj.getMetersPerUnit(); if (targetMetersPerUnit !== undefined) { sourceResolution *= targetMetersPerUnit; } - var sourceMetersPerUnit = sourceProj.getMetersPerUnit(); + const sourceMetersPerUnit = sourceProj.getMetersPerUnit(); if (sourceMetersPerUnit !== undefined) { sourceResolution /= sourceMetersPerUnit; } @@ -41,9 +41,9 @@ _ol_reproj_.calculateSourceResolution = function(sourceProj, targetProj, // coordinates may be slightly different. We need to reverse-compensate this // in order to achieve optimal results. - var sourceExtent = sourceProj.getExtent(); + const sourceExtent = sourceProj.getExtent(); if (!sourceExtent || containsCoordinate(sourceExtent, sourceCenter)) { - var compensationFactor = getPointResolution(sourceProj, sourceResolution, sourceCenter) / + const compensationFactor = getPointResolution(sourceProj, sourceResolution, sourceCenter) / sourceResolution; if (isFinite(compensationFactor) && compensationFactor > 0) { sourceResolution /= compensationFactor; @@ -66,8 +66,9 @@ _ol_reproj_.calculateSourceResolution = function(sourceProj, targetProj, * @private */ _ol_reproj_.enlargeClipPoint_ = function(centroidX, centroidY, x, y) { - var dX = x - centroidX, dY = y - centroidY; - var distance = Math.sqrt(dX * dX + dY * dY); + const dX = x - centroidX; + const dY = y - centroidY; + const distance = Math.sqrt(dX * dX + dY * dY); return [Math.round(x + dX / distance), Math.round(y + dY / distance)]; }; @@ -91,11 +92,11 @@ _ol_reproj_.enlargeClipPoint_ = function(centroidX, centroidY, x, y) { * @return {HTMLCanvasElement} Canvas with reprojected data. */ _ol_reproj_.render = function(width, height, pixelRatio, - sourceResolution, sourceExtent, targetResolution, targetExtent, - triangulation, sources, gutter, opt_renderEdges) { + sourceResolution, sourceExtent, targetResolution, targetExtent, + triangulation, sources, gutter, opt_renderEdges) { - var context = createCanvasContext2D(Math.round(pixelRatio * width), - Math.round(pixelRatio * height)); + const context = createCanvasContext2D(Math.round(pixelRatio * width), + Math.round(pixelRatio * height)); if (sources.length === 0) { return context.canvas; @@ -103,34 +104,34 @@ _ol_reproj_.render = function(width, height, pixelRatio, context.scale(pixelRatio, pixelRatio); - var sourceDataExtent = createEmpty(); + const sourceDataExtent = createEmpty(); sources.forEach(function(src, i, arr) { extend(sourceDataExtent, src.extent); }); - var canvasWidthInUnits = getWidth(sourceDataExtent); - var canvasHeightInUnits = getHeight(sourceDataExtent); - var stitchContext = createCanvasContext2D( - Math.round(pixelRatio * canvasWidthInUnits / sourceResolution), - Math.round(pixelRatio * canvasHeightInUnits / sourceResolution)); + const canvasWidthInUnits = getWidth(sourceDataExtent); + const canvasHeightInUnits = getHeight(sourceDataExtent); + const stitchContext = createCanvasContext2D( + Math.round(pixelRatio * canvasWidthInUnits / sourceResolution), + Math.round(pixelRatio * canvasHeightInUnits / sourceResolution)); - var stitchScale = pixelRatio / sourceResolution; + const stitchScale = pixelRatio / sourceResolution; sources.forEach(function(src, i, arr) { - var xPos = src.extent[0] - sourceDataExtent[0]; - var yPos = -(src.extent[3] - sourceDataExtent[3]); - var srcWidth = getWidth(src.extent); - var srcHeight = getHeight(src.extent); + const xPos = src.extent[0] - sourceDataExtent[0]; + const yPos = -(src.extent[3] - sourceDataExtent[3]); + const srcWidth = getWidth(src.extent); + const srcHeight = getHeight(src.extent); stitchContext.drawImage( - src.image, - gutter, gutter, - src.image.width - 2 * gutter, src.image.height - 2 * gutter, - xPos * stitchScale, yPos * stitchScale, - srcWidth * stitchScale, srcHeight * stitchScale); + src.image, + gutter, gutter, + src.image.width - 2 * gutter, src.image.height - 2 * gutter, + xPos * stitchScale, yPos * stitchScale, + srcWidth * stitchScale, srcHeight * stitchScale); }); - var targetTopLeft = getTopLeft(targetExtent); + const targetTopLeft = getTopLeft(targetExtent); triangulation.getTriangles().forEach(function(triangle, i, arr) { /* Calculate affine transform (src -> dst) @@ -153,21 +154,23 @@ _ol_reproj_.render = function(width, height, pixelRatio, * | 0 0 0 x1 y1 1 | |a11| |v1| * | 0 0 0 x2 y2 1 | |a12| |v2| */ - var source = triangle.source, target = triangle.target; - var x0 = source[0][0], y0 = source[0][1], - x1 = source[1][0], y1 = source[1][1], - x2 = source[2][0], y2 = source[2][1]; - var u0 = (target[0][0] - targetTopLeft[0]) / targetResolution, - v0 = -(target[0][1] - targetTopLeft[1]) / targetResolution; - var u1 = (target[1][0] - targetTopLeft[0]) / targetResolution, - v1 = -(target[1][1] - targetTopLeft[1]) / targetResolution; - var u2 = (target[2][0] - targetTopLeft[0]) / targetResolution, - v2 = -(target[2][1] - targetTopLeft[1]) / targetResolution; + const source = triangle.source; + const target = triangle.target; + let x0 = source[0][0], y0 = source[0][1]; + let x1 = source[1][0], y1 = source[1][1]; + let x2 = source[2][0], y2 = source[2][1]; + const u0 = (target[0][0] - targetTopLeft[0]) / targetResolution; + const v0 = -(target[0][1] - targetTopLeft[1]) / targetResolution; + const u1 = (target[1][0] - targetTopLeft[0]) / targetResolution; + const v1 = -(target[1][1] - targetTopLeft[1]) / targetResolution; + const u2 = (target[2][0] - targetTopLeft[0]) / targetResolution; + const v2 = -(target[2][1] - targetTopLeft[1]) / targetResolution; // Shift all the source points to improve numerical stability // of all the subsequent calculations. The [x0, y0] is used here. // This is also used to simplify the linear system. - var sourceNumericalShiftX = x0, sourceNumericalShiftY = y0; + const sourceNumericalShiftX = x0; + const sourceNumericalShiftY = y0; x0 = 0; y0 = 0; x1 -= sourceNumericalShiftX; @@ -175,23 +178,24 @@ _ol_reproj_.render = function(width, height, pixelRatio, x2 -= sourceNumericalShiftX; y2 -= sourceNumericalShiftY; - var augmentedMatrix = [ + const augmentedMatrix = [ [x1, y1, 0, 0, u1 - u0], [x2, y2, 0, 0, u2 - u0], [0, 0, x1, y1, v1 - v0], [0, 0, x2, y2, v2 - v0] ]; - var affineCoefs = solveLinearSystem(augmentedMatrix); + const affineCoefs = solveLinearSystem(augmentedMatrix); if (!affineCoefs) { return; } context.save(); context.beginPath(); - var centroidX = (u0 + u1 + u2) / 3, centroidY = (v0 + v1 + v2) / 3; - var p0 = _ol_reproj_.enlargeClipPoint_(centroidX, centroidY, u0, v0); - var p1 = _ol_reproj_.enlargeClipPoint_(centroidX, centroidY, u1, v1); - var p2 = _ol_reproj_.enlargeClipPoint_(centroidX, centroidY, u2, v2); + const centroidX = (u0 + u1 + u2) / 3; + const centroidY = (v0 + v1 + v2) / 3; + const p0 = _ol_reproj_.enlargeClipPoint_(centroidX, centroidY, u0, v0); + const p1 = _ol_reproj_.enlargeClipPoint_(centroidX, centroidY, u1, v1); + const p2 = _ol_reproj_.enlargeClipPoint_(centroidX, centroidY, u2, v2); context.moveTo(p1[0], p1[1]); context.lineTo(p0[0], p0[1]); @@ -199,13 +203,13 @@ _ol_reproj_.render = function(width, height, pixelRatio, context.clip(); context.transform( - affineCoefs[0], affineCoefs[2], affineCoefs[1], affineCoefs[3], u0, v0); + affineCoefs[0], affineCoefs[2], affineCoefs[1], affineCoefs[3], u0, v0); context.translate(sourceDataExtent[0] - sourceNumericalShiftX, - sourceDataExtent[3] - sourceNumericalShiftY); + sourceDataExtent[3] - sourceNumericalShiftY); context.scale(sourceResolution / pixelRatio, - -sourceResolution / pixelRatio); + -sourceResolution / pixelRatio); context.drawImage(stitchContext.canvas, 0, 0); context.restore(); @@ -218,13 +222,13 @@ _ol_reproj_.render = function(width, height, pixelRatio, context.lineWidth = 1; triangulation.getTriangles().forEach(function(triangle, i, arr) { - var target = triangle.target; - var u0 = (target[0][0] - targetTopLeft[0]) / targetResolution, - v0 = -(target[0][1] - targetTopLeft[1]) / targetResolution; - var u1 = (target[1][0] - targetTopLeft[0]) / targetResolution, - v1 = -(target[1][1] - targetTopLeft[1]) / targetResolution; - var u2 = (target[2][0] - targetTopLeft[0]) / targetResolution, - v2 = -(target[2][1] - targetTopLeft[1]) / targetResolution; + const target = triangle.target; + const u0 = (target[0][0] - targetTopLeft[0]) / targetResolution; + const v0 = -(target[0][1] - targetTopLeft[1]) / targetResolution; + const u1 = (target[1][0] - targetTopLeft[0]) / targetResolution; + const v1 = -(target[1][1] - targetTopLeft[1]) / targetResolution; + const u2 = (target[2][0] - targetTopLeft[0]) / targetResolution; + const v2 = -(target[2][1] - targetTopLeft[1]) / targetResolution; context.beginPath(); context.moveTo(u1, v1); diff --git a/src/ol/reproj/Image.js b/src/ol/reproj/Image.js index 69f418fd0d..d427acacee 100644 --- a/src/ol/reproj/Image.js +++ b/src/ol/reproj/Image.js @@ -26,8 +26,8 @@ import Triangulation from '../reproj/Triangulation.js'; * @param {ol.ReprojImageFunctionType} getImageFunction * Function returning source images (extent, resolution, pixelRatio). */ -var ReprojImage = function(sourceProj, targetProj, - targetExtent, targetResolution, pixelRatio, getImageFunction) { +const ReprojImage = function(sourceProj, targetProj, + targetExtent, targetResolution, pixelRatio, getImageFunction) { /** * @private @@ -40,24 +40,24 @@ var ReprojImage = function(sourceProj, targetProj, * @type {ol.Extent} */ this.maxSourceExtent_ = sourceProj.getExtent(); - var maxTargetExtent = targetProj.getExtent(); + const maxTargetExtent = targetProj.getExtent(); - var limitedTargetExtent = maxTargetExtent ? + const limitedTargetExtent = maxTargetExtent ? getIntersection(targetExtent, maxTargetExtent) : targetExtent; - var targetCenter = getCenter(limitedTargetExtent); - var sourceResolution = _ol_reproj_.calculateSourceResolution( - sourceProj, targetProj, targetCenter, targetResolution); + const targetCenter = getCenter(limitedTargetExtent); + const sourceResolution = _ol_reproj_.calculateSourceResolution( + sourceProj, targetProj, targetCenter, targetResolution); - var errorThresholdInPixels = ERROR_THRESHOLD; + const errorThresholdInPixels = ERROR_THRESHOLD; /** * @private * @type {!ol.reproj.Triangulation} */ this.triangulation_ = new Triangulation( - sourceProj, targetProj, limitedTargetExtent, this.maxSourceExtent_, - sourceResolution * errorThresholdInPixels); + sourceProj, targetProj, limitedTargetExtent, this.maxSourceExtent_, + sourceResolution * errorThresholdInPixels); /** * @private @@ -71,7 +71,7 @@ var ReprojImage = function(sourceProj, targetProj, */ this.targetExtent_ = targetExtent; - var sourceExtent = this.triangulation_.calculateSourceExtent(); + const sourceExtent = this.triangulation_.calculateSourceExtent(); /** * @private @@ -100,7 +100,7 @@ var ReprojImage = function(sourceProj, targetProj, this.sourceListenerKey_ = null; - var state = ImageState.LOADED; + let state = ImageState.LOADED; if (this.sourceImage_) { state = ImageState.IDLE; @@ -143,17 +143,17 @@ ReprojImage.prototype.getProjection = function() { * @private */ ReprojImage.prototype.reproject_ = function() { - var sourceState = this.sourceImage_.getState(); + const sourceState = this.sourceImage_.getState(); if (sourceState == ImageState.LOADED) { - var width = getWidth(this.targetExtent_) / this.targetResolution_; - var height = getHeight(this.targetExtent_) / this.targetResolution_; + const width = getWidth(this.targetExtent_) / this.targetResolution_; + const height = getHeight(this.targetExtent_) / this.targetResolution_; this.canvas_ = _ol_reproj_.render(width, height, this.sourcePixelRatio_, - this.sourceImage_.getResolution(), this.maxSourceExtent_, - this.targetResolution_, this.targetExtent_, this.triangulation_, [{ - extent: this.sourceImage_.getExtent(), - image: this.sourceImage_.getImage() - }], 0); + this.sourceImage_.getResolution(), this.maxSourceExtent_, + this.targetResolution_, this.targetExtent_, this.triangulation_, [{ + extent: this.sourceImage_.getExtent(), + image: this.sourceImage_.getImage() + }], 0); } this.state = sourceState; this.changed(); @@ -168,18 +168,18 @@ ReprojImage.prototype.load = function() { this.state = ImageState.LOADING; this.changed(); - var sourceState = this.sourceImage_.getState(); + const sourceState = this.sourceImage_.getState(); if (sourceState == ImageState.LOADED || sourceState == ImageState.ERROR) { this.reproject_(); } else { this.sourceListenerKey_ = _ol_events_.listen(this.sourceImage_, - EventType.CHANGE, function(e) { - var sourceState = this.sourceImage_.getState(); - if (sourceState == ImageState.LOADED || sourceState == ImageState.ERROR) { - this.unlistenSource_(); - this.reproject_(); - } - }, this); + EventType.CHANGE, function(e) { + const sourceState = this.sourceImage_.getState(); + if (sourceState == ImageState.LOADED || sourceState == ImageState.ERROR) { + this.unlistenSource_(); + this.reproject_(); + } + }, this); this.sourceImage_.load(); } } diff --git a/src/ol/reproj/Tile.js b/src/ol/reproj/Tile.js index 7567c0388b..37a2947615 100644 --- a/src/ol/reproj/Tile.js +++ b/src/ol/reproj/Tile.js @@ -32,10 +32,10 @@ import Triangulation from '../reproj/Triangulation.js'; * @param {number=} opt_errorThreshold Acceptable reprojection error (in px). * @param {boolean=} opt_renderEdges Render reprojection edges. */ -var ReprojTile = function(sourceProj, sourceTileGrid, - targetProj, targetTileGrid, tileCoord, wrappedTileCoord, - pixelRatio, gutter, getTileFunction, - opt_errorThreshold, opt_renderEdges) { +const ReprojTile = function(sourceProj, sourceTileGrid, + targetProj, targetTileGrid, tileCoord, wrappedTileCoord, + pixelRatio, gutter, getTileFunction, + opt_errorThreshold, opt_renderEdges) { Tile.call(this, tileCoord, TileState.IDLE); /** @@ -98,11 +98,11 @@ var ReprojTile = function(sourceProj, sourceTileGrid, */ this.sourceZ_ = 0; - var targetExtent = targetTileGrid.getTileCoordExtent(this.wrappedTileCoord_); - var maxTargetExtent = this.targetTileGrid_.getExtent(); - var maxSourceExtent = this.sourceTileGrid_.getExtent(); + const targetExtent = targetTileGrid.getTileCoordExtent(this.wrappedTileCoord_); + const maxTargetExtent = this.targetTileGrid_.getExtent(); + let maxSourceExtent = this.sourceTileGrid_.getExtent(); - var limitedTargetExtent = maxTargetExtent ? + const limitedTargetExtent = maxTargetExtent ? getIntersection(targetExtent, maxTargetExtent) : targetExtent; if (getArea(limitedTargetExtent) === 0) { @@ -112,7 +112,7 @@ var ReprojTile = function(sourceProj, sourceTileGrid, return; } - var sourceProjExtent = sourceProj.getExtent(); + const sourceProjExtent = sourceProj.getExtent(); if (sourceProjExtent) { if (!maxSourceExtent) { maxSourceExtent = sourceProjExtent; @@ -121,12 +121,12 @@ var ReprojTile = function(sourceProj, sourceTileGrid, } } - var targetResolution = targetTileGrid.getResolution( - this.wrappedTileCoord_[0]); + const targetResolution = targetTileGrid.getResolution( + this.wrappedTileCoord_[0]); - var targetCenter = getCenter(limitedTargetExtent); - var sourceResolution = _ol_reproj_.calculateSourceResolution( - sourceProj, targetProj, targetCenter, targetResolution); + const targetCenter = getCenter(limitedTargetExtent); + const sourceResolution = _ol_reproj_.calculateSourceResolution( + sourceProj, targetProj, targetCenter, targetResolution); if (!isFinite(sourceResolution) || sourceResolution <= 0) { // invalid sourceResolution -> EMPTY @@ -135,7 +135,7 @@ var ReprojTile = function(sourceProj, sourceTileGrid, return; } - var errorThresholdInPixels = opt_errorThreshold !== undefined ? + const errorThresholdInPixels = opt_errorThreshold !== undefined ? opt_errorThreshold : ERROR_THRESHOLD; /** @@ -143,8 +143,8 @@ var ReprojTile = function(sourceProj, sourceTileGrid, * @type {!ol.reproj.Triangulation} */ this.triangulation_ = new Triangulation( - sourceProj, targetProj, limitedTargetExtent, maxSourceExtent, - sourceResolution * errorThresholdInPixels); + sourceProj, targetProj, limitedTargetExtent, maxSourceExtent, + sourceResolution * errorThresholdInPixels); if (this.triangulation_.getTriangles().length === 0) { // no valid triangles -> EMPTY @@ -153,14 +153,14 @@ var ReprojTile = function(sourceProj, sourceTileGrid, } this.sourceZ_ = sourceTileGrid.getZForResolution(sourceResolution); - var sourceExtent = this.triangulation_.calculateSourceExtent(); + let sourceExtent = this.triangulation_.calculateSourceExtent(); if (maxSourceExtent) { if (sourceProj.canWrapX()) { sourceExtent[1] = clamp( - sourceExtent[1], maxSourceExtent[1], maxSourceExtent[3]); + sourceExtent[1], maxSourceExtent[1], maxSourceExtent[3]); sourceExtent[3] = clamp( - sourceExtent[3], maxSourceExtent[1], maxSourceExtent[3]); + sourceExtent[3], maxSourceExtent[1], maxSourceExtent[3]); } else { sourceExtent = getIntersection(sourceExtent, maxSourceExtent); } @@ -169,12 +169,12 @@ var ReprojTile = function(sourceProj, sourceTileGrid, if (!getArea(sourceExtent)) { this.state = TileState.EMPTY; } else { - var sourceRange = sourceTileGrid.getTileRangeForExtentAndZ( - sourceExtent, this.sourceZ_); + const sourceRange = sourceTileGrid.getTileRangeForExtentAndZ( + sourceExtent, this.sourceZ_); - for (var srcX = sourceRange.minX; srcX <= sourceRange.maxX; srcX++) { - for (var srcY = sourceRange.minY; srcY <= sourceRange.maxY; srcY++) { - var tile = getTileFunction(this.sourceZ_, srcX, srcY, pixelRatio); + for (let srcX = sourceRange.minX; srcX <= sourceRange.maxX; srcX++) { + for (let srcY = sourceRange.minY; srcY <= sourceRange.maxY; srcY++) { + const tile = getTileFunction(this.sourceZ_, srcX, srcY, pixelRatio); if (tile) { this.sourceTiles_.push(tile); } @@ -214,7 +214,7 @@ ReprojTile.prototype.getImage = function() { * @private */ ReprojTile.prototype.reproject_ = function() { - var sources = []; + const sources = []; this.sourceTiles_.forEach(function(tile, i, arr) { if (tile && tile.getState() == TileState.LOADED) { sources.push({ @@ -228,19 +228,19 @@ ReprojTile.prototype.reproject_ = function() { if (sources.length === 0) { this.state = TileState.ERROR; } else { - var z = this.wrappedTileCoord_[0]; - var size = this.targetTileGrid_.getTileSize(z); - var width = typeof size === 'number' ? size : size[0]; - var height = typeof size === 'number' ? size : size[1]; - var targetResolution = this.targetTileGrid_.getResolution(z); - var sourceResolution = this.sourceTileGrid_.getResolution(this.sourceZ_); + const z = this.wrappedTileCoord_[0]; + const size = this.targetTileGrid_.getTileSize(z); + const width = typeof size === 'number' ? size : size[0]; + const height = typeof size === 'number' ? size : size[1]; + const targetResolution = this.targetTileGrid_.getResolution(z); + const sourceResolution = this.sourceTileGrid_.getResolution(this.sourceZ_); - var targetExtent = this.targetTileGrid_.getTileCoordExtent( - this.wrappedTileCoord_); + const targetExtent = this.targetTileGrid_.getTileCoordExtent( + this.wrappedTileCoord_); this.canvas_ = _ol_reproj_.render(width, height, this.pixelRatio_, - sourceResolution, this.sourceTileGrid_.getExtent(), - targetResolution, targetExtent, this.triangulation_, sources, - this.gutter_, this.renderEdges_); + sourceResolution, this.sourceTileGrid_.getExtent(), + targetResolution, targetExtent, this.triangulation_, sources, + this.gutter_, this.renderEdges_); this.state = TileState.LOADED; } @@ -256,35 +256,34 @@ ReprojTile.prototype.load = function() { this.state = TileState.LOADING; this.changed(); - var leftToLoad = 0; + let leftToLoad = 0; this.sourcesListenerKeys_ = []; this.sourceTiles_.forEach(function(tile, i, arr) { - var state = tile.getState(); + const state = tile.getState(); if (state == TileState.IDLE || state == TileState.LOADING) { leftToLoad++; - var sourceListenKey; - sourceListenKey = _ol_events_.listen(tile, EventType.CHANGE, - function(e) { - var state = tile.getState(); - if (state == TileState.LOADED || + const sourceListenKey = _ol_events_.listen(tile, EventType.CHANGE, + function(e) { + const state = tile.getState(); + if (state == TileState.LOADED || state == TileState.ERROR || state == TileState.EMPTY) { - _ol_events_.unlistenByKey(sourceListenKey); - leftToLoad--; - if (leftToLoad === 0) { - this.unlistenSources_(); - this.reproject_(); - } + _ol_events_.unlistenByKey(sourceListenKey); + leftToLoad--; + if (leftToLoad === 0) { + this.unlistenSources_(); + this.reproject_(); } - }, this); + } + }, this); this.sourcesListenerKeys_.push(sourceListenKey); } }.bind(this)); this.sourceTiles_.forEach(function(tile, i, arr) { - var state = tile.getState(); + const state = tile.getState(); if (state == TileState.IDLE) { tile.load(); } diff --git a/src/ol/reproj/Triangulation.js b/src/ol/reproj/Triangulation.js index 1635d872e0..702c092c46 100644 --- a/src/ol/reproj/Triangulation.js +++ b/src/ol/reproj/Triangulation.js @@ -14,7 +14,7 @@ import {getTransform} from '../proj.js'; * At most `2*(2^this)` triangles are created for each triangulated * extent (tile/image). */ -var MAX_SUBDIVISION = 10; +const MAX_SUBDIVISION = 10; /** @@ -26,7 +26,7 @@ var MAX_SUBDIVISION = 10; * subdivison is forced (up to `MAX_SUBDIVISION`). * Default is `0.25`. */ -var MAX_TRIANGLE_WIDTH = 0.25; +const MAX_TRIANGLE_WIDTH = 0.25; /** @@ -41,8 +41,8 @@ var MAX_TRIANGLE_WIDTH = 0.25; * @param {number} errorThreshold Acceptable error (in source units). * @constructor */ -var Triangulation = function(sourceProj, targetProj, targetExtent, - maxSourceExtent, errorThreshold) { +const Triangulation = function(sourceProj, targetProj, targetExtent, + maxSourceExtent, errorThreshold) { /** * @type {ol.proj.Projection} @@ -57,8 +57,8 @@ var Triangulation = function(sourceProj, targetProj, targetExtent, this.targetProj_ = targetProj; /** @type {!Object.} */ - var transformInvCache = {}; - var transformInv = getTransform(this.targetProj_, this.sourceProj_); + let transformInvCache = {}; + const transformInv = getTransform(this.targetProj_, this.sourceProj_); /** * @param {ol.Coordinate} c A coordinate. @@ -66,7 +66,7 @@ var Triangulation = function(sourceProj, targetProj, targetExtent, * @private */ this.transformInv_ = function(c) { - var key = c[0] + '/' + c[1]; + const key = c[0] + '/' + c[1]; if (!transformInvCache[key]) { transformInvCache[key] = transformInv(c); } @@ -121,34 +121,34 @@ var Triangulation = function(sourceProj, targetProj, targetExtent, this.targetWorldWidth_ = this.targetProj_.getExtent() ? getWidth(this.targetProj_.getExtent()) : null; - var destinationTopLeft = getTopLeft(targetExtent); - var destinationTopRight = getTopRight(targetExtent); - var destinationBottomRight = getBottomRight(targetExtent); - var destinationBottomLeft = getBottomLeft(targetExtent); - var sourceTopLeft = this.transformInv_(destinationTopLeft); - var sourceTopRight = this.transformInv_(destinationTopRight); - var sourceBottomRight = this.transformInv_(destinationBottomRight); - var sourceBottomLeft = this.transformInv_(destinationBottomLeft); + const destinationTopLeft = getTopLeft(targetExtent); + const destinationTopRight = getTopRight(targetExtent); + const destinationBottomRight = getBottomRight(targetExtent); + const destinationBottomLeft = getBottomLeft(targetExtent); + const sourceTopLeft = this.transformInv_(destinationTopLeft); + const sourceTopRight = this.transformInv_(destinationTopRight); + const sourceBottomRight = this.transformInv_(destinationBottomRight); + const sourceBottomLeft = this.transformInv_(destinationBottomLeft); this.addQuad_( - destinationTopLeft, destinationTopRight, - destinationBottomRight, destinationBottomLeft, - sourceTopLeft, sourceTopRight, sourceBottomRight, sourceBottomLeft, - MAX_SUBDIVISION); + destinationTopLeft, destinationTopRight, + destinationBottomRight, destinationBottomLeft, + sourceTopLeft, sourceTopRight, sourceBottomRight, sourceBottomLeft, + MAX_SUBDIVISION); if (this.wrapsXInSource_) { - var leftBound = Infinity; + let leftBound = Infinity; this.triangles_.forEach(function(triangle, i, arr) { leftBound = Math.min(leftBound, - triangle.source[0][0], triangle.source[1][0], triangle.source[2][0]); + triangle.source[0][0], triangle.source[1][0], triangle.source[2][0]); }); // Shift triangles to be as close to `leftBound` as possible // (if the distance is more than `worldWidth / 2` it can be closer. this.triangles_.forEach(function(triangle) { if (Math.max(triangle.source[0][0], triangle.source[1][0], - triangle.source[2][0]) - leftBound > this.sourceWorldWidth_ / 2) { - var newTriangle = [[triangle.source[0][0], triangle.source[0][1]], + triangle.source[2][0]) - leftBound > this.sourceWorldWidth_ / 2) { + const newTriangle = [[triangle.source[0][0], triangle.source[0][1]], [triangle.source[1][0], triangle.source[1][1]], [triangle.source[2][0], triangle.source[2][1]]]; if ((newTriangle[0][0] - leftBound) > this.sourceWorldWidth_ / 2) { @@ -164,10 +164,10 @@ var Triangulation = function(sourceProj, targetProj, targetExtent, // Rarely (if the extent contains both the dateline and prime meridian) // the shift can in turn break some triangles. // Detect this here and don't shift in such cases. - var minX = Math.min( - newTriangle[0][0], newTriangle[1][0], newTriangle[2][0]); - var maxX = Math.max( - newTriangle[0][0], newTriangle[1][0], newTriangle[2][0]); + const minX = Math.min( + newTriangle[0][0], newTriangle[1][0], newTriangle[2][0]); + const maxX = Math.max( + newTriangle[0][0], newTriangle[1][0], newTriangle[2][0]); if ((maxX - minX) < this.sourceWorldWidth_ / 2) { triangle.source = newTriangle; } @@ -190,7 +190,7 @@ var Triangulation = function(sourceProj, targetProj, targetExtent, * @private */ Triangulation.prototype.addTriangle_ = function(a, b, c, - aSrc, bSrc, cSrc) { + aSrc, bSrc, cSrc) { this.triangles_.push({ source: [aSrc, bSrc, cSrc], target: [a, b, c] @@ -215,24 +215,24 @@ Triangulation.prototype.addTriangle_ = function(a, b, c, * @private */ Triangulation.prototype.addQuad_ = function(a, b, c, d, - aSrc, bSrc, cSrc, dSrc, maxSubdivision) { + aSrc, bSrc, cSrc, dSrc, maxSubdivision) { - var sourceQuadExtent = boundingExtent([aSrc, bSrc, cSrc, dSrc]); - var sourceCoverageX = this.sourceWorldWidth_ ? + const sourceQuadExtent = boundingExtent([aSrc, bSrc, cSrc, dSrc]); + const sourceCoverageX = this.sourceWorldWidth_ ? getWidth(sourceQuadExtent) / this.sourceWorldWidth_ : null; - var sourceWorldWidth = /** @type {number} */ (this.sourceWorldWidth_); + const sourceWorldWidth = /** @type {number} */ (this.sourceWorldWidth_); // when the quad is wrapped in the source projection // it covers most of the projection extent, but not fully - var wrapsX = this.sourceProj_.canWrapX() && + const wrapsX = this.sourceProj_.canWrapX() && sourceCoverageX > 0.5 && sourceCoverageX < 1; - var needsSubdivision = false; + let needsSubdivision = false; if (maxSubdivision > 0) { if (this.targetProj_.isGlobal() && this.targetWorldWidth_) { - var targetQuadExtent = boundingExtent([a, b, c, d]); - var targetCoverageX = getWidth(targetQuadExtent) / this.targetWorldWidth_; + const targetQuadExtent = boundingExtent([a, b, c, d]); + const targetCoverageX = getWidth(targetQuadExtent) / this.targetWorldWidth_; needsSubdivision |= targetCoverageX > MAX_TRIANGLE_WIDTH; } @@ -264,12 +264,12 @@ Triangulation.prototype.addQuad_ = function(a, b, c, d, if (maxSubdivision > 0) { if (!needsSubdivision) { - var center = [(a[0] + c[0]) / 2, (a[1] + c[1]) / 2]; - var centerSrc = this.transformInv_(center); + const center = [(a[0] + c[0]) / 2, (a[1] + c[1]) / 2]; + const centerSrc = this.transformInv_(center); - var dx; + let dx; if (wrapsX) { - var centerSrcEstimX = + const centerSrcEstimX = (modulo(aSrc[0], sourceWorldWidth) + modulo(cSrc[0], sourceWorldWidth)) / 2; dx = centerSrcEstimX - @@ -277,33 +277,33 @@ Triangulation.prototype.addQuad_ = function(a, b, c, d, } else { dx = (aSrc[0] + cSrc[0]) / 2 - centerSrc[0]; } - var dy = (aSrc[1] + cSrc[1]) / 2 - centerSrc[1]; - var centerSrcErrorSquared = dx * dx + dy * dy; + const dy = (aSrc[1] + cSrc[1]) / 2 - centerSrc[1]; + const centerSrcErrorSquared = dx * dx + dy * dy; needsSubdivision = centerSrcErrorSquared > this.errorThresholdSquared_; } if (needsSubdivision) { if (Math.abs(a[0] - c[0]) <= Math.abs(a[1] - c[1])) { // split horizontally (top & bottom) - var bc = [(b[0] + c[0]) / 2, (b[1] + c[1]) / 2]; - var bcSrc = this.transformInv_(bc); - var da = [(d[0] + a[0]) / 2, (d[1] + a[1]) / 2]; - var daSrc = this.transformInv_(da); + const bc = [(b[0] + c[0]) / 2, (b[1] + c[1]) / 2]; + const bcSrc = this.transformInv_(bc); + const da = [(d[0] + a[0]) / 2, (d[1] + a[1]) / 2]; + const daSrc = this.transformInv_(da); this.addQuad_( - a, b, bc, da, aSrc, bSrc, bcSrc, daSrc, maxSubdivision - 1); + a, b, bc, da, aSrc, bSrc, bcSrc, daSrc, maxSubdivision - 1); this.addQuad_( - da, bc, c, d, daSrc, bcSrc, cSrc, dSrc, maxSubdivision - 1); + da, bc, c, d, daSrc, bcSrc, cSrc, dSrc, maxSubdivision - 1); } else { // split vertically (left & right) - var ab = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; - var abSrc = this.transformInv_(ab); - var cd = [(c[0] + d[0]) / 2, (c[1] + d[1]) / 2]; - var cdSrc = this.transformInv_(cd); + const ab = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; + const abSrc = this.transformInv_(ab); + const cd = [(c[0] + d[0]) / 2, (c[1] + d[1]) / 2]; + const cdSrc = this.transformInv_(cd); this.addQuad_( - a, ab, cd, d, aSrc, abSrc, cdSrc, dSrc, maxSubdivision - 1); + a, ab, cd, d, aSrc, abSrc, cdSrc, dSrc, maxSubdivision - 1); this.addQuad_( - ab, b, c, cd, abSrc, bSrc, cSrc, cdSrc, maxSubdivision - 1); + ab, b, c, cd, abSrc, bSrc, cSrc, cdSrc, maxSubdivision - 1); } return; } @@ -327,10 +327,10 @@ Triangulation.prototype.addQuad_ = function(a, b, c, d, * @return {ol.Extent} Calculated extent. */ Triangulation.prototype.calculateSourceExtent = function() { - var extent = createEmpty(); + const extent = createEmpty(); this.triangles_.forEach(function(triangle, i, arr) { - var src = triangle.source; + const src = triangle.source; extendCoordinate(extent, src[0]); extendCoordinate(extent, src[1]); extendCoordinate(extent, src[2]); diff --git a/src/ol/reproj/common.js b/src/ol/reproj/common.js index 524358e314..6b28ebfe6b 100644 --- a/src/ol/reproj/common.js +++ b/src/ol/reproj/common.js @@ -2,11 +2,11 @@ * @type {number} Default maximum allowed threshold (in pixels) for * reprojection triangulation. */ -export var ERROR_THRESHOLD = 0.5; +export const ERROR_THRESHOLD = 0.5; /** * TODO: decide if we want to expose this as a build flag or remove it * @type {boolean} Enable automatic reprojection of raster sources. Default is * `true`. */ -export var ENABLE_RASTER_REPROJECTION = true; +export const ENABLE_RASTER_REPROJECTION = true; diff --git a/src/ol/size.js b/src/ol/size.js index e9db34087a..662782fd82 100644 --- a/src/ol/size.js +++ b/src/ol/size.js @@ -1,7 +1,7 @@ /** * @module ol/size */ -var _ol_size_ = {}; +const _ol_size_ = {}; /** diff --git a/src/ol/source/BingMaps.js b/src/ol/source/BingMaps.js index 485f0055f7..5b1dc6e65f 100644 --- a/src/ol/source/BingMaps.js +++ b/src/ol/source/BingMaps.js @@ -20,7 +20,7 @@ import _ol_tilegrid_ from '../tilegrid.js'; * @param {olx.source.BingMapsOptions} options Bing Maps options. * @api */ -var BingMaps = function(options) { +const BingMaps = function(options) { /** * @private @@ -65,13 +65,13 @@ var BingMaps = function(options) { */ this.imagerySet_ = options.imagerySet; - var url = 'https://dev.virtualearth.net/REST/v1/Imagery/Metadata/' + + const url = 'https://dev.virtualearth.net/REST/v1/Imagery/Metadata/' + this.imagerySet_ + '?uriScheme=https&include=ImageryProviders&key=' + this.apiKey_ + '&c=' + this.culture_; _ol_net_.jsonp(url, this.handleImageryMetadataResponse.bind(this), undefined, - 'jsonp'); + 'jsonp'); }; @@ -125,14 +125,14 @@ BingMaps.prototype.handleImageryMetadataResponse = function(response) { return; } - var resource = response.resourceSets[0].resources[0]; - var maxZoom = this.maxZoom_ == -1 ? resource.zoomMax : this.maxZoom_; + const resource = response.resourceSets[0].resources[0]; + const maxZoom = this.maxZoom_ == -1 ? resource.zoomMax : this.maxZoom_; - var sourceProjection = this.getProjection(); - var extent = _ol_tilegrid_.extentFromProjection(sourceProjection); - var tileSize = resource.imageWidth == resource.imageHeight ? + const sourceProjection = this.getProjection(); + const extent = _ol_tilegrid_.extentFromProjection(sourceProjection); + const tileSize = resource.imageWidth == resource.imageHeight ? resource.imageWidth : [resource.imageWidth, resource.imageHeight]; - var tileGrid = _ol_tilegrid_.createXYZ({ + const tileGrid = _ol_tilegrid_.createXYZ({ extent: extent, minZoom: resource.zoomMin, maxZoom: maxZoom, @@ -140,54 +140,54 @@ BingMaps.prototype.handleImageryMetadataResponse = function(response) { }); this.tileGrid = tileGrid; - var culture = this.culture_; - var hidpi = this.hidpi_; + const culture = this.culture_; + const hidpi = this.hidpi_; this.tileUrlFunction = createFromTileUrlFunctions( - resource.imageUrlSubdomains.map(function(subdomain) { - var quadKeyTileCoord = [0, 0, 0]; - var imageUrl = resource.imageUrl - .replace('{subdomain}', subdomain) - .replace('{culture}', culture); - return ( - /** + resource.imageUrlSubdomains.map(function(subdomain) { + const quadKeyTileCoord = [0, 0, 0]; + const imageUrl = resource.imageUrl + .replace('{subdomain}', subdomain) + .replace('{culture}', culture); + return ( + /** * @param {ol.TileCoord} tileCoord Tile coordinate. * @param {number} pixelRatio Pixel ratio. * @param {ol.proj.Projection} projection Projection. * @return {string|undefined} Tile URL. */ - function(tileCoord, pixelRatio, projection) { - if (!tileCoord) { - return undefined; - } else { - _ol_tilecoord_.createOrUpdate(tileCoord[0], tileCoord[1], - -tileCoord[2] - 1, quadKeyTileCoord); - var url = imageUrl; - if (hidpi) { - url += '&dpi=d1&device=mobile'; - } - return url.replace('{quadkey}', _ol_tilecoord_.quadKey( - quadKeyTileCoord)); + function(tileCoord, pixelRatio, projection) { + if (!tileCoord) { + return undefined; + } else { + _ol_tilecoord_.createOrUpdate(tileCoord[0], tileCoord[1], + -tileCoord[2] - 1, quadKeyTileCoord); + let url = imageUrl; + if (hidpi) { + url += '&dpi=d1&device=mobile'; } + return url.replace('{quadkey}', _ol_tilecoord_.quadKey( + quadKeyTileCoord)); } - ); - })); + } + ); + })); if (resource.imageryProviders) { - var transform = getTransformFromProjections( - getProjection('EPSG:4326'), this.getProjection()); + const transform = getTransformFromProjections( + getProjection('EPSG:4326'), this.getProjection()); this.setAttributions(function(frameState) { - var attributions = []; - var zoom = frameState.viewState.zoom; + const attributions = []; + const zoom = frameState.viewState.zoom; resource.imageryProviders.map(function(imageryProvider) { - var intersecting = false; - var coverageAreas = imageryProvider.coverageAreas; - for (var i = 0, ii = coverageAreas.length; i < ii; ++i) { - var coverageArea = coverageAreas[i]; + let intersecting = false; + const coverageAreas = imageryProvider.coverageAreas; + for (let i = 0, ii = coverageAreas.length; i < ii; ++i) { + const coverageArea = coverageAreas[i]; if (zoom >= coverageArea.zoomMin && zoom <= coverageArea.zoomMax) { - var bbox = coverageArea.bbox; - var epsg4326Extent = [bbox[1], bbox[0], bbox[3], bbox[2]]; - var extent = applyTransform(epsg4326Extent, transform); + const bbox = coverageArea.bbox; + const epsg4326Extent = [bbox[1], bbox[0], bbox[3], bbox[2]]; + const extent = applyTransform(epsg4326Extent, transform); if (intersects(extent, frameState.extent)) { intersecting = true; break; diff --git a/src/ol/source/CartoDB.js b/src/ol/source/CartoDB.js index 46c1b8aa02..a0eb0c1fe0 100644 --- a/src/ol/source/CartoDB.js +++ b/src/ol/source/CartoDB.js @@ -15,7 +15,7 @@ import XYZ from '../source/XYZ.js'; * @param {olx.source.CartoDBOptions} options CartoDB options. * @api */ -var CartoDB = function(options) { +const CartoDB = function(options) { /** * @type {string} @@ -97,18 +97,18 @@ CartoDB.prototype.setConfig = function(config) { * @private */ CartoDB.prototype.initializeMap_ = function() { - var paramHash = JSON.stringify(this.config_); + const paramHash = JSON.stringify(this.config_); if (this.templateCache_[paramHash]) { this.applyTemplate_(this.templateCache_[paramHash]); return; } - var mapUrl = 'https://' + this.account_ + '.carto.com/api/v1/map'; + let mapUrl = 'https://' + this.account_ + '.carto.com/api/v1/map'; if (this.mapId_) { mapUrl += '/named/' + this.mapId_; } - var client = new XMLHttpRequest(); + const client = new XMLHttpRequest(); client.addEventListener('load', this.handleInitResponse_.bind(this, paramHash)); client.addEventListener('error', this.handleInitError_.bind(this)); client.open('POST', mapUrl); @@ -125,10 +125,10 @@ CartoDB.prototype.initializeMap_ = function() { * @private */ CartoDB.prototype.handleInitResponse_ = function(paramHash, event) { - var client = /** @type {XMLHttpRequest} */ (event.target); + const client = /** @type {XMLHttpRequest} */ (event.target); // status will be 0 for file:// urls if (!client.status || client.status >= 200 && client.status < 300) { - var response; + let response; try { response = /** @type {CartoDBLayerInfo} */(JSON.parse(client.responseText)); } catch (err) { @@ -159,7 +159,7 @@ CartoDB.prototype.handleInitError_ = function(event) { * @private */ CartoDB.prototype.applyTemplate_ = function(data) { - var tilesUrl = 'https://' + data.cdn_url.https + '/' + this.account_ + + const tilesUrl = 'https://' + data.cdn_url.https + '/' + this.account_ + '/api/v1/map/' + data.layergroupid + '/{z}/{x}/{y}.png'; this.setUrl(tilesUrl); }; diff --git a/src/ol/source/Cluster.js b/src/ol/source/Cluster.js index 75ce57f452..c28d49ee61 100644 --- a/src/ol/source/Cluster.js +++ b/src/ol/source/Cluster.js @@ -22,7 +22,7 @@ import VectorSource from '../source/Vector.js'; * @extends {ol.source.Vector} * @api */ -var Cluster = function(options) { +const Cluster = function(options) { VectorSource.call(this, { attributions: options.attributions, extent: options.extent, @@ -54,9 +54,9 @@ var Cluster = function(options) { * @protected */ this.geometryFunction = options.geometryFunction || function(feature) { - var geometry = /** @type {ol.geom.Point} */ (feature.getGeometry()); + const geometry = /** @type {ol.geom.Point} */ (feature.getGeometry()); assert(geometry instanceof Point, - 10); // The default `geometryFunction` can only handle `ol.geom.Point` geometries + 10); // The default `geometryFunction` can only handle `ol.geom.Point` geometries return geometry; }; @@ -67,7 +67,7 @@ var Cluster = function(options) { this.source = options.source; this.source.on(EventType.CHANGE, - Cluster.prototype.refresh, this); + Cluster.prototype.refresh, this); }; inherits(Cluster, VectorSource); @@ -97,7 +97,7 @@ Cluster.prototype.getSource = function() { * @inheritDoc */ Cluster.prototype.loadFeatures = function(extent, resolution, - projection) { + projection) { this.source.loadFeatures(extent, resolution, projection); if (resolution !== this.resolution) { this.clear(); @@ -139,27 +139,27 @@ Cluster.prototype.cluster = function() { return; } this.features.length = 0; - var extent = createEmpty(); - var mapDistance = this.distance * this.resolution; - var features = this.source.getFeatures(); + const extent = createEmpty(); + const mapDistance = this.distance * this.resolution; + const features = this.source.getFeatures(); /** * @type {!Object.} */ - var clustered = {}; + const clustered = {}; - for (var i = 0, ii = features.length; i < ii; i++) { - var feature = features[i]; + for (let i = 0, ii = features.length; i < ii; i++) { + const feature = features[i]; if (!(getUid(feature).toString() in clustered)) { - var geometry = this.geometryFunction(feature); + const geometry = this.geometryFunction(feature); if (geometry) { - var coordinates = geometry.getCoordinates(); + const coordinates = geometry.getCoordinates(); createOrUpdateFromCoordinate(coordinates, extent); buffer(extent, mapDistance, extent); - var neighbors = this.source.getFeaturesInExtent(extent); + let neighbors = this.source.getFeaturesInExtent(extent); neighbors = neighbors.filter(function(neighbor) { - var uid = getUid(neighbor).toString(); + const uid = getUid(neighbor).toString(); if (!(uid in clustered)) { clustered[uid] = true; return true; @@ -180,9 +180,9 @@ Cluster.prototype.cluster = function() { * @protected */ Cluster.prototype.createCluster = function(features) { - var centroid = [0, 0]; - for (var i = features.length - 1; i >= 0; --i) { - var geometry = this.geometryFunction(features[i]); + const centroid = [0, 0]; + for (let i = features.length - 1; i >= 0; --i) { + const geometry = this.geometryFunction(features[i]); if (geometry) { _ol_coordinate_.add(centroid, geometry.getCoordinates()); } else { @@ -191,7 +191,7 @@ Cluster.prototype.createCluster = function(features) { } _ol_coordinate_.scale(centroid, 1 / features.length); - var cluster = new Feature(new Point(centroid)); + const cluster = new Feature(new Point(centroid)); cluster.set('features', features); return cluster; }; diff --git a/src/ol/source/Image.js b/src/ol/source/Image.js index c96e424092..7e332ed484 100644 --- a/src/ol/source/Image.js +++ b/src/ol/source/Image.js @@ -23,7 +23,7 @@ import Source from '../source/Source.js'; * @param {ol.SourceImageOptions} options Single image source options. * @api */ -var ImageSource = function(options) { +const ImageSource = function(options) { Source.call(this, { attributions: options.attributions, extent: options.extent, @@ -72,7 +72,7 @@ ImageSource.prototype.getResolutions = function() { */ ImageSource.prototype.findNearestResolution = function(resolution) { if (this.resolutions_) { - var idx = linearFindNearest(this.resolutions_, resolution, 0); + const idx = linearFindNearest(this.resolutions_, resolution, 0); resolution = this.resolutions_[idx]; } return resolution; @@ -87,7 +87,7 @@ ImageSource.prototype.findNearestResolution = function(resolution) { * @return {ol.ImageBase} Single image. */ ImageSource.prototype.getImage = function(extent, resolution, pixelRatio, projection) { - var sourceProjection = this.getProjection(); + const sourceProjection = this.getProjection(); if (!ENABLE_RASTER_REPROJECTION || !sourceProjection || !projection || @@ -100,7 +100,7 @@ ImageSource.prototype.getImage = function(extent, resolution, pixelRatio, projec if (this.reprojectedImage_) { if (this.reprojectedRevision_ == this.getRevision() && equivalent( - this.reprojectedImage_.getProjection(), projection) && + this.reprojectedImage_.getProjection(), projection) && this.reprojectedImage_.getResolution() == resolution && equals(this.reprojectedImage_.getExtent(), extent)) { return this.reprojectedImage_; @@ -110,11 +110,11 @@ ImageSource.prototype.getImage = function(extent, resolution, pixelRatio, projec } this.reprojectedImage_ = new ReprojImage( - sourceProjection, projection, extent, resolution, pixelRatio, - function(extent, resolution, pixelRatio) { - return this.getImageInternal(extent, resolution, - pixelRatio, sourceProjection); - }.bind(this)); + sourceProjection, projection, extent, resolution, pixelRatio, + function(extent, resolution, pixelRatio) { + return this.getImageInternal(extent, resolution, + pixelRatio, sourceProjection); + }.bind(this)); this.reprojectedRevision_ = this.getRevision(); return this.reprojectedImage_; @@ -140,22 +140,22 @@ ImageSource.prototype.getImageInternal = function(extent, resolution, pixelRatio * @protected */ ImageSource.prototype.handleImageChange = function(event) { - var image = /** @type {ol.Image} */ (event.target); + const image = /** @type {ol.Image} */ (event.target); switch (image.getState()) { case ImageState.LOADING: this.dispatchEvent( - new ImageSource.Event(ImageSource.EventType_.IMAGELOADSTART, - image)); + new ImageSource.Event(ImageSource.EventType_.IMAGELOADSTART, + image)); break; case ImageState.LOADED: this.dispatchEvent( - new ImageSource.Event(ImageSource.EventType_.IMAGELOADEND, - image)); + new ImageSource.Event(ImageSource.EventType_.IMAGELOADEND, + image)); break; case ImageState.ERROR: this.dispatchEvent( - new ImageSource.Event(ImageSource.EventType_.IMAGELOADERROR, - image)); + new ImageSource.Event(ImageSource.EventType_.IMAGELOADERROR, + image)); break; default: // pass diff --git a/src/ol/source/ImageArcGISRest.js b/src/ol/source/ImageArcGISRest.js index 8ae61c4790..ea67456744 100644 --- a/src/ol/source/ImageArcGISRest.js +++ b/src/ol/source/ImageArcGISRest.js @@ -26,9 +26,9 @@ import _ol_uri_ from '../uri.js'; * @param {olx.source.ImageArcGISRestOptions=} opt_options Image ArcGIS Rest Options. * @api */ -var ImageArcGISRest = function(opt_options) { +const ImageArcGISRest = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; ImageSource.call(this, { attributions: options.attributions, @@ -122,7 +122,7 @@ ImageArcGISRest.prototype.getImageInternal = function(extent, resolution, pixelR resolution = this.findNearestResolution(resolution); pixelRatio = this.hidpi_ ? pixelRatio : 1; - var image = this.image_; + const image = this.image_; if (image && this.renderedRevision_ == this.getRevision() && image.getResolution() == resolution && @@ -131,7 +131,7 @@ ImageArcGISRest.prototype.getImageInternal = function(extent, resolution, pixelR return image; } - var params = { + const params = { 'F': 'image', 'FORMAT': 'PNG32', 'TRANSPARENT': true @@ -139,22 +139,22 @@ ImageArcGISRest.prototype.getImageInternal = function(extent, resolution, pixelR _ol_obj_.assign(params, this.params_); extent = extent.slice(); - var centerX = (extent[0] + extent[2]) / 2; - var centerY = (extent[1] + extent[3]) / 2; + const centerX = (extent[0] + extent[2]) / 2; + const centerY = (extent[1] + extent[3]) / 2; if (this.ratio_ != 1) { - var halfWidth = this.ratio_ * getWidth(extent) / 2; - var halfHeight = this.ratio_ * getHeight(extent) / 2; + const halfWidth = this.ratio_ * getWidth(extent) / 2; + const halfHeight = this.ratio_ * getHeight(extent) / 2; extent[0] = centerX - halfWidth; extent[1] = centerY - halfHeight; extent[2] = centerX + halfWidth; extent[3] = centerY + halfHeight; } - var imageResolution = resolution / pixelRatio; + const imageResolution = resolution / pixelRatio; // Compute an integer width and height. - var width = Math.ceil(getWidth(extent) / imageResolution); - var height = Math.ceil(getHeight(extent) / imageResolution); + const width = Math.ceil(getWidth(extent) / imageResolution); + const height = Math.ceil(getHeight(extent) / imageResolution); // Modify the extent to match the integer width and height. extent[0] = centerX - imageResolution * width / 2; @@ -165,16 +165,16 @@ ImageArcGISRest.prototype.getImageInternal = function(extent, resolution, pixelR this.imageSize_[0] = width; this.imageSize_[1] = height; - var url = this.getRequestUrl_(extent, this.imageSize_, pixelRatio, - projection, params); + const url = this.getRequestUrl_(extent, this.imageSize_, pixelRatio, + projection, params); this.image_ = new _ol_Image_(extent, resolution, pixelRatio, - url, this.crossOrigin_, this.imageLoadFunction_); + url, this.crossOrigin_, this.imageLoadFunction_); this.renderedRevision_ = this.getRevision(); _ol_events_.listen(this.image_, EventType.CHANGE, - this.handleImageChange, this); + this.handleImageChange, this); return this.image_; @@ -202,7 +202,7 @@ ImageArcGISRest.prototype.getImageLoadFunction = function() { */ ImageArcGISRest.prototype.getRequestUrl_ = function(extent, size, pixelRatio, projection, params) { // ArcGIS Server only wants the numeric portion of the projection ID. - var srid = projection.getCode().split(':').pop(); + const srid = projection.getCode().split(':').pop(); params['SIZE'] = size[0] + ',' + size[1]; params['BBOX'] = extent.join(','); @@ -210,11 +210,11 @@ ImageArcGISRest.prototype.getRequestUrl_ = function(extent, size, pixelRatio, pr params['IMAGESR'] = srid; params['DPI'] = Math.round(90 * pixelRatio); - var url = this.url_; + const url = this.url_; - var modifiedUrl = url - .replace(/MapServer\/?$/, 'MapServer/export') - .replace(/ImageServer\/?$/, 'ImageServer/exportImage'); + const modifiedUrl = url + .replace(/MapServer\/?$/, 'MapServer/export') + .replace(/ImageServer\/?$/, 'ImageServer/exportImage'); if (modifiedUrl == url) { assert(false, 50); // `options.featureTypes` should be an Array } diff --git a/src/ol/source/ImageCanvas.js b/src/ol/source/ImageCanvas.js index 249ff6d687..95a9a694bd 100644 --- a/src/ol/source/ImageCanvas.js +++ b/src/ol/source/ImageCanvas.js @@ -15,7 +15,7 @@ import ImageSource from '../source/Image.js'; * @param {olx.source.ImageCanvasOptions} options Constructor options. * @api */ -var ImageCanvasSource = function(options) { +const ImageCanvasSource = function(options) { ImageSource.call(this, { attributions: options.attributions, @@ -60,7 +60,7 @@ inherits(ImageCanvasSource, ImageSource); ImageCanvasSource.prototype.getImageInternal = function(extent, resolution, pixelRatio, projection) { resolution = this.findNearestResolution(resolution); - var canvas = this.canvas_; + let canvas = this.canvas_; if (canvas && this.renderedRevision_ == this.getRevision() && canvas.getResolution() == resolution && @@ -71,12 +71,12 @@ ImageCanvasSource.prototype.getImageInternal = function(extent, resolution, pixe extent = extent.slice(); scaleFromCenter(extent, this.ratio_); - var width = getWidth(extent) / resolution; - var height = getHeight(extent) / resolution; - var size = [width * pixelRatio, height * pixelRatio]; + const width = getWidth(extent) / resolution; + const height = getHeight(extent) / resolution; + const size = [width * pixelRatio, height * pixelRatio]; - var canvasElement = this.canvasFunction_( - extent, resolution, pixelRatio, size, projection); + const canvasElement = this.canvasFunction_( + extent, resolution, pixelRatio, size, projection); if (canvasElement) { canvas = new ImageCanvas(extent, resolution, pixelRatio, canvasElement); } diff --git a/src/ol/source/ImageMapGuide.js b/src/ol/source/ImageMapGuide.js index 540e00e82c..a16a16478a 100644 --- a/src/ol/source/ImageMapGuide.js +++ b/src/ol/source/ImageMapGuide.js @@ -20,7 +20,7 @@ import _ol_uri_ from '../uri.js'; * @param {olx.source.ImageMapGuideOptions} options Options. * @api */ -var ImageMapGuide = function(options) { +const ImageMapGuide = function(options) { ImageSource.call(this, { projection: options.projection, @@ -121,7 +121,7 @@ ImageMapGuide.prototype.getImageInternal = function(extent, resolution, pixelRat resolution = this.findNearestResolution(resolution); pixelRatio = this.hidpi_ ? pixelRatio : 1; - var image = this.image_; + let image = this.image_; if (image && this.renderedRevision_ == this.getRevision() && image.getResolution() == resolution && @@ -134,18 +134,18 @@ ImageMapGuide.prototype.getImageInternal = function(extent, resolution, pixelRat extent = extent.slice(); scaleFromCenter(extent, this.ratio_); } - var width = getWidth(extent) / resolution; - var height = getHeight(extent) / resolution; - var size = [width * pixelRatio, height * pixelRatio]; + const width = getWidth(extent) / resolution; + const height = getHeight(extent) / resolution; + const size = [width * pixelRatio, height * pixelRatio]; if (this.url_ !== undefined) { - var imageUrl = this.getUrl(this.url_, this.params_, extent, size, - projection); + const imageUrl = this.getUrl(this.url_, this.params_, extent, size, + projection); image = new _ol_Image_(extent, resolution, pixelRatio, - imageUrl, this.crossOrigin_, - this.imageLoadFunction_); + imageUrl, this.crossOrigin_, + this.imageLoadFunction_); _ol_events_.listen(image, EventType.CHANGE, - this.handleImageChange, this); + this.handleImageChange, this); } else { image = null; } @@ -174,11 +174,11 @@ ImageMapGuide.prototype.getImageLoadFunction = function() { * @return {number} The computed map scale. */ ImageMapGuide.getScale = function(extent, size, metersPerUnit, dpi) { - var mcsW = getWidth(extent); - var mcsH = getHeight(extent); - var devW = size[0]; - var devH = size[1]; - var mpp = 0.0254 / dpi; + const mcsW = getWidth(extent); + const mcsH = getHeight(extent); + const devW = size[0]; + const devH = size[1]; + const mpp = 0.0254 / dpi; if (devH * mcsW > devW * mcsH) { return mcsW * metersPerUnit / (devW * mpp); // width limited } else { @@ -207,10 +207,10 @@ ImageMapGuide.prototype.updateParams = function(params) { * @return {string} The mapagent map image request URL. */ ImageMapGuide.prototype.getUrl = function(baseUrl, params, extent, size, projection) { - var scale = ImageMapGuide.getScale(extent, size, - this.metersPerUnit_, this.displayDpi_); - var center = getCenter(extent); - var baseParams = { + const scale = ImageMapGuide.getScale(extent, size, + this.metersPerUnit_, this.displayDpi_); + const center = getCenter(extent); + const baseParams = { 'OPERATION': this.useOverlay_ ? 'GETDYNAMICMAPOVERLAYIMAGE' : 'GETMAPIMAGE', 'VERSION': '2.0.0', 'LOCALE': 'en', @@ -234,7 +234,7 @@ ImageMapGuide.prototype.getUrl = function(baseUrl, params, extent, size, project * @api */ ImageMapGuide.prototype.setImageLoadFunction = function( - imageLoadFunction) { + imageLoadFunction) { this.image_ = null; this.imageLoadFunction_ = imageLoadFunction; this.changed(); diff --git a/src/ol/source/ImageStatic.js b/src/ol/source/ImageStatic.js index 099e88e9e5..32775b5f9b 100644 --- a/src/ol/source/ImageStatic.js +++ b/src/ol/source/ImageStatic.js @@ -20,13 +20,13 @@ import ImageSource from '../source/Image.js'; * @param {olx.source.ImageStaticOptions} options Options. * @api */ -var Static = function(options) { - var imageExtent = options.imageExtent; +const Static = function(options) { + const imageExtent = options.imageExtent; - var crossOrigin = options.crossOrigin !== undefined ? + const crossOrigin = options.crossOrigin !== undefined ? options.crossOrigin : null; - var /** @type {ol.ImageLoadFunctionType} */ imageLoadFunction = + const /** @type {ol.ImageLoadFunctionType} */ imageLoadFunction = options.imageLoadFunction !== undefined ? options.imageLoadFunction : ImageSource.defaultImageLoadFunction; @@ -48,7 +48,7 @@ var Static = function(options) { this.imageSize_ = options.imageSize ? options.imageSize : null; _ol_events_.listen(this.image_, EventType.CHANGE, - this.handleImageChange, this); + this.handleImageChange, this); }; @@ -71,9 +71,9 @@ Static.prototype.getImageInternal = function(extent, resolution, pixelRatio, pro */ Static.prototype.handleImageChange = function(evt) { if (this.image_.getState() == ImageState.LOADED) { - var imageExtent = this.image_.getExtent(); - var image = this.image_.getImage(); - var imageWidth, imageHeight; + const imageExtent = this.image_.getExtent(); + const image = this.image_.getImage(); + let imageWidth, imageHeight; if (this.imageSize_) { imageWidth = this.imageSize_[0]; imageHeight = this.imageSize_[1]; @@ -81,13 +81,13 @@ Static.prototype.handleImageChange = function(evt) { imageWidth = image.width; imageHeight = image.height; } - var resolution = getHeight(imageExtent) / imageHeight; - var targetWidth = Math.ceil(getWidth(imageExtent) / resolution); + const resolution = getHeight(imageExtent) / imageHeight; + const targetWidth = Math.ceil(getWidth(imageExtent) / resolution); if (targetWidth != imageWidth) { - var context = createCanvasContext2D(targetWidth, imageHeight); - var canvas = context.canvas; + const context = createCanvasContext2D(targetWidth, imageHeight); + const canvas = context.canvas; context.drawImage(image, 0, 0, imageWidth, imageHeight, - 0, 0, canvas.width, canvas.height); + 0, 0, canvas.width, canvas.height); this.image_.setImage(canvas); } } diff --git a/src/ol/source/ImageWMS.js b/src/ol/source/ImageWMS.js index b6eb1749ed..8d240cbe26 100644 --- a/src/ol/source/ImageWMS.js +++ b/src/ol/source/ImageWMS.js @@ -27,9 +27,9 @@ import _ol_uri_ from '../uri.js'; * @param {olx.source.ImageWMSOptions=} opt_options Options. * @api */ -var ImageWMS = function(opt_options) { +const ImageWMS = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; ImageSource.call(this, { attributions: options.attributions, @@ -137,18 +137,18 @@ ImageWMS.prototype.getGetFeatureInfoUrl = function(coordinate, resolution, proje if (this.url_ === undefined) { return undefined; } - var projectionObj = getProjection(projection); - var sourceProjectionObj = this.getProjection(); + const projectionObj = getProjection(projection); + const sourceProjectionObj = this.getProjection(); if (sourceProjectionObj && sourceProjectionObj !== projectionObj) { resolution = _ol_reproj_.calculateSourceResolution(sourceProjectionObj, projectionObj, coordinate, resolution); coordinate = transform(coordinate, projectionObj, sourceProjectionObj); } - var extent = getForViewAndSize(coordinate, resolution, 0, - ImageWMS.GETFEATUREINFO_IMAGE_SIZE_); + const extent = getForViewAndSize(coordinate, resolution, 0, + ImageWMS.GETFEATUREINFO_IMAGE_SIZE_); - var baseParams = { + const baseParams = { 'SERVICE': 'WMS', 'VERSION': DEFAULT_WMS_VERSION, 'REQUEST': 'GetFeatureInfo', @@ -158,14 +158,14 @@ ImageWMS.prototype.getGetFeatureInfoUrl = function(coordinate, resolution, proje }; _ol_obj_.assign(baseParams, this.params_, params); - var x = Math.floor((coordinate[0] - extent[0]) / resolution); - var y = Math.floor((extent[3] - coordinate[1]) / resolution); + const x = Math.floor((coordinate[0] - extent[0]) / resolution); + const y = Math.floor((extent[3] - coordinate[1]) / resolution); baseParams[this.v13_ ? 'I' : 'X'] = x; baseParams[this.v13_ ? 'J' : 'Y'] = y; return this.getRequestUrl_( - extent, ImageWMS.GETFEATUREINFO_IMAGE_SIZE_, - 1, sourceProjectionObj || projectionObj, baseParams); + extent, ImageWMS.GETFEATUREINFO_IMAGE_SIZE_, + 1, sourceProjectionObj || projectionObj, baseParams); }; @@ -195,19 +195,19 @@ ImageWMS.prototype.getImageInternal = function(extent, resolution, pixelRatio, p pixelRatio = 1; } - var imageResolution = resolution / pixelRatio; + const imageResolution = resolution / pixelRatio; - var center = getCenter(extent); - var viewWidth = Math.ceil(getWidth(extent) / imageResolution); - var viewHeight = Math.ceil(getHeight(extent) / imageResolution); - var viewExtent = getForViewAndSize(center, imageResolution, 0, - [viewWidth, viewHeight]); - var requestWidth = Math.ceil(this.ratio_ * getWidth(extent) / imageResolution); - var requestHeight = Math.ceil(this.ratio_ * getHeight(extent) / imageResolution); - var requestExtent = getForViewAndSize(center, imageResolution, 0, - [requestWidth, requestHeight]); + const center = getCenter(extent); + const viewWidth = Math.ceil(getWidth(extent) / imageResolution); + const viewHeight = Math.ceil(getHeight(extent) / imageResolution); + const viewExtent = getForViewAndSize(center, imageResolution, 0, + [viewWidth, viewHeight]); + const requestWidth = Math.ceil(this.ratio_ * getWidth(extent) / imageResolution); + const requestHeight = Math.ceil(this.ratio_ * getHeight(extent) / imageResolution); + const requestExtent = getForViewAndSize(center, imageResolution, 0, + [requestWidth, requestHeight]); - var image = this.image_; + const image = this.image_; if (image && this.renderedRevision_ == this.getRevision() && image.getResolution() == resolution && @@ -216,7 +216,7 @@ ImageWMS.prototype.getImageInternal = function(extent, resolution, pixelRatio, p return image; } - var params = { + const params = { 'SERVICE': 'WMS', 'VERSION': DEFAULT_WMS_VERSION, 'REQUEST': 'GetMap', @@ -228,16 +228,16 @@ ImageWMS.prototype.getImageInternal = function(extent, resolution, pixelRatio, p this.imageSize_[0] = Math.round(getWidth(requestExtent) / imageResolution); this.imageSize_[1] = Math.round(getHeight(requestExtent) / imageResolution); - var url = this.getRequestUrl_(requestExtent, this.imageSize_, pixelRatio, - projection, params); + const url = this.getRequestUrl_(requestExtent, this.imageSize_, pixelRatio, + projection, params); this.image_ = new _ol_Image_(requestExtent, resolution, pixelRatio, - url, this.crossOrigin_, this.imageLoadFunction_); + url, this.crossOrigin_, this.imageLoadFunction_); this.renderedRevision_ = this.getRevision(); _ol_events_.listen(this.image_, EventType.CHANGE, - this.handleImageChange, this); + this.handleImageChange, this); return this.image_; @@ -276,7 +276,7 @@ ImageWMS.prototype.getRequestUrl_ = function(extent, size, pixelRatio, projectio if (pixelRatio != 1) { switch (this.serverType_) { case WMSServerType.GEOSERVER: - var dpi = (90 * pixelRatio + 0.5) | 0; + const dpi = (90 * pixelRatio + 0.5) | 0; if ('FORMAT_OPTIONS' in params) { params['FORMAT_OPTIONS'] += ';dpi:' + dpi; } else { @@ -299,8 +299,8 @@ ImageWMS.prototype.getRequestUrl_ = function(extent, size, pixelRatio, projectio params['WIDTH'] = size[0]; params['HEIGHT'] = size[1]; - var axisOrientation = projection.getAxisOrientation(); - var bbox; + const axisOrientation = projection.getAxisOrientation(); + let bbox; if (this.v13_ && axisOrientation.substr(0, 2) == 'ne') { bbox = [extent[1], extent[0], extent[3], extent[2]]; } else { @@ -328,7 +328,7 @@ ImageWMS.prototype.getUrl = function() { * @api */ ImageWMS.prototype.setImageLoadFunction = function( - imageLoadFunction) { + imageLoadFunction) { this.image_ = null; this.imageLoadFunction_ = imageLoadFunction; this.changed(); @@ -366,7 +366,7 @@ ImageWMS.prototype.updateParams = function(params) { * @private */ ImageWMS.prototype.updateV13_ = function() { - var version = this.params_['VERSION'] || DEFAULT_WMS_VERSION; + const version = this.params_['VERSION'] || DEFAULT_WMS_VERSION; this.v13_ = _ol_string_.compareVersions(version, '1.3') >= 0; }; export default ImageWMS; diff --git a/src/ol/source/OSM.js b/src/ol/source/OSM.js index 2e3bf63428..f934d0762f 100644 --- a/src/ol/source/OSM.js +++ b/src/ol/source/OSM.js @@ -13,21 +13,21 @@ import XYZ from '../source/XYZ.js'; * @param {olx.source.OSMOptions=} opt_options Open Street Map options. * @api */ -var OSM = function(opt_options) { +const OSM = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; - var attributions; + let attributions; if (options.attributions !== undefined) { attributions = options.attributions; } else { attributions = [OSM.ATTRIBUTION]; } - var crossOrigin = options.crossOrigin !== undefined ? + const crossOrigin = options.crossOrigin !== undefined ? options.crossOrigin : 'anonymous'; - var url = options.url !== undefined ? + const url = options.url !== undefined ? options.url : 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'; XYZ.call(this, { diff --git a/src/ol/source/Raster.js b/src/ol/source/Raster.js index b8086d7872..79dc011807 100644 --- a/src/ol/source/Raster.js +++ b/src/ol/source/Raster.js @@ -25,7 +25,7 @@ import _ol_transform_ from '../transform.js'; /** * @enum {string} */ -var RasterEventType = { +const RasterEventType = { /** * Triggered before operations are run. * @event ol.source.Raster.Event#beforeoperations @@ -54,7 +54,7 @@ var RasterEventType = { * @param {olx.source.RasterOptions} options Options. * @api */ -var RasterSource = function(options) { +const RasterSource = function(options) { /** * @private @@ -81,9 +81,9 @@ var RasterSource = function(options) { */ this.renderers_ = createRenderers(options.sources); - for (var r = 0, rr = this.renderers_.length; r < rr; ++r) { + for (let r = 0, rr = this.renderers_.length; r < rr; ++r) { _ol_events_.listen(this.renderers_[r], EventType.CHANGE, - this.changed, this); + this.changed, this); } /** @@ -91,14 +91,14 @@ var RasterSource = function(options) { * @type {ol.TileQueue} */ this.tileQueue_ = new TileQueue( - function() { - return 1; - }, - this.changed.bind(this)); + function() { + return 1; + }, + this.changed.bind(this)); - var layerStatesArray = getLayerStatesArray(this.renderers_); - var layerStates = {}; - for (var i = 0, ii = layerStatesArray.length; i < ii; ++i) { + const layerStatesArray = getLayerStatesArray(this.renderers_); + const layerStates = {}; + for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) { layerStates[getUid(layerStatesArray[i].layer)] = layerStatesArray[i]; } @@ -189,13 +189,13 @@ RasterSource.prototype.setOperation = function(operation, opt_lib) { */ RasterSource.prototype.updateFrameState_ = function(extent, resolution, projection) { - var frameState = /** @type {olx.FrameState} */ ( + const frameState = /** @type {olx.FrameState} */ ( _ol_obj_.assign({}, this.frameState_)); frameState.viewState = /** @type {olx.ViewState} */ ( _ol_obj_.assign({}, frameState.viewState)); - var center = getCenter(extent); + const center = getCenter(extent); frameState.extent = extent.slice(); frameState.focus = center; @@ -204,7 +204,7 @@ RasterSource.prototype.updateFrameState_ = function(extent, resolution, projecti frameState.time = Date.now(); frameState.animate = false; - var viewState = frameState.viewState; + const viewState = frameState.viewState; viewState.center = center; viewState.projection = projection; viewState.resolution = resolution; @@ -218,9 +218,9 @@ RasterSource.prototype.updateFrameState_ = function(extent, resolution, projecti * @private */ RasterSource.prototype.allSourcesReady_ = function() { - var ready = true; - var source; - for (var i = 0, ii = this.renderers_.length; i < ii; ++i) { + let ready = true; + let source; + for (let i = 0, ii = this.renderers_.length; i < ii; ++i) { source = this.renderers_[i].getLayer().getSource(); if (source.getState() !== SourceState.READY) { ready = false; @@ -239,13 +239,13 @@ RasterSource.prototype.getImage = function(extent, resolution, pixelRatio, proje return null; } - var frameState = this.updateFrameState_(extent, resolution, projection); + const frameState = this.updateFrameState_(extent, resolution, projection); this.requestedFrameState_ = frameState; // check if we can't reuse the existing ol.ImageCanvas if (this.renderedImageCanvas_) { - var renderedResolution = this.renderedImageCanvas_.getResolution(); - var renderedExtent = this.renderedImageCanvas_.getExtent(); + const renderedResolution = this.renderedImageCanvas_.getResolution(); + const renderedExtent = this.renderedImageCanvas_.getExtent(); if (resolution !== renderedResolution || !equals(extent, renderedExtent)) { this.renderedImageCanvas_ = null; } @@ -270,12 +270,12 @@ RasterSource.prototype.getImage = function(extent, resolution, pixelRatio, proje * @private */ RasterSource.prototype.processSources_ = function() { - var frameState = this.requestedFrameState_; - var len = this.renderers_.length; - var imageDatas = new Array(len); - for (var i = 0; i < len; ++i) { - var imageData = getImageData( - this.renderers_[i], frameState, frameState.layerStatesArray[i]); + const frameState = this.requestedFrameState_; + const len = this.renderers_.length; + const imageDatas = new Array(len); + for (let i = 0; i < len; ++i) { + const imageData = getImageData( + this.renderers_[i], frameState, frameState.layerStatesArray[i]); if (imageData) { imageDatas[i] = imageData; } else { @@ -283,7 +283,7 @@ RasterSource.prototype.processSources_ = function() { } } - var data = {}; + const data = {}; this.dispatchEvent(new RasterSource.Event(RasterEventType.BEFOREOPERATIONS, frameState, data)); this.worker_.process(imageDatas, data, this.onWorkerComplete_.bind(this, frameState)); }; @@ -303,19 +303,19 @@ RasterSource.prototype.onWorkerComplete_ = function(frameState, err, output, dat } // do nothing if extent or resolution changed - var extent = frameState.extent; - var resolution = frameState.viewState.resolution; + const extent = frameState.extent; + const resolution = frameState.viewState.resolution; if (resolution !== this.requestedFrameState_.viewState.resolution || !equals(extent, this.requestedFrameState_.extent)) { return; } - var context; + let context; if (this.renderedImageCanvas_) { context = this.renderedImageCanvas_.getImage().getContext('2d'); } else { - var width = Math.round(getWidth(extent) / resolution); - var height = Math.round(getHeight(extent) / resolution); + const width = Math.round(getWidth(extent) / resolution); + const height = Math.round(getHeight(extent) / resolution); context = createCanvasContext2D(width, height); this.renderedImageCanvas_ = new ImageCanvas(extent, resolution, 1, context.canvas); } @@ -339,12 +339,12 @@ function getImageData(renderer, frameState, layerState) { if (!renderer.prepareFrame(frameState, layerState)) { return null; } - var width = frameState.size[0]; - var height = frameState.size[1]; + const width = frameState.size[0]; + const height = frameState.size[1]; if (!RasterSource.context_) { RasterSource.context_ = createCanvasContext2D(width, height); } else { - var canvas = RasterSource.context_.canvas; + const canvas = RasterSource.context_.canvas; if (canvas.width !== width || canvas.height !== height) { RasterSource.context_ = createCanvasContext2D(width, height); } else { @@ -382,9 +382,9 @@ function getLayerStatesArray(renderers) { * @return {Array.} Array of layer renderers. */ function createRenderers(sources) { - var len = sources.length; - var renderers = new Array(len); - for (var i = 0; i < len; ++i) { + const len = sources.length; + const renderers = new Array(len); + for (let i = 0; i < len; ++i) { renderers[i] = createRenderer(sources[i]); } return renderers; @@ -397,7 +397,7 @@ function createRenderers(sources) { * @return {ol.renderer.canvas.Layer} The renderer. */ function createRenderer(source) { - var renderer = null; + let renderer = null; if (source instanceof TileSource) { renderer = createTileRenderer(source); } else if (source instanceof ImageSource) { @@ -413,7 +413,7 @@ function createRenderer(source) { * @return {ol.renderer.canvas.Layer} The renderer. */ function createImageRenderer(source) { - var layer = new ImageLayer({source: source}); + const layer = new ImageLayer({source: source}); return new CanvasImageLayerRenderer(layer); } @@ -424,7 +424,7 @@ function createImageRenderer(source) { * @return {ol.renderer.canvas.Layer} The renderer. */ function createTileRenderer(source) { - var layer = new TileLayer({source: source}); + const layer = new TileLayer({source: source}); return new CanvasTileLayerRenderer(layer); } diff --git a/src/ol/source/Source.js b/src/ol/source/Source.js index 379ac6e1fb..b466290e0f 100644 --- a/src/ol/source/Source.js +++ b/src/ol/source/Source.js @@ -21,7 +21,7 @@ import SourceState from '../source/State.js'; * @param {ol.SourceSourceOptions} options Source options. * @api */ -var Source = function(options) { +const Source = function(options) { BaseObject.call(this); diff --git a/src/ol/source/Stamen.js b/src/ol/source/Stamen.js index c1c249bfa8..7434c70b47 100644 --- a/src/ol/source/Stamen.js +++ b/src/ol/source/Stamen.js @@ -14,14 +14,14 @@ import XYZ from '../source/XYZ.js'; * @param {olx.source.StamenOptions} options Stamen options. * @api */ -var Stamen = function(options) { - var i = options.layer.indexOf('-'); - var provider = i == -1 ? options.layer : options.layer.slice(0, i); - var providerConfig = Stamen.ProviderConfig[provider]; +const Stamen = function(options) { + const i = options.layer.indexOf('-'); + const provider = i == -1 ? options.layer : options.layer.slice(0, i); + const providerConfig = Stamen.ProviderConfig[provider]; - var layerConfig = Stamen.LayerConfig[options.layer]; + const layerConfig = Stamen.LayerConfig[options.layer]; - var url = options.url !== undefined ? options.url : + const url = options.url !== undefined ? options.url : 'https://stamen-tiles-{a-d}.a.ssl.fastly.net/' + options.layer + '/{z}/{x}/{y}.' + layerConfig.extension; diff --git a/src/ol/source/Tile.js b/src/ol/source/Tile.js index 0f55f7dc55..ebef0fb906 100644 --- a/src/ol/source/Tile.js +++ b/src/ol/source/Tile.js @@ -23,7 +23,7 @@ import _ol_tilegrid_ from '../tilegrid.js'; * @param {ol.SourceTileOptions} options Tile source options. * @api */ -var TileSource = function(options) { +const TileSource = function(options) { Source.call(this, { attributions: options.attributions, @@ -94,7 +94,7 @@ TileSource.prototype.canExpireCache = function() { * @param {Object.} usedTiles Used tiles. */ TileSource.prototype.expireCache = function(projection, usedTiles) { - var tileCache = this.getTileCacheForProjection(projection); + const tileCache = this.getTileCacheForProjection(projection); if (tileCache) { tileCache.expireCache(usedTiles); } @@ -111,15 +111,15 @@ TileSource.prototype.expireCache = function(projection, usedTiles) { * @return {boolean} The tile range is fully covered with loaded tiles. */ TileSource.prototype.forEachLoadedTile = function(projection, z, tileRange, callback) { - var tileCache = this.getTileCacheForProjection(projection); + const tileCache = this.getTileCacheForProjection(projection); if (!tileCache) { return false; } - var covered = true; - var tile, tileCoordKey, loaded; - for (var x = tileRange.minX; x <= tileRange.maxX; ++x) { - for (var y = tileRange.minY; y <= tileRange.maxY; ++y) { + let covered = true; + let tile, tileCoordKey, loaded; + for (let x = tileRange.minX; x <= tileRange.maxX; ++x) { + for (let y = tileRange.minY; y <= tileRange.maxY; ++y) { tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); loaded = false; if (tileCache.containsKey(tileCoordKey)) { @@ -228,7 +228,7 @@ TileSource.prototype.getTileGridForProjection = function(projection) { * @protected */ TileSource.prototype.getTileCacheForProjection = function(projection) { - var thisProj = this.getProjection(); + const thisProj = this.getProjection(); if (thisProj && !equivalent(thisProj, projection)) { return null; } else { @@ -256,9 +256,9 @@ TileSource.prototype.getTilePixelRatio = function(pixelRatio) { * @return {ol.Size} Tile size. */ TileSource.prototype.getTilePixelSize = function(z, pixelRatio, projection) { - var tileGrid = this.getTileGridForProjection(projection); - var tilePixelRatio = this.getTilePixelRatio(pixelRatio); - var tileSize = _ol_size_.toSize(tileGrid.getTileSize(z), this.tmpSize); + const tileGrid = this.getTileGridForProjection(projection); + const tilePixelRatio = this.getTilePixelRatio(pixelRatio); + const tileSize = _ol_size_.toSize(tileGrid.getTileSize(z), this.tmpSize); if (tilePixelRatio == 1) { return tileSize; } else { @@ -277,9 +277,9 @@ TileSource.prototype.getTilePixelSize = function(z, pixelRatio, projection) { * null if no tile URL should be created for the passed `tileCoord`. */ TileSource.prototype.getTileCoordForTileUrlFunction = function(tileCoord, opt_projection) { - var projection = opt_projection !== undefined ? + const projection = opt_projection !== undefined ? opt_projection : this.getProjection(); - var tileGrid = this.getTileGridForProjection(projection); + const tileGrid = this.getTileGridForProjection(projection); if (this.getWrapX() && projection.isGlobal()) { tileCoord = _ol_tilegrid_.wrapX(tileGrid, tileCoord, projection); } diff --git a/src/ol/source/TileArcGISRest.js b/src/ol/source/TileArcGISRest.js index 5a3f9a486f..af0da1b4ed 100644 --- a/src/ol/source/TileArcGISRest.js +++ b/src/ol/source/TileArcGISRest.js @@ -24,9 +24,9 @@ import _ol_uri_ from '../uri.js'; * options. * @api */ -var TileArcGISRest = function(opt_options) { +const TileArcGISRest = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; TileImage.call(this, { attributions: options.attributions, @@ -65,9 +65,9 @@ inherits(TileArcGISRest, TileImage); * @return {string} The key for the current params. */ TileArcGISRest.prototype.getKeyForParams_ = function() { - var i = 0; - var res = []; - for (var key in this.params_) { + let i = 0; + const res = []; + for (const key in this.params_) { res[i++] = key + '-' + this.params_[key]; } return res.join('/'); @@ -96,35 +96,35 @@ TileArcGISRest.prototype.getParams = function() { * @private */ TileArcGISRest.prototype.getRequestUrl_ = function(tileCoord, tileSize, tileExtent, - pixelRatio, projection, params) { + pixelRatio, projection, params) { - var urls = this.urls; + const urls = this.urls; if (!urls) { return undefined; } // ArcGIS Server only wants the numeric portion of the projection ID. - var srid = projection.getCode().split(':').pop(); + const srid = projection.getCode().split(':').pop(); params['SIZE'] = tileSize[0] + ',' + tileSize[1]; params['BBOX'] = tileExtent.join(','); params['BBOXSR'] = srid; params['IMAGESR'] = srid; params['DPI'] = Math.round( - params['DPI'] ? params['DPI'] * pixelRatio : 90 * pixelRatio + params['DPI'] ? params['DPI'] * pixelRatio : 90 * pixelRatio ); - var url; + let url; if (urls.length == 1) { url = urls[0]; } else { - var index = modulo(_ol_tilecoord_.hash(tileCoord), urls.length); + const index = modulo(_ol_tilecoord_.hash(tileCoord), urls.length); url = urls[index]; } - var modifiedUrl = url - .replace(/MapServer\/?$/, 'MapServer/export') - .replace(/ImageServer\/?$/, 'ImageServer/exportImage'); + const modifiedUrl = url + .replace(/MapServer\/?$/, 'MapServer/export') + .replace(/ImageServer\/?$/, 'ImageServer/exportImage'); return _ol_uri_.appendParams(modifiedUrl, params); }; @@ -142,7 +142,7 @@ TileArcGISRest.prototype.getTilePixelRatio = function(pixelRatio) { */ TileArcGISRest.prototype.fixedTileUrlFunction = function(tileCoord, pixelRatio, projection) { - var tileGrid = this.getTileGrid(); + let tileGrid = this.getTileGrid(); if (!tileGrid) { tileGrid = this.getTileGridForProjection(projection); } @@ -151,17 +151,17 @@ TileArcGISRest.prototype.fixedTileUrlFunction = function(tileCoord, pixelRatio, return undefined; } - var tileExtent = tileGrid.getTileCoordExtent( - tileCoord, this.tmpExtent_); - var tileSize = _ol_size_.toSize( - tileGrid.getTileSize(tileCoord[0]), this.tmpSize); + const tileExtent = tileGrid.getTileCoordExtent( + tileCoord, this.tmpExtent_); + let tileSize = _ol_size_.toSize( + tileGrid.getTileSize(tileCoord[0]), this.tmpSize); if (pixelRatio != 1) { tileSize = _ol_size_.scale(tileSize, pixelRatio, this.tmpSize); } // Apply default params and override with user specified values. - var baseParams = { + const baseParams = { 'F': 'image', 'FORMAT': 'PNG32', 'TRANSPARENT': true @@ -169,7 +169,7 @@ TileArcGISRest.prototype.fixedTileUrlFunction = function(tileCoord, pixelRatio, _ol_obj_.assign(baseParams, this.params_); return this.getRequestUrl_(tileCoord, tileSize, tileExtent, - pixelRatio, projection, baseParams); + pixelRatio, projection, baseParams); }; diff --git a/src/ol/source/TileDebug.js b/src/ol/source/TileDebug.js index 4bbc08aff4..f13d23db26 100644 --- a/src/ol/source/TileDebug.js +++ b/src/ol/source/TileDebug.js @@ -22,7 +22,7 @@ import _ol_tilecoord_ from '../tilecoord.js'; * @param {olx.source.TileDebugOptions} options Debug tile options. * @api */ -var TileDebug = function(options) { +const TileDebug = function(options) { TileSource.call(this, { opaque: false, @@ -40,16 +40,16 @@ inherits(TileDebug, TileSource); * @inheritDoc */ TileDebug.prototype.getTile = function(z, x, y) { - var tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); + const tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); if (this.tileCache.containsKey(tileCoordKey)) { return /** @type {!ol.source.TileDebug.Tile_} */ (this.tileCache.get(tileCoordKey)); } else { - var tileSize = _ol_size_.toSize(this.tileGrid.getTileSize(z)); - var tileCoord = [z, x, y]; - var textTileCoord = this.getTileCoordForTileUrlFunction(tileCoord); - var text = !textTileCoord ? '' : + const tileSize = _ol_size_.toSize(this.tileGrid.getTileSize(z)); + const tileCoord = [z, x, y]; + const textTileCoord = this.getTileCoordForTileUrlFunction(tileCoord); + const text = !textTileCoord ? '' : this.getTileCoordForTileUrlFunction(textTileCoord).toString(); - var tile = new TileDebug.Tile_(tileCoord, tileSize, text); + const tile = new TileDebug.Tile_(tileCoord, tileSize, text); this.tileCache.set(tileCoordKey, tile); return tile; } @@ -98,8 +98,8 @@ TileDebug.Tile_.prototype.getImage = function() { if (this.canvas_) { return this.canvas_; } else { - var tileSize = this.tileSize_; - var context = createCanvasContext2D(tileSize[0], tileSize[1]); + const tileSize = this.tileSize_; + const context = createCanvasContext2D(tileSize[0], tileSize[1]); context.strokeStyle = 'black'; context.strokeRect(0.5, 0.5, tileSize[0] + 0.5, tileSize[1] + 0.5); diff --git a/src/ol/source/TileImage.js b/src/ol/source/TileImage.js index 7c71e935a4..61fda97cbd 100644 --- a/src/ol/source/TileImage.js +++ b/src/ol/source/TileImage.js @@ -24,7 +24,7 @@ import _ol_tilegrid_ from '../tilegrid.js'; * @param {olx.source.TileImageOptions} options Image tile options. * @api */ -var TileImage = function(options) { +const TileImage = function(options) { UrlTile.call(this, { attributions: options.attributions, @@ -97,7 +97,7 @@ TileImage.prototype.canExpireCache = function() { if (this.tileCache.canExpireCache()) { return true; } else { - for (var key in this.tileCacheForProjection) { + for (const key in this.tileCacheForProjection) { if (this.tileCacheForProjection[key].canExpireCache()) { return true; } @@ -115,11 +115,11 @@ TileImage.prototype.expireCache = function(projection, usedTiles) { UrlTile.prototype.expireCache.call(this, projection, usedTiles); return; } - var usedTileCache = this.getTileCacheForProjection(projection); + const usedTileCache = this.getTileCacheForProjection(projection); this.tileCache.expireCache(this.tileCache == usedTileCache ? usedTiles : {}); - for (var id in this.tileCacheForProjection) { - var tileCache = this.tileCacheForProjection[id]; + for (const id in this.tileCacheForProjection) { + const tileCache = this.tileCacheForProjection[id]; tileCache.expireCache(tileCache == usedTileCache ? usedTiles : {}); } }; @@ -167,11 +167,11 @@ TileImage.prototype.getTileGridForProjection = function(projection) { if (!ENABLE_RASTER_REPROJECTION) { return UrlTile.prototype.getTileGridForProjection.call(this, projection); } - var thisProj = this.getProjection(); + const thisProj = this.getProjection(); if (this.tileGrid && (!thisProj || equivalent(thisProj, projection))) { return this.tileGrid; } else { - var projKey = getUid(projection).toString(); + const projKey = getUid(projection).toString(); if (!(projKey in this.tileGridForProjection)) { this.tileGridForProjection[projKey] = _ol_tilegrid_.getForProjection(projection); @@ -188,10 +188,10 @@ TileImage.prototype.getTileCacheForProjection = function(projection) { if (!ENABLE_RASTER_REPROJECTION) { return UrlTile.prototype.getTileCacheForProjection.call(this, projection); } - var thisProj = this.getProjection(); if (!thisProj || equivalent(thisProj, projection)) { + const thisProj = this.getProjection(); if (!thisProj || equivalent(thisProj, projection)) { return this.tileCache; } else { - var projKey = getUid(projection).toString(); + const projKey = getUid(projection).toString(); if (!(projKey in this.tileCacheForProjection)) { this.tileCacheForProjection[projKey] = new TileCache(this.tileCache.highWaterMark); } @@ -211,21 +211,21 @@ TileImage.prototype.getTileCacheForProjection = function(projection) { * @private */ TileImage.prototype.createTile_ = function(z, x, y, pixelRatio, projection, key) { - var tileCoord = [z, x, y]; - var urlTileCoord = this.getTileCoordForTileUrlFunction( - tileCoord, projection); - var tileUrl = urlTileCoord ? + const tileCoord = [z, x, y]; + const urlTileCoord = this.getTileCoordForTileUrlFunction( + tileCoord, projection); + const tileUrl = urlTileCoord ? this.tileUrlFunction(urlTileCoord, pixelRatio, projection) : undefined; - var tile = new this.tileClass( - tileCoord, - tileUrl !== undefined ? TileState.IDLE : TileState.EMPTY, - tileUrl !== undefined ? tileUrl : '', - this.crossOrigin, - this.tileLoadFunction, - this.tileOptions); + const tile = new this.tileClass( + tileCoord, + tileUrl !== undefined ? TileState.IDLE : TileState.EMPTY, + tileUrl !== undefined ? tileUrl : '', + this.crossOrigin, + this.tileLoadFunction, + this.tileOptions); tile.key = key; _ol_events_.listen(tile, EventType.CHANGE, - this.handleTileChange, this); + this.handleTileChange, this); return tile; }; @@ -234,35 +234,35 @@ TileImage.prototype.createTile_ = function(z, x, y, pixelRatio, projection, key) * @inheritDoc */ TileImage.prototype.getTile = function(z, x, y, pixelRatio, projection) { - var sourceProjection = /** @type {!ol.proj.Projection} */ (this.getProjection()); + const sourceProjection = /** @type {!ol.proj.Projection} */ (this.getProjection()); if (!ENABLE_RASTER_REPROJECTION || !sourceProjection || !projection || equivalent(sourceProjection, projection)) { return this.getTileInternal(z, x, y, pixelRatio, sourceProjection || projection); } else { - var cache = this.getTileCacheForProjection(projection); - var tileCoord = [z, x, y]; - var tile; - var tileCoordKey = _ol_tilecoord_.getKey(tileCoord); + const cache = this.getTileCacheForProjection(projection); + const tileCoord = [z, x, y]; + let tile; + const tileCoordKey = _ol_tilecoord_.getKey(tileCoord); if (cache.containsKey(tileCoordKey)) { tile = /** @type {!ol.Tile} */ (cache.get(tileCoordKey)); } - var key = this.getKey(); + const key = this.getKey(); if (tile && tile.key == key) { return tile; } else { - var sourceTileGrid = this.getTileGridForProjection(sourceProjection); - var targetTileGrid = this.getTileGridForProjection(projection); - var wrappedTileCoord = + const sourceTileGrid = this.getTileGridForProjection(sourceProjection); + const targetTileGrid = this.getTileGridForProjection(projection); + const wrappedTileCoord = this.getTileCoordForTileUrlFunction(tileCoord, projection); - var newTile = new ReprojTile( - sourceProjection, sourceTileGrid, - projection, targetTileGrid, - tileCoord, wrappedTileCoord, this.getTilePixelRatio(pixelRatio), - this.getGutterInternal(), - function(z, x, y, pixelRatio) { - return this.getTileInternal(z, x, y, pixelRatio, sourceProjection); - }.bind(this), this.reprojectionErrorThreshold_, - this.renderReprojectionEdges_); + const newTile = new ReprojTile( + sourceProjection, sourceTileGrid, + projection, targetTileGrid, + tileCoord, wrappedTileCoord, this.getTilePixelRatio(pixelRatio), + this.getGutterInternal(), + function(z, x, y, pixelRatio) { + return this.getTileInternal(z, x, y, pixelRatio, sourceProjection); + }.bind(this), this.reprojectionErrorThreshold_, + this.renderReprojectionEdges_); newTile.key = key; if (tile) { @@ -288,9 +288,9 @@ TileImage.prototype.getTile = function(z, x, y, pixelRatio, projection) { * @protected */ TileImage.prototype.getTileInternal = function(z, x, y, pixelRatio, projection) { - var tile = null; - var tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); - var key = this.getKey(); + let tile = null; + const tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); + const key = this.getKey(); if (!this.tileCache.containsKey(tileCoordKey)) { tile = this.createTile_(z, x, y, pixelRatio, projection, key); this.tileCache.set(tileCoordKey, tile); @@ -300,7 +300,7 @@ TileImage.prototype.getTileInternal = function(z, x, y, pixelRatio, projection) // The source's params changed. If the tile has an interim tile and if we // can use it then we use it. Otherwise we create a new tile. In both // cases we attempt to assign an interim tile to the new tile. - var interimTile = tile; + const interimTile = tile; tile = this.createTile_(z, x, y, pixelRatio, projection, key); //make the new tile the head of the list, @@ -329,7 +329,7 @@ TileImage.prototype.setRenderReprojectionEdges = function(render) { return; } this.renderReprojectionEdges_ = render; - for (var id in this.tileCacheForProjection) { + for (const id in this.tileCacheForProjection) { this.tileCacheForProjection[id].clear(); } this.changed(); @@ -350,9 +350,9 @@ TileImage.prototype.setRenderReprojectionEdges = function(render) { */ TileImage.prototype.setTileGridForProjection = function(projection, tilegrid) { if (ENABLE_RASTER_REPROJECTION) { - var proj = getProjection(projection); + const proj = getProjection(projection); if (proj) { - var projKey = getUid(proj).toString(); + const projKey = getUid(proj).toString(); if (!(projKey in this.tileGridForProjection)) { this.tileGridForProjection[projKey] = tilegrid; } diff --git a/src/ol/source/TileJSON.js b/src/ol/source/TileJSON.js index d6653c2da0..32681f9aad 100644 --- a/src/ol/source/TileJSON.js +++ b/src/ol/source/TileJSON.js @@ -26,7 +26,7 @@ import _ol_tilegrid_ from '../tilegrid.js'; * @param {olx.source.TileJSONOptions} options TileJSON options. * @api */ -var TileJSON = function(options) { +const TileJSON = function(options) { /** * @type {TileJSON} @@ -49,9 +49,9 @@ var TileJSON = function(options) { if (options.url) { if (options.jsonp) { _ol_net_.jsonp(options.url, this.handleTileJSONResponse.bind(this), - this.handleTileJSONError.bind(this)); + this.handleTileJSONError.bind(this)); } else { - var client = new XMLHttpRequest(); + const client = new XMLHttpRequest(); client.addEventListener('load', this.onXHRLoad_.bind(this)); client.addEventListener('error', this.onXHRError_.bind(this)); client.open('GET', options.url); @@ -73,10 +73,10 @@ inherits(TileJSON, TileImage); * @param {Event} event The load event. */ TileJSON.prototype.onXHRLoad_ = function(event) { - var client = /** @type {XMLHttpRequest} */ (event.target); + const client = /** @type {XMLHttpRequest} */ (event.target); // status will be 0 for file:// urls if (!client.status || client.status >= 200 && client.status < 300) { - var response; + let response; try { response = /** @type {TileJSON} */(JSON.parse(client.responseText)); } catch (err) { @@ -114,19 +114,19 @@ TileJSON.prototype.getTileJSON = function() { */ TileJSON.prototype.handleTileJSONResponse = function(tileJSON) { - var epsg4326Projection = getProjection('EPSG:4326'); + const epsg4326Projection = getProjection('EPSG:4326'); - var sourceProjection = this.getProjection(); - var extent; + const sourceProjection = this.getProjection(); + let extent; if (tileJSON.bounds !== undefined) { - var transform = getTransformFromProjections( - epsg4326Projection, sourceProjection); + const transform = getTransformFromProjections( + epsg4326Projection, sourceProjection); extent = applyTransform(tileJSON.bounds, transform); } - var minZoom = tileJSON.minzoom || 0; - var maxZoom = tileJSON.maxzoom || 22; - var tileGrid = _ol_tilegrid_.createXYZ({ + const minZoom = tileJSON.minzoom || 0; + const maxZoom = tileJSON.maxzoom || 22; + const tileGrid = _ol_tilegrid_.createXYZ({ extent: _ol_tilegrid_.extentFromProjection(sourceProjection), maxZoom: maxZoom, minZoom: minZoom @@ -136,7 +136,7 @@ TileJSON.prototype.handleTileJSONResponse = function(tileJSON) { this.tileUrlFunction = createFromTemplates(tileJSON.tiles, tileGrid); if (tileJSON.attribution !== undefined && !this.getAttributions()) { - var attributionExtent = extent !== undefined ? + const attributionExtent = extent !== undefined ? extent : epsg4326Projection.getExtent(); this.setAttributions(function(frameState) { diff --git a/src/ol/source/TileUTFGrid.js b/src/ol/source/TileUTFGrid.js index afe7effc42..0e1ee9b1a4 100644 --- a/src/ol/source/TileUTFGrid.js +++ b/src/ol/source/TileUTFGrid.js @@ -25,7 +25,7 @@ import _ol_tilegrid_ from '../tilegrid.js'; * @param {olx.source.TileUTFGridOptions} options Source options. * @api */ -var UTFGrid = function(options) { +const UTFGrid = function(options) { TileSource.call(this, { projection: getProjection('EPSG:3857'), state: SourceState.LOADING @@ -59,9 +59,9 @@ var UTFGrid = function(options) { if (options.url) { if (this.jsonp_) { _ol_net_.jsonp(options.url, this.handleTileJSONResponse.bind(this), - this.handleTileJSONError.bind(this)); + this.handleTileJSONError.bind(this)); } else { - var client = new XMLHttpRequest(); + const client = new XMLHttpRequest(); client.addEventListener('load', this.onXHRLoad_.bind(this)); client.addEventListener('error', this.onXHRError_.bind(this)); client.open('GET', options.url); @@ -82,10 +82,10 @@ inherits(UTFGrid, TileSource); * @param {Event} event The load event. */ UTFGrid.prototype.onXHRLoad_ = function(event) { - var client = /** @type {XMLHttpRequest} */ (event.target); + const client = /** @type {XMLHttpRequest} */ (event.target); // status will be 0 for file:// urls if (!client.status || client.status >= 200 && client.status < 300) { - var response; + let response; try { response = /** @type {TileJSON} */(JSON.parse(client.responseText)); } catch (err) { @@ -130,12 +130,12 @@ UTFGrid.prototype.getTemplate = function() { * @api */ UTFGrid.prototype.forDataAtCoordinateAndResolution = function( - coordinate, resolution, callback, opt_request) { + coordinate, resolution, callback, opt_request) { if (this.tileGrid) { - var tileCoord = this.tileGrid.getTileCoordForCoordAndResolution( - coordinate, resolution); - var tile = /** @type {!ol.source.TileUTFGrid.Tile_} */(this.getTile( - tileCoord[0], tileCoord[1], tileCoord[2], 1, this.getProjection())); + const tileCoord = this.tileGrid.getTileCoordForCoordAndResolution( + coordinate, resolution); + const tile = /** @type {!ol.source.TileUTFGrid.Tile_} */(this.getTile( + tileCoord[0], tileCoord[1], tileCoord[2], 1, this.getProjection())); tile.forDataAtCoordinate(coordinate, callback, null, opt_request); } else { if (opt_request === true) { @@ -164,19 +164,19 @@ UTFGrid.prototype.handleTileJSONError = function() { */ UTFGrid.prototype.handleTileJSONResponse = function(tileJSON) { - var epsg4326Projection = getProjection('EPSG:4326'); + const epsg4326Projection = getProjection('EPSG:4326'); - var sourceProjection = this.getProjection(); - var extent; + const sourceProjection = this.getProjection(); + let extent; if (tileJSON.bounds !== undefined) { - var transform = getTransformFromProjections( - epsg4326Projection, sourceProjection); + const transform = getTransformFromProjections( + epsg4326Projection, sourceProjection); extent = applyTransform(tileJSON.bounds, transform); } - var minZoom = tileJSON.minzoom || 0; - var maxZoom = tileJSON.maxzoom || 22; - var tileGrid = _ol_tilegrid_.createXYZ({ + const minZoom = tileJSON.minzoom || 0; + const maxZoom = tileJSON.maxzoom || 22; + const tileGrid = _ol_tilegrid_.createXYZ({ extent: _ol_tilegrid_.extentFromProjection(sourceProjection), maxZoom: maxZoom, minZoom: minZoom @@ -185,7 +185,7 @@ UTFGrid.prototype.handleTileJSONResponse = function(tileJSON) { this.template_ = tileJSON.template; - var grids = tileJSON.grids; + const grids = tileJSON.grids; if (!grids) { this.setState(SourceState.ERROR); return; @@ -194,7 +194,7 @@ UTFGrid.prototype.handleTileJSONResponse = function(tileJSON) { this.tileUrlFunction_ = createFromTemplates(grids, tileGrid); if (tileJSON.attribution !== undefined) { - var attributionExtent = extent !== undefined ? + const attributionExtent = extent !== undefined ? extent : epsg4326Projection.getExtent(); this.setAttributions(function(frameState) { @@ -214,21 +214,21 @@ UTFGrid.prototype.handleTileJSONResponse = function(tileJSON) { * @inheritDoc */ UTFGrid.prototype.getTile = function(z, x, y, pixelRatio, projection) { - var tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); + const tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); if (this.tileCache.containsKey(tileCoordKey)) { return /** @type {!ol.Tile} */ (this.tileCache.get(tileCoordKey)); } else { - var tileCoord = [z, x, y]; - var urlTileCoord = + const tileCoord = [z, x, y]; + const urlTileCoord = this.getTileCoordForTileUrlFunction(tileCoord, projection); - var tileUrl = this.tileUrlFunction_(urlTileCoord, pixelRatio, projection); - var tile = new UTFGrid.Tile_( - tileCoord, - tileUrl !== undefined ? TileState.IDLE : TileState.EMPTY, - tileUrl !== undefined ? tileUrl : '', - this.tileGrid.getTileCoordExtent(tileCoord), - this.preemptive_, - this.jsonp_); + const tileUrl = this.tileUrlFunction_(urlTileCoord, pixelRatio, projection); + const tile = new UTFGrid.Tile_( + tileCoord, + tileUrl !== undefined ? TileState.IDLE : TileState.EMPTY, + tileUrl !== undefined ? tileUrl : '', + this.tileGrid.getTileCoordExtent(tileCoord), + this.preemptive_, + this.jsonp_); this.tileCache.set(tileCoordKey, tile); return tile; } @@ -239,7 +239,7 @@ UTFGrid.prototype.getTile = function(z, x, y, pixelRatio, projection) { * @inheritDoc */ UTFGrid.prototype.useTile = function(z, x, y) { - var tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); + const tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); if (this.tileCache.containsKey(tileCoordKey)) { this.tileCache.get(tileCoordKey); } @@ -326,18 +326,18 @@ UTFGrid.Tile_.prototype.getData = function(coordinate) { if (!this.grid_ || !this.keys_) { return null; } - var xRelative = (coordinate[0] - this.extent_[0]) / + const xRelative = (coordinate[0] - this.extent_[0]) / (this.extent_[2] - this.extent_[0]); - var yRelative = (coordinate[1] - this.extent_[1]) / + const yRelative = (coordinate[1] - this.extent_[1]) / (this.extent_[3] - this.extent_[1]); - var row = this.grid_[Math.floor((1 - yRelative) * this.grid_.length)]; + const row = this.grid_[Math.floor((1 - yRelative) * this.grid_.length)]; if (typeof row !== 'string') { return null; } - var code = row.charCodeAt(Math.floor(xRelative * row.length)); + let code = row.charCodeAt(Math.floor(xRelative * row.length)); if (code >= 93) { code--; } @@ -346,9 +346,9 @@ UTFGrid.Tile_.prototype.getData = function(coordinate) { } code -= 32; - var data = null; + let data = null; if (code in this.keys_) { - var id = this.keys_[code]; + const id = this.keys_[code]; if (this.data_ && id in this.data_) { data = this.data_[id]; } else { @@ -426,9 +426,9 @@ UTFGrid.Tile_.prototype.loadInternal_ = function() { this.state = TileState.LOADING; if (this.jsonp_) { _ol_net_.jsonp(this.src_, this.handleLoad_.bind(this), - this.handleError_.bind(this)); + this.handleError_.bind(this)); } else { - var client = new XMLHttpRequest(); + const client = new XMLHttpRequest(); client.addEventListener('load', this.onXHRLoad_.bind(this)); client.addEventListener('error', this.onXHRError_.bind(this)); client.open('GET', this.src_); @@ -443,10 +443,10 @@ UTFGrid.Tile_.prototype.loadInternal_ = function() { * @param {Event} event The load event. */ UTFGrid.Tile_.prototype.onXHRLoad_ = function(event) { - var client = /** @type {XMLHttpRequest} */ (event.target); + const client = /** @type {XMLHttpRequest} */ (event.target); // status will be 0 for file:// urls if (!client.status || client.status >= 200 && client.status < 300) { - var response; + let response; try { response = /** @type {!UTFGridJSON} */(JSON.parse(client.responseText)); } catch (err) { diff --git a/src/ol/source/TileWMS.js b/src/ol/source/TileWMS.js index fb078c4a3d..23180d8a21 100644 --- a/src/ol/source/TileWMS.js +++ b/src/ol/source/TileWMS.js @@ -26,13 +26,13 @@ import _ol_uri_ from '../uri.js'; * @param {olx.source.TileWMSOptions=} opt_options Tile WMS options. * @api */ -var TileWMS = function(opt_options) { +const TileWMS = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; - var params = options.params || {}; + const params = options.params || {}; - var transparent = 'TRANSPARENT' in params ? params['TRANSPARENT'] : true; + const transparent = 'TRANSPARENT' in params ? params['TRANSPARENT'] : true; TileImage.call(this, { attributions: options.attributions, @@ -109,26 +109,26 @@ inherits(TileWMS, TileImage); * @api */ TileWMS.prototype.getGetFeatureInfoUrl = function(coordinate, resolution, projection, params) { - var projectionObj = getProjection(projection); - var sourceProjectionObj = this.getProjection(); + const projectionObj = getProjection(projection); + const sourceProjectionObj = this.getProjection(); - var tileGrid = this.getTileGrid(); + let tileGrid = this.getTileGrid(); if (!tileGrid) { tileGrid = this.getTileGridForProjection(projectionObj); } - var tileCoord = tileGrid.getTileCoordForCoordAndResolution(coordinate, resolution); + const tileCoord = tileGrid.getTileCoordForCoordAndResolution(coordinate, resolution); if (tileGrid.getResolutions().length <= tileCoord[0]) { return undefined; } - var tileResolution = tileGrid.getResolution(tileCoord[0]); - var tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_); - var tileSize = _ol_size_.toSize(tileGrid.getTileSize(tileCoord[0]), this.tmpSize); + let tileResolution = tileGrid.getResolution(tileCoord[0]); + let tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_); + let tileSize = _ol_size_.toSize(tileGrid.getTileSize(tileCoord[0]), this.tmpSize); - var gutter = this.gutter_; + const gutter = this.gutter_; if (gutter !== 0) { tileSize = _ol_size_.buffer(tileSize, gutter, this.tmpSize); tileExtent = buffer(tileExtent, tileResolution * gutter, tileExtent); @@ -140,7 +140,7 @@ TileWMS.prototype.getGetFeatureInfoUrl = function(coordinate, resolution, projec coordinate = transform(coordinate, projectionObj, sourceProjectionObj); } - var baseParams = { + const baseParams = { 'SERVICE': 'WMS', 'VERSION': DEFAULT_WMS_VERSION, 'REQUEST': 'GetFeatureInfo', @@ -150,14 +150,14 @@ TileWMS.prototype.getGetFeatureInfoUrl = function(coordinate, resolution, projec }; _ol_obj_.assign(baseParams, this.params_, params); - var x = Math.floor((coordinate[0] - tileExtent[0]) / tileResolution); - var y = Math.floor((tileExtent[3] - coordinate[1]) / tileResolution); + const x = Math.floor((coordinate[0] - tileExtent[0]) / tileResolution); + const y = Math.floor((tileExtent[3] - coordinate[1]) / tileResolution); baseParams[this.v13_ ? 'I' : 'X'] = x; baseParams[this.v13_ ? 'J' : 'Y'] = y; return this.getRequestUrl_(tileCoord, tileSize, tileExtent, - 1, sourceProjectionObj || projectionObj, baseParams); + 1, sourceProjectionObj || projectionObj, baseParams); }; @@ -191,9 +191,9 @@ TileWMS.prototype.getParams = function() { * @private */ TileWMS.prototype.getRequestUrl_ = function(tileCoord, tileSize, tileExtent, - pixelRatio, projection, params) { + pixelRatio, projection, params) { - var urls = this.urls; + const urls = this.urls; if (!urls) { return undefined; } @@ -210,7 +210,7 @@ TileWMS.prototype.getRequestUrl_ = function(tileCoord, tileSize, tileExtent, if (pixelRatio != 1) { switch (this.serverType_) { case WMSServerType.GEOSERVER: - var dpi = (90 * pixelRatio + 0.5) | 0; + const dpi = (90 * pixelRatio + 0.5) | 0; if ('FORMAT_OPTIONS' in params) { params['FORMAT_OPTIONS'] += ';dpi:' + dpi; } else { @@ -230,10 +230,10 @@ TileWMS.prototype.getRequestUrl_ = function(tileCoord, tileSize, tileExtent, } } - var axisOrientation = projection.getAxisOrientation(); - var bbox = tileExtent; + const axisOrientation = projection.getAxisOrientation(); + const bbox = tileExtent; if (this.v13_ && axisOrientation.substr(0, 2) == 'ne') { - var tmp; + let tmp; tmp = tileExtent[0]; bbox[0] = tileExtent[1]; bbox[1] = tmp; @@ -243,11 +243,11 @@ TileWMS.prototype.getRequestUrl_ = function(tileCoord, tileSize, tileExtent, } params['BBOX'] = bbox.join(','); - var url; + let url; if (urls.length == 1) { url = urls[0]; } else { - var index = modulo(_ol_tilecoord_.hash(tileCoord), urls.length); + const index = modulo(_ol_tilecoord_.hash(tileCoord), urls.length); url = urls[index]; } return _ol_uri_.appendParams(url, params); @@ -268,9 +268,9 @@ TileWMS.prototype.getTilePixelRatio = function(pixelRatio) { * @return {string} The key for the current params. */ TileWMS.prototype.getKeyForParams_ = function() { - var i = 0; - var res = []; - for (var key in this.params_) { + let i = 0; + const res = []; + for (const key in this.params_) { res[i++] = key + '-' + this.params_[key]; } return res.join('/'); @@ -282,7 +282,7 @@ TileWMS.prototype.getKeyForParams_ = function() { */ TileWMS.prototype.fixedTileUrlFunction = function(tileCoord, pixelRatio, projection) { - var tileGrid = this.getTileGrid(); + let tileGrid = this.getTileGrid(); if (!tileGrid) { tileGrid = this.getTileGridForProjection(projection); } @@ -295,12 +295,12 @@ TileWMS.prototype.fixedTileUrlFunction = function(tileCoord, pixelRatio, project pixelRatio = 1; } - var tileResolution = tileGrid.getResolution(tileCoord[0]); - var tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_); - var tileSize = _ol_size_.toSize( - tileGrid.getTileSize(tileCoord[0]), this.tmpSize); + const tileResolution = tileGrid.getResolution(tileCoord[0]); + let tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_); + let tileSize = _ol_size_.toSize( + tileGrid.getTileSize(tileCoord[0]), this.tmpSize); - var gutter = this.gutter_; + const gutter = this.gutter_; if (gutter !== 0) { tileSize = _ol_size_.buffer(tileSize, gutter, this.tmpSize); tileExtent = buffer(tileExtent, tileResolution * gutter, tileExtent); @@ -310,7 +310,7 @@ TileWMS.prototype.fixedTileUrlFunction = function(tileCoord, pixelRatio, project tileSize = _ol_size_.scale(tileSize, pixelRatio, this.tmpSize); } - var baseParams = { + const baseParams = { 'SERVICE': 'WMS', 'VERSION': DEFAULT_WMS_VERSION, 'REQUEST': 'GetMap', @@ -320,7 +320,7 @@ TileWMS.prototype.fixedTileUrlFunction = function(tileCoord, pixelRatio, project _ol_obj_.assign(baseParams, this.params_); return this.getRequestUrl_(tileCoord, tileSize, tileExtent, - pixelRatio, projection, baseParams); + pixelRatio, projection, baseParams); }; /** @@ -339,7 +339,7 @@ TileWMS.prototype.updateParams = function(params) { * @private */ TileWMS.prototype.updateV13_ = function() { - var version = this.params_['VERSION'] || DEFAULT_WMS_VERSION; + const version = this.params_['VERSION'] || DEFAULT_WMS_VERSION; this.v13_ = _ol_string_.compareVersions(version, '1.3') >= 0; }; export default TileWMS; diff --git a/src/ol/source/UrlTile.js b/src/ol/source/UrlTile.js index f29470b0ca..3e6a354873 100644 --- a/src/ol/source/UrlTile.js +++ b/src/ol/source/UrlTile.js @@ -18,7 +18,7 @@ import _ol_tilecoord_ from '../tilecoord.js'; * @extends {ol.source.Tile} * @param {ol.SourceUrlTileOptions} options Image tile options. */ -var UrlTile = function(options) { +const UrlTile = function(options) { TileSource.call(this, { attributions: options.attributions, @@ -116,10 +116,10 @@ UrlTile.prototype.getUrls = function() { * @protected */ UrlTile.prototype.handleTileChange = function(event) { - var tile = /** @type {ol.Tile} */ (event.target); - var uid = getUid(tile); - var tileState = tile.getState(); - var type; + const tile = /** @type {ol.Tile} */ (event.target); + const uid = getUid(tile); + const tileState = tile.getState(); + let type; if (tileState == TileState.LOADING) { this.tileLoadingKeys_[uid] = true; type = TileEventType.TILELOADSTART; @@ -170,7 +170,7 @@ UrlTile.prototype.setTileUrlFunction = function(tileUrlFunction, opt_key) { * @api */ UrlTile.prototype.setUrl = function(url) { - var urls = this.urls = expandUrl(url); + const urls = this.urls = expandUrl(url); this.setTileUrlFunction(this.fixedTileUrlFunction ? this.fixedTileUrlFunction.bind(this) : createFromTemplates(urls, this.tileGrid), url); @@ -184,7 +184,7 @@ UrlTile.prototype.setUrl = function(url) { */ UrlTile.prototype.setUrls = function(urls) { this.urls = urls; - var key = urls.join('\n'); + const key = urls.join('\n'); this.setTileUrlFunction(this.fixedTileUrlFunction ? this.fixedTileUrlFunction.bind(this) : createFromTemplates(urls, this.tileGrid), key); @@ -195,7 +195,7 @@ UrlTile.prototype.setUrls = function(urls) { * @inheritDoc */ UrlTile.prototype.useTile = function(z, x, y) { - var tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); + const tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); if (this.tileCache.containsKey(tileCoordKey)) { this.tileCache.get(tileCoordKey); } diff --git a/src/ol/source/Vector.js b/src/ol/source/Vector.js index e2ff2799c3..b02b5807d6 100644 --- a/src/ol/source/Vector.js +++ b/src/ol/source/Vector.js @@ -33,9 +33,9 @@ import RBush from '../structs/RBush.js'; * @param {olx.source.VectorOptions=} opt_options Vector source options. * @api */ -var VectorSource = function(opt_options) { +const VectorSource = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; Source.call(this, { attributions: options.attributions, @@ -83,7 +83,7 @@ var VectorSource = function(opt_options) { this.strategy_ = options.strategy !== undefined ? options.strategy : _ol_loadingstrategy_.all; - var useSpatialIndex = + const useSpatialIndex = options.useSpatialIndex !== undefined ? options.useSpatialIndex : true; /** @@ -130,7 +130,7 @@ var VectorSource = function(opt_options) { */ this.featuresCollection_ = null; - var collection, features; + let collection, features; if (options.features instanceof Collection) { collection = options.features; features = collection.getArray(); @@ -173,7 +173,7 @@ VectorSource.prototype.addFeature = function(feature) { * @protected */ VectorSource.prototype.addFeatureInternal = function(feature) { - var featureKey = getUid(feature).toString(); + const featureKey = getUid(feature).toString(); if (!this.addToIndex_(featureKey, feature)) { return; @@ -181,9 +181,9 @@ VectorSource.prototype.addFeatureInternal = function(feature) { this.setupChangeEvents_(featureKey, feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); if (geometry) { - var extent = geometry.getExtent(); + const extent = geometry.getExtent(); if (this.featuresRtree_) { this.featuresRtree_.insert(extent, feature); } @@ -192,7 +192,7 @@ VectorSource.prototype.addFeatureInternal = function(feature) { } this.dispatchEvent( - new VectorSource.Event(VectorEventType.ADDFEATURE, feature)); + new VectorSource.Event(VectorEventType.ADDFEATURE, feature)); }; @@ -204,9 +204,9 @@ VectorSource.prototype.addFeatureInternal = function(feature) { VectorSource.prototype.setupChangeEvents_ = function(featureKey, feature) { this.featureChangeKeys_[featureKey] = [ _ol_events_.listen(feature, EventType.CHANGE, - this.handleFeatureChange_, this), + this.handleFeatureChange_, this), _ol_events_.listen(feature, ObjectEventType.PROPERTYCHANGE, - this.handleFeatureChange_, this) + this.handleFeatureChange_, this) ]; }; @@ -219,8 +219,8 @@ VectorSource.prototype.setupChangeEvents_ = function(featureKey, feature) { * @private */ VectorSource.prototype.addToIndex_ = function(featureKey, feature) { - var valid = true; - var id = feature.getId(); + let valid = true; + const id = feature.getId(); if (id !== undefined) { if (!(id.toString() in this.idIndex_)) { this.idIndex_[id.toString()] = feature; @@ -229,7 +229,7 @@ VectorSource.prototype.addToIndex_ = function(featureKey, feature) { } } else { assert(!(featureKey in this.undefIdIndex_), - 30); // The passed `feature` was already added to the source + 30); // The passed `feature` was already added to the source this.undefIdIndex_[featureKey] = feature; } return valid; @@ -253,11 +253,11 @@ VectorSource.prototype.addFeatures = function(features) { * @protected */ VectorSource.prototype.addFeaturesInternal = function(features) { - var featureKey, i, length, feature; + let featureKey, i, length, feature; - var extents = []; - var newFeatures = []; - var geometryFeatures = []; + const extents = []; + const newFeatures = []; + const geometryFeatures = []; for (i = 0, length = features.length; i < length; i++) { feature = features[i]; @@ -272,9 +272,9 @@ VectorSource.prototype.addFeaturesInternal = function(features) { featureKey = getUid(feature).toString(); this.setupChangeEvents_(featureKey, feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); if (geometry) { - var extent = geometry.getExtent(); + const extent = geometry.getExtent(); extents.push(extent); geometryFeatures.push(feature); } else { @@ -287,7 +287,7 @@ VectorSource.prototype.addFeaturesInternal = function(features) { for (i = 0, length = newFeatures.length; i < length; i++) { this.dispatchEvent(new VectorSource.Event( - VectorEventType.ADDFEATURE, newFeatures[i])); + VectorEventType.ADDFEATURE, newFeatures[i])); } }; @@ -297,39 +297,39 @@ VectorSource.prototype.addFeaturesInternal = function(features) { * @private */ VectorSource.prototype.bindFeaturesCollection_ = function(collection) { - var modifyingCollection = false; + let modifyingCollection = false; _ol_events_.listen(this, VectorEventType.ADDFEATURE, - function(evt) { - if (!modifyingCollection) { - modifyingCollection = true; - collection.push(evt.feature); - modifyingCollection = false; - } - }); + function(evt) { + if (!modifyingCollection) { + modifyingCollection = true; + collection.push(evt.feature); + modifyingCollection = false; + } + }); _ol_events_.listen(this, VectorEventType.REMOVEFEATURE, - function(evt) { - if (!modifyingCollection) { - modifyingCollection = true; - collection.remove(evt.feature); - modifyingCollection = false; - } - }); + function(evt) { + if (!modifyingCollection) { + modifyingCollection = true; + collection.remove(evt.feature); + modifyingCollection = false; + } + }); _ol_events_.listen(collection, CollectionEventType.ADD, - function(evt) { - if (!modifyingCollection) { - modifyingCollection = true; - this.addFeature(/** @type {ol.Feature} */ (evt.element)); - modifyingCollection = false; - } - }, this); + function(evt) { + if (!modifyingCollection) { + modifyingCollection = true; + this.addFeature(/** @type {ol.Feature} */ (evt.element)); + modifyingCollection = false; + } + }, this); _ol_events_.listen(collection, CollectionEventType.REMOVE, - function(evt) { - if (!modifyingCollection) { - modifyingCollection = true; - this.removeFeature(/** @type {ol.Feature} */ (evt.element)); - modifyingCollection = false; - } - }, this); + function(evt) { + if (!modifyingCollection) { + modifyingCollection = true; + this.removeFeature(/** @type {ol.Feature} */ (evt.element)); + modifyingCollection = false; + } + }, this); this.featuresCollection_ = collection; }; @@ -341,8 +341,8 @@ VectorSource.prototype.bindFeaturesCollection_ = function(collection) { */ VectorSource.prototype.clear = function(opt_fast) { if (opt_fast) { - for (var featureId in this.featureChangeKeys_) { - var keys = this.featureChangeKeys_[featureId]; + for (const featureId in this.featureChangeKeys_) { + const keys = this.featureChangeKeys_[featureId]; keys.forEach(_ol_events_.unlistenByKey); } if (!this.featuresCollection_) { @@ -353,7 +353,7 @@ VectorSource.prototype.clear = function(opt_fast) { } else { if (this.featuresRtree_) { this.featuresRtree_.forEach(this.removeFeatureInternal, this); - for (var id in this.nullGeometryFeatures_) { + for (const id in this.nullGeometryFeatures_) { this.removeFeatureInternal(this.nullGeometryFeatures_[id]); } } @@ -368,7 +368,7 @@ VectorSource.prototype.clear = function(opt_fast) { this.loadedExtentsRtree_.clear(); this.nullGeometryFeatures_ = {}; - var clearEvent = new VectorSource.Event(VectorEventType.CLEAR); + const clearEvent = new VectorSource.Event(VectorEventType.CLEAR); this.dispatchEvent(clearEvent); this.changed(); }; @@ -407,9 +407,9 @@ VectorSource.prototype.forEachFeature = function(callback) { * @template T */ VectorSource.prototype.forEachFeatureAtCoordinateDirect = function(coordinate, callback) { - var extent = [coordinate[0], coordinate[1], coordinate[0], coordinate[1]]; + const extent = [coordinate[0], coordinate[1], coordinate[0], coordinate[1]]; return this.forEachFeatureInExtent(extent, function(feature) { - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); if (geometry.intersectsCoordinate(coordinate)) { return callback(feature); } else { @@ -466,20 +466,20 @@ VectorSource.prototype.forEachFeatureInExtent = function(extent, callback) { */ VectorSource.prototype.forEachFeatureIntersectingExtent = function(extent, callback) { return this.forEachFeatureInExtent(extent, - /** + /** * @param {ol.Feature} feature Feature. * @return {T|undefined} The return value from the last call to the callback. * @template T */ - function(feature) { - var geometry = feature.getGeometry(); - if (geometry.intersectsExtent(extent)) { - var result = callback(feature); - if (result) { - return result; - } + function(feature) { + const geometry = feature.getGeometry(); + if (geometry.intersectsExtent(extent)) { + const result = callback(feature); + if (result) { + return result; } - }); + } + }); }; @@ -501,7 +501,7 @@ VectorSource.prototype.getFeaturesCollection = function() { * @api */ VectorSource.prototype.getFeatures = function() { - var features; + let features; if (this.featuresCollection_) { features = this.featuresCollection_.getArray(); } else if (this.featuresRtree_) { @@ -521,7 +521,7 @@ VectorSource.prototype.getFeatures = function() { * @api */ VectorSource.prototype.getFeaturesAtCoordinate = function(coordinate) { - var features = []; + const features = []; this.forEachFeatureAtCoordinateDirect(coordinate, function(feature) { features.push(feature); }); @@ -565,37 +565,37 @@ VectorSource.prototype.getClosestFeatureToCoordinate = function(coordinate, opt_ // extent, trying to find a closer feature. Every time we find a closer // feature, we update the extent being searched so that any even closer // feature must intersect it. We continue until we run out of features. - var x = coordinate[0]; - var y = coordinate[1]; - var closestFeature = null; - var closestPoint = [NaN, NaN]; - var minSquaredDistance = Infinity; - var extent = [-Infinity, -Infinity, Infinity, Infinity]; - var filter = opt_filter ? opt_filter : TRUE; + const x = coordinate[0]; + const y = coordinate[1]; + let closestFeature = null; + const closestPoint = [NaN, NaN]; + let minSquaredDistance = Infinity; + const extent = [-Infinity, -Infinity, Infinity, Infinity]; + const filter = opt_filter ? opt_filter : TRUE; this.featuresRtree_.forEachInExtent(extent, - /** + /** * @param {ol.Feature} feature Feature. */ - function(feature) { - if (filter(feature)) { - var geometry = feature.getGeometry(); - var previousMinSquaredDistance = minSquaredDistance; - minSquaredDistance = geometry.closestPointXY( - x, y, closestPoint, minSquaredDistance); - if (minSquaredDistance < previousMinSquaredDistance) { - closestFeature = feature; - // This is sneaky. Reduce the extent that it is currently being - // searched while the R-Tree traversal using this same extent object - // is still in progress. This is safe because the new extent is - // strictly contained by the old extent. - var minDistance = Math.sqrt(minSquaredDistance); - extent[0] = x - minDistance; - extent[1] = y - minDistance; - extent[2] = x + minDistance; - extent[3] = y + minDistance; - } + function(feature) { + if (filter(feature)) { + const geometry = feature.getGeometry(); + const previousMinSquaredDistance = minSquaredDistance; + minSquaredDistance = geometry.closestPointXY( + x, y, closestPoint, minSquaredDistance); + if (minSquaredDistance < previousMinSquaredDistance) { + closestFeature = feature; + // This is sneaky. Reduce the extent that it is currently being + // searched while the R-Tree traversal using this same extent object + // is still in progress. This is safe because the new extent is + // strictly contained by the old extent. + const minDistance = Math.sqrt(minSquaredDistance); + extent[0] = x - minDistance; + extent[1] = y - minDistance; + extent[2] = x + minDistance; + extent[3] = y + minDistance; } - }); + } + }); return closestFeature; }; @@ -625,7 +625,7 @@ VectorSource.prototype.getExtent = function(opt_extent) { * @api */ VectorSource.prototype.getFeatureById = function(id) { - var feature = this.idIndex_[id.toString()]; + const feature = this.idIndex_[id.toString()]; return feature !== undefined ? feature : null; }; @@ -671,9 +671,9 @@ VectorSource.prototype.getUrl = function() { * @private */ VectorSource.prototype.handleFeatureChange_ = function(event) { - var feature = /** @type {ol.Feature} */ (event.target); - var featureKey = getUid(feature).toString(); - var geometry = feature.getGeometry(); + const feature = /** @type {ol.Feature} */ (event.target); + const featureKey = getUid(feature).toString(); + const geometry = feature.getGeometry(); if (!geometry) { if (!(featureKey in this.nullGeometryFeatures_)) { if (this.featuresRtree_) { @@ -682,7 +682,7 @@ VectorSource.prototype.handleFeatureChange_ = function(event) { this.nullGeometryFeatures_[featureKey] = feature; } } else { - var extent = geometry.getExtent(); + const extent = geometry.getExtent(); if (featureKey in this.nullGeometryFeatures_) { delete this.nullGeometryFeatures_[featureKey]; if (this.featuresRtree_) { @@ -694,9 +694,9 @@ VectorSource.prototype.handleFeatureChange_ = function(event) { } } } - var id = feature.getId(); + const id = feature.getId(); if (id !== undefined) { - var sid = id.toString(); + const sid = id.toString(); if (featureKey in this.undefIdIndex_) { delete this.undefIdIndex_[featureKey]; this.idIndex_[sid] = feature; @@ -714,7 +714,7 @@ VectorSource.prototype.handleFeatureChange_ = function(event) { } this.changed(); this.dispatchEvent(new VectorSource.Event( - VectorEventType.CHANGEFEATURE, feature)); + VectorEventType.CHANGEFEATURE, feature)); }; @@ -733,20 +733,20 @@ VectorSource.prototype.isEmpty = function() { * @param {ol.proj.Projection} projection Projection. */ VectorSource.prototype.loadFeatures = function( - extent, resolution, projection) { - var loadedExtentsRtree = this.loadedExtentsRtree_; - var extentsToLoad = this.strategy_(extent, resolution); - var i, ii; + extent, resolution, projection) { + const loadedExtentsRtree = this.loadedExtentsRtree_; + const extentsToLoad = this.strategy_(extent, resolution); + let i, ii; for (i = 0, ii = extentsToLoad.length; i < ii; ++i) { - var extentToLoad = extentsToLoad[i]; - var alreadyLoaded = loadedExtentsRtree.forEachInExtent(extentToLoad, - /** + const extentToLoad = extentsToLoad[i]; + const alreadyLoaded = loadedExtentsRtree.forEachInExtent(extentToLoad, + /** * @param {{extent: ol.Extent}} object Object. * @return {boolean} Contains. */ - function(object) { - return containsExtent(object.extent, extentToLoad); - }); + function(object) { + return containsExtent(object.extent, extentToLoad); + }); if (!alreadyLoaded) { this.loader_.call(this, extentToLoad, resolution, projection); loadedExtentsRtree.insert(extentToLoad, {extent: extentToLoad.slice()}); @@ -761,8 +761,8 @@ VectorSource.prototype.loadFeatures = function( * @api */ VectorSource.prototype.removeLoadedExtent = function(extent) { - var loadedExtentsRtree = this.loadedExtentsRtree_; - var obj; + const loadedExtentsRtree = this.loadedExtentsRtree_; + let obj; loadedExtentsRtree.forEachInExtent(extent, function(object) { if (equals(object.extent, extent)) { obj = object; @@ -783,7 +783,7 @@ VectorSource.prototype.removeLoadedExtent = function(extent) { * @api */ VectorSource.prototype.removeFeature = function(feature) { - var featureKey = getUid(feature).toString(); + const featureKey = getUid(feature).toString(); if (featureKey in this.nullGeometryFeatures_) { delete this.nullGeometryFeatures_[featureKey]; } else { @@ -802,17 +802,17 @@ VectorSource.prototype.removeFeature = function(feature) { * @protected */ VectorSource.prototype.removeFeatureInternal = function(feature) { - var featureKey = getUid(feature).toString(); + const featureKey = getUid(feature).toString(); this.featureChangeKeys_[featureKey].forEach(_ol_events_.unlistenByKey); delete this.featureChangeKeys_[featureKey]; - var id = feature.getId(); + const id = feature.getId(); if (id !== undefined) { delete this.idIndex_[id.toString()]; } else { delete this.undefIdIndex_[featureKey]; } this.dispatchEvent(new VectorSource.Event( - VectorEventType.REMOVEFEATURE, feature)); + VectorEventType.REMOVEFEATURE, feature)); }; @@ -824,8 +824,8 @@ VectorSource.prototype.removeFeatureInternal = function(feature) { * @private */ VectorSource.prototype.removeFromIdIndex_ = function(feature) { - var removed = false; - for (var id in this.idIndex_) { + let removed = false; + for (const id in this.idIndex_) { if (this.idIndex_[id] === feature) { delete this.idIndex_[id]; removed = true; diff --git a/src/ol/source/VectorTile.js b/src/ol/source/VectorTile.js index 6287477ad3..9ee2f9a52f 100644 --- a/src/ol/source/VectorTile.js +++ b/src/ol/source/VectorTile.js @@ -26,12 +26,12 @@ import _ol_tilegrid_ from '../tilegrid.js'; * @param {olx.source.VectorTileOptions} options Vector tile options. * @api */ -var VectorTileSource = function(options) { - var projection = options.projection || 'EPSG:3857'; +const VectorTileSource = function(options) { + const projection = options.projection || 'EPSG:3857'; - var extent = options.extent || _ol_tilegrid_.extentFromProjection(projection); + const extent = options.extent || _ol_tilegrid_.extentFromProjection(projection); - var tileGrid = options.tileGrid || _ol_tilegrid_.createXYZ({ + const tileGrid = options.tileGrid || _ol_tilegrid_.createXYZ({ extent: extent, maxZoom: options.maxZoom || 22, minZoom: options.minZoom, @@ -110,22 +110,22 @@ VectorTileSource.prototype.clear = function() { * @inheritDoc */ VectorTileSource.prototype.getTile = function(z, x, y, pixelRatio, projection) { - var tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); + const tileCoordKey = _ol_tilecoord_.getKeyZXY(z, x, y); if (this.tileCache.containsKey(tileCoordKey)) { return /** @type {!ol.Tile} */ (this.tileCache.get(tileCoordKey)); } else { - var tileCoord = [z, x, y]; - var urlTileCoord = this.getTileCoordForTileUrlFunction( - tileCoord, projection); - var tile = new VectorImageTile( - tileCoord, - urlTileCoord !== null ? TileState.IDLE : TileState.EMPTY, - this.getRevision(), - this.format_, this.tileLoadFunction, urlTileCoord, this.tileUrlFunction, - this.tileGrid, this.getTileGridForProjection(projection), - this.sourceTiles_, pixelRatio, projection, this.tileClass, - this.handleTileChange.bind(this), - this.tileOptions); + const tileCoord = [z, x, y]; + const urlTileCoord = this.getTileCoordForTileUrlFunction( + tileCoord, projection); + const tile = new VectorImageTile( + tileCoord, + urlTileCoord !== null ? TileState.IDLE : TileState.EMPTY, + this.getRevision(), + this.format_, this.tileLoadFunction, urlTileCoord, this.tileUrlFunction, + this.tileGrid, this.getTileGridForProjection(projection), + this.sourceTiles_, pixelRatio, projection, this.tileClass, + this.handleTileChange.bind(this), + this.tileOptions); this.tileCache.set(tileCoordKey, tile); return tile; @@ -137,14 +137,14 @@ VectorTileSource.prototype.getTile = function(z, x, y, pixelRatio, projection) { * @inheritDoc */ VectorTileSource.prototype.getTileGridForProjection = function(projection) { - var code = projection.getCode(); - var tileGrid = this.tileGrids_[code]; + const code = projection.getCode(); + let tileGrid = this.tileGrids_[code]; if (!tileGrid) { // A tile grid that matches the tile size of the source tile grid is more // likely to have 1:1 relationships between source tiles and rendered tiles. - var sourceTileGrid = this.tileGrid; + const sourceTileGrid = this.tileGrid; tileGrid = this.tileGrids_[code] = _ol_tilegrid_.createForProjection(projection, undefined, - sourceTileGrid ? sourceTileGrid.getTileSize(sourceTileGrid.getMinZoom()) : undefined); + sourceTileGrid ? sourceTileGrid.getTileSize(sourceTileGrid.getMinZoom()) : undefined); } return tileGrid; }; @@ -162,7 +162,7 @@ VectorTileSource.prototype.getTilePixelRatio = function(pixelRatio) { * @inheritDoc */ VectorTileSource.prototype.getTilePixelSize = function(z, pixelRatio, projection) { - var tileSize = _ol_size_.toSize(this.getTileGridForProjection(projection).getTileSize(z)); + const tileSize = _ol_size_.toSize(this.getTileGridForProjection(projection).getTileSize(z)); return [Math.round(tileSize[0] * pixelRatio), Math.round(tileSize[1] * pixelRatio)]; }; export default VectorTileSource; diff --git a/src/ol/source/WMTS.js b/src/ol/source/WMTS.js index 82455ca207..125201b51b 100644 --- a/src/ol/source/WMTS.js +++ b/src/ol/source/WMTS.js @@ -21,7 +21,7 @@ import _ol_uri_ from '../uri.js'; * @param {olx.source.WMTSOptions} options WMTS options. * @api */ -var WMTS = function(options) { +const WMTS = function(options) { // TODO: add support for TileMatrixLimits @@ -61,7 +61,7 @@ var WMTS = function(options) { */ this.style_ = options.style; - var urls = options.urls; + let urls = options.urls; if (urls === undefined && options.url !== undefined) { urls = expandUrl(options.url); } @@ -77,15 +77,15 @@ var WMTS = function(options) { /** @type {ol.source.WMTSRequestEncoding} */ (options.requestEncoding) : WMTSRequestEncoding.KVP; - var requestEncoding = this.requestEncoding_; + const requestEncoding = this.requestEncoding_; // FIXME: should we create a default tileGrid? // we could issue a getCapabilities xhr to retrieve missing configuration - var tileGrid = options.tileGrid; + const tileGrid = options.tileGrid; // context property names are lower case to allow for a case insensitive // replacement as some services use different naming conventions - var context = { + const context = { 'layer': this.layer_, 'style': this.style_, 'tilematrixset': this.matrixSet_ @@ -100,7 +100,7 @@ var WMTS = function(options) { }); } - var dimensions = this.dimensions_; + const dimensions = this.dimensions_; /** * @param {string} template Template. @@ -130,13 +130,13 @@ var WMTS = function(options) { if (!tileCoord) { return undefined; } else { - var localContext = { + const localContext = { 'TileMatrix': tileGrid.getMatrixId(tileCoord[0]), 'TileCol': tileCoord[1], 'TileRow': -tileCoord[2] - 1 }; _ol_obj_.assign(localContext, dimensions); - var url = template; + let url = template; if (requestEncoding == WMTSRequestEncoding.KVP) { url = _ol_uri_.appendParams(url, localContext); } else { @@ -150,7 +150,7 @@ var WMTS = function(options) { ); }; - var tileUrlFunction = (urls && urls.length > 0) ? + const tileUrlFunction = (urls && urls.length > 0) ? createFromTileUrlFunctions(urls.map(this.createFromWMTSTemplate_)) : nullTileUrlFunction; TileImage.call(this, { @@ -182,7 +182,7 @@ inherits(WMTS, TileImage); */ WMTS.prototype.setUrls = function(urls) { this.urls = urls; - var key = urls.join('\n'); + const key = urls.join('\n'); this.setTileUrlFunction(this.fixedTileUrlFunction ? this.fixedTileUrlFunction.bind(this) : createFromTileUrlFunctions(urls.map(this.createFromWMTSTemplate_.bind(this))), key); @@ -265,9 +265,9 @@ WMTS.prototype.getVersion = function() { * @return {string} The key for the current dimensions. */ WMTS.prototype.getKeyForDimensions_ = function() { - var i = 0; - var res = []; - for (var key in this.dimensions_) { + let i = 0; + const res = []; + for (const key in this.dimensions_) { res[i++] = key + '-' + this.dimensions_[key]; } return res.join('/'); @@ -310,37 +310,37 @@ WMTS.prototype.updateDimensions = function(dimensions) { * @api */ WMTS.optionsFromCapabilities = function(wmtsCap, config) { - var layers = wmtsCap['Contents']['Layer']; - var l = find(layers, function(elt, index, array) { + const layers = wmtsCap['Contents']['Layer']; + const l = find(layers, function(elt, index, array) { return elt['Identifier'] == config['layer']; }); if (l === null) { return null; } - var tileMatrixSets = wmtsCap['Contents']['TileMatrixSet']; - var idx, matrixSet, matrixLimits; + const tileMatrixSets = wmtsCap['Contents']['TileMatrixSet']; + let idx; if (l['TileMatrixSetLink'].length > 1) { if ('projection' in config) { idx = findIndex(l['TileMatrixSetLink'], - function(elt, index, array) { - var tileMatrixSet = find(tileMatrixSets, function(el) { - return el['Identifier'] == elt['TileMatrixSet']; - }); - var supportedCRS = tileMatrixSet['SupportedCRS']; - var proj1 = getProjection(supportedCRS.replace(/urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/, '$1:$3')) || - getProjection(supportedCRS); - var proj2 = getProjection(config['projection']); - if (proj1 && proj2) { - return equivalent(proj1, proj2); - } else { - return supportedCRS == config['projection']; - } + function(elt, index, array) { + const tileMatrixSet = find(tileMatrixSets, function(el) { + return el['Identifier'] == elt['TileMatrixSet']; }); + const supportedCRS = tileMatrixSet['SupportedCRS']; + const proj1 = getProjection(supportedCRS.replace(/urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/, '$1:$3')) || + getProjection(supportedCRS); + const proj2 = getProjection(config['projection']); + if (proj1 && proj2) { + return equivalent(proj1, proj2); + } else { + return supportedCRS == config['projection']; + } + }); } else { idx = findIndex(l['TileMatrixSetLink'], - function(elt, index, array) { - return elt['TileMatrixSet'] == config['matrixSet']; - }); + function(elt, index, array) { + return elt['TileMatrixSet'] == config['matrixSet']; + }); } } else { idx = 0; @@ -348,12 +348,12 @@ WMTS.optionsFromCapabilities = function(wmtsCap, config) { if (idx < 0) { idx = 0; } - matrixSet = /** @type {string} */ + const matrixSet = /** @type {string} */ (l['TileMatrixSetLink'][idx]['TileMatrixSet']); - matrixLimits = /** @type {Array.} */ + const matrixLimits = /** @type {Array.} */ (l['TileMatrixSetLink'][idx]['TileMatrixSetLimits']); - var format = /** @type {string} */ (l['Format'][0]); + let format = /** @type {string} */ (l['Format'][0]); if ('format' in config) { format = config['format']; } @@ -367,13 +367,13 @@ WMTS.optionsFromCapabilities = function(wmtsCap, config) { if (idx < 0) { idx = 0; } - var style = /** @type {string} */ (l['Style'][idx]['Identifier']); + const style = /** @type {string} */ (l['Style'][idx]['Identifier']); - var dimensions = {}; + const dimensions = {}; if ('Dimension' in l) { l['Dimension'].forEach(function(elt, index, array) { - var key = elt['Identifier']; - var value = elt['Default']; + const key = elt['Identifier']; + let value = elt['Default']; if (value === undefined) { value = elt['Value'][0]; } @@ -381,19 +381,19 @@ WMTS.optionsFromCapabilities = function(wmtsCap, config) { }); } - var matrixSets = wmtsCap['Contents']['TileMatrixSet']; - var matrixSetObj = find(matrixSets, function(elt, index, array) { + const matrixSets = wmtsCap['Contents']['TileMatrixSet']; + const matrixSetObj = find(matrixSets, function(elt, index, array) { return elt['Identifier'] == matrixSet; }); - var projection; - var code = matrixSetObj['SupportedCRS']; + let projection; + const code = matrixSetObj['SupportedCRS']; if (code) { projection = getProjection(code.replace(/urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/, '$1:$3')) || getProjection(code); } if ('projection' in config) { - var projConfig = getProjection(config['projection']); + const projConfig = getProjection(config['projection']); if (projConfig) { if (!projection || equivalent(projConfig, projection)) { projection = projConfig; @@ -401,15 +401,15 @@ WMTS.optionsFromCapabilities = function(wmtsCap, config) { } } - var wgs84BoundingBox = l['WGS84BoundingBox']; - var extent, wrapX; + const wgs84BoundingBox = l['WGS84BoundingBox']; + let extent, wrapX; if (wgs84BoundingBox !== undefined) { - var wgs84ProjectionExtent = getProjection('EPSG:4326').getExtent(); + const wgs84ProjectionExtent = getProjection('EPSG:4326').getExtent(); wrapX = (wgs84BoundingBox[0] == wgs84ProjectionExtent[0] && wgs84BoundingBox[2] == wgs84ProjectionExtent[2]); extent = transformExtent( - wgs84BoundingBox, 'EPSG:4326', projection); - var projectionExtent = projection.getExtent(); + wgs84BoundingBox, 'EPSG:4326', projection); + const projectionExtent = projection.getExtent(); if (projectionExtent) { // If possible, do a sanity check on the extent - it should never be // bigger than the validity extent of the projection of a matrix set. @@ -419,22 +419,22 @@ WMTS.optionsFromCapabilities = function(wmtsCap, config) { } } - var tileGrid = createFromCapabilitiesMatrixSet(matrixSetObj, extent, matrixLimits); + const tileGrid = createFromCapabilitiesMatrixSet(matrixSetObj, extent, matrixLimits); /** @type {!Array.} */ - var urls = []; - var requestEncoding = config['requestEncoding']; + const urls = []; + let requestEncoding = config['requestEncoding']; requestEncoding = requestEncoding !== undefined ? requestEncoding : ''; if ('OperationsMetadata' in wmtsCap && 'GetTile' in wmtsCap['OperationsMetadata']) { - var gets = wmtsCap['OperationsMetadata']['GetTile']['DCP']['HTTP']['Get']; + const gets = wmtsCap['OperationsMetadata']['GetTile']['DCP']['HTTP']['Get']; - for (var i = 0, ii = gets.length; i < ii; ++i) { + for (let i = 0, ii = gets.length; i < ii; ++i) { if (gets[i]['Constraint']) { - var constraint = find(gets[i]['Constraint'], function(element) { + const constraint = find(gets[i]['Constraint'], function(element) { return element['name'] == 'GetEncoding'; }); - var encodings = constraint['AllowedValues']['Value']; + const encodings = constraint['AllowedValues']['Value']; if (requestEncoding === '') { // requestEncoding not provided, use the first encoding from the list diff --git a/src/ol/source/XYZ.js b/src/ol/source/XYZ.js index 98a41fb560..439538da0b 100644 --- a/src/ol/source/XYZ.js +++ b/src/ol/source/XYZ.js @@ -27,12 +27,12 @@ import _ol_tilegrid_ from '../tilegrid.js'; * @param {olx.source.XYZOptions=} opt_options XYZ options. * @api */ -var XYZ = function(opt_options) { - var options = opt_options || {}; - var projection = options.projection !== undefined ? +const XYZ = function(opt_options) { + const options = opt_options || {}; + const projection = options.projection !== undefined ? options.projection : 'EPSG:3857'; - var tileGrid = options.tileGrid !== undefined ? options.tileGrid : + const tileGrid = options.tileGrid !== undefined ? options.tileGrid : _ol_tilegrid_.createXYZ({ extent: _ol_tilegrid_.extentFromProjection(projection), maxZoom: options.maxZoom, diff --git a/src/ol/source/Zoomify.js b/src/ol/source/Zoomify.js index ac4dd05494..ed37d45c2a 100644 --- a/src/ol/source/Zoomify.js +++ b/src/ol/source/Zoomify.js @@ -23,21 +23,21 @@ import TileGrid from '../tilegrid/TileGrid.js'; * @param {olx.source.ZoomifyOptions=} opt_options Options. * @api */ -var Zoomify = function(opt_options) { +const Zoomify = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; - var size = options.size; - var tierSizeCalculation = options.tierSizeCalculation !== undefined ? + const size = options.size; + const tierSizeCalculation = options.tierSizeCalculation !== undefined ? options.tierSizeCalculation : Zoomify.TierSizeCalculation_.DEFAULT; - var imageWidth = size[0]; - var imageHeight = size[1]; - var extent = options.extent || [0, -size[1], size[0], 0]; - var tierSizeInTiles = []; - var tileSize = options.tileSize || DEFAULT_TILE_SIZE; - var tileSizeForTierSizeCalculation = tileSize; + const imageWidth = size[0]; + const imageHeight = size[1]; + const extent = options.extent || [0, -size[1], size[0], 0]; + const tierSizeInTiles = []; + const tileSize = options.tileSize || DEFAULT_TILE_SIZE; + let tileSizeForTierSizeCalculation = tileSize; switch (tierSizeCalculation) { case Zoomify.TierSizeCalculation_.DEFAULT: @@ -50,8 +50,8 @@ var Zoomify = function(opt_options) { } break; case Zoomify.TierSizeCalculation_.TRUNCATED: - var width = imageWidth; - var height = imageHeight; + let width = imageWidth; + let height = imageHeight; while (width > tileSizeForTierSizeCalculation || height > tileSizeForTierSizeCalculation) { tierSizeInTiles.push([ Math.ceil(width / tileSizeForTierSizeCalculation), @@ -69,30 +69,30 @@ var Zoomify = function(opt_options) { tierSizeInTiles.push([1, 1]); tierSizeInTiles.reverse(); - var resolutions = [1]; - var tileCountUpToTier = [0]; - var i, ii; + const resolutions = [1]; + const tileCountUpToTier = [0]; + let i, ii; for (i = 1, ii = tierSizeInTiles.length; i < ii; i++) { resolutions.push(1 << i); tileCountUpToTier.push( - tierSizeInTiles[i - 1][0] * tierSizeInTiles[i - 1][1] + + tierSizeInTiles[i - 1][0] * tierSizeInTiles[i - 1][1] + tileCountUpToTier[i - 1] ); } resolutions.reverse(); - var tileGrid = new TileGrid({ + const tileGrid = new TileGrid({ tileSize: tileSize, extent: extent, origin: getTopLeft(extent), resolutions: resolutions }); - var url = options.url; + let url = options.url; if (url && url.indexOf('{TileGroup}') == -1 && url.indexOf('{tileIndex}') == -1) { url += '{TileGroup}/{z}-{x}-{y}.jpg'; } - var urls = expandUrl(url); + const urls = expandUrl(url); /** * @param {string} template Template. @@ -111,15 +111,15 @@ var Zoomify = function(opt_options) { if (!tileCoord) { return undefined; } else { - var tileCoordZ = tileCoord[0]; - var tileCoordX = tileCoord[1]; - var tileCoordY = -tileCoord[2] - 1; - var tileIndex = + const tileCoordZ = tileCoord[0]; + const tileCoordX = tileCoord[1]; + const tileCoordY = -tileCoord[2] - 1; + const tileIndex = tileCoordX + tileCoordY * tierSizeInTiles[tileCoordZ][0]; - var tileSize = tileGrid.getTileSize(tileCoordZ); - var tileGroup = ((tileIndex + tileCountUpToTier[tileCoordZ]) / tileSize) | 0; - var localContext = { + const tileSize = tileGrid.getTileSize(tileCoordZ); + const tileGroup = ((tileIndex + tileCountUpToTier[tileCoordZ]) / tileSize) | 0; + const localContext = { 'z': tileCoordZ, 'x': tileCoordX, 'y': tileCoordY, @@ -133,9 +133,9 @@ var Zoomify = function(opt_options) { }); } - var tileUrlFunction = createFromTileUrlFunctions(urls.map(createFromTemplate)); + const tileUrlFunction = createFromTileUrlFunctions(urls.map(createFromTemplate)); - var ZoomifyTileClass = Zoomify.Tile_.bind(null, tileGrid); + const ZoomifyTileClass = Zoomify.Tile_.bind(null, tileGrid); TileImage.call(this, { attributions: options.attributions, @@ -166,7 +166,7 @@ inherits(Zoomify, TileImage); * @private */ Zoomify.Tile_ = function( - tileGrid, tileCoord, state, src, crossOrigin, tileLoadFunction, opt_options) { + tileGrid, tileCoord, state, src, crossOrigin, tileLoadFunction, opt_options) { ImageTile.call(this, tileCoord, state, src, crossOrigin, tileLoadFunction, opt_options); @@ -192,14 +192,14 @@ Zoomify.Tile_.prototype.getImage = function() { if (this.zoomifyImage_) { return this.zoomifyImage_; } - var image = ImageTile.prototype.getImage.call(this); + const image = ImageTile.prototype.getImage.call(this); if (this.state == TileState.LOADED) { - var tileSize = this.tileSize_; + const tileSize = this.tileSize_; if (image.width == tileSize[0] && image.height == tileSize[1]) { this.zoomifyImage_ = image; return image; } else { - var context = createCanvasContext2D(tileSize[0], tileSize[1]); + const context = createCanvasContext2D(tileSize[0], tileSize[1]); context.drawImage(image, 0, 0); this.zoomifyImage_ = context.canvas; return context.canvas; diff --git a/src/ol/source/common.js b/src/ol/source/common.js index a20bbd8c85..373726a379 100644 --- a/src/ol/source/common.js +++ b/src/ol/source/common.js @@ -1,4 +1,4 @@ /** * @type {string} Default WMS version. */ -export var DEFAULT_WMS_VERSION = '1.3.0'; +export const DEFAULT_WMS_VERSION = '1.3.0'; diff --git a/src/ol/sphere.js b/src/ol/sphere.js index 538cf256e2..fcb923bba2 100644 --- a/src/ol/sphere.js +++ b/src/ol/sphere.js @@ -18,7 +18,7 @@ import GeometryType from './geom/GeometryType.js'; * @typedef {{projection: (ol.ProjectionLike|undefined), * radius: (number|undefined)}} */ -export var SphereMetricOptions; +export let SphereMetricOptions; /** @@ -26,7 +26,7 @@ export var SphereMetricOptions; * https://en.wikipedia.org/wiki/Earth_radius#Mean_radius * @type {number} */ -export var DEFAULT_RADIUS = 6371008.8; +export const DEFAULT_RADIUS = 6371008.8; /** @@ -39,12 +39,12 @@ export var DEFAULT_RADIUS = 6371008.8; * @api */ export function getDistance(c1, c2, opt_radius) { - var radius = opt_radius || DEFAULT_RADIUS; - var lat1 = toRadians(c1[1]); - var lat2 = toRadians(c2[1]); - var deltaLatBy2 = (lat2 - lat1) / 2; - var deltaLonBy2 = toRadians(c2[0] - c1[0]) / 2; - var a = Math.sin(deltaLatBy2) * Math.sin(deltaLatBy2) + + const radius = opt_radius || DEFAULT_RADIUS; + const lat1 = toRadians(c1[1]); + const lat2 = toRadians(c2[1]); + const deltaLatBy2 = (lat2 - lat1) / 2; + const deltaLonBy2 = toRadians(c2[0] - c1[0]) / 2; + const a = Math.sin(deltaLatBy2) * Math.sin(deltaLatBy2) + Math.sin(deltaLonBy2) * Math.sin(deltaLonBy2) * Math.cos(lat1) * Math.cos(lat2); return 2 * radius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); @@ -58,8 +58,8 @@ export function getDistance(c1, c2, opt_radius) { * @return {number} The length (in meters). */ function getLengthInternal(coordinates, radius) { - var length = 0; - for (var i = 0, ii = coordinates.length; i < ii - 1; ++i) { + let length = 0; + for (let i = 0, ii = coordinates.length; i < ii - 1; ++i) { length += getDistance(coordinates[i], coordinates[i + 1], radius); } return length; @@ -84,15 +84,15 @@ function getLengthInternal(coordinates, radius) { * @api */ export function getLength(geometry, opt_options) { - var options = opt_options || {}; - var radius = options.radius || DEFAULT_RADIUS; - var projection = options.projection || 'EPSG:3857'; - var type = geometry.getType(); + const options = opt_options || {}; + const radius = options.radius || DEFAULT_RADIUS; + const projection = options.projection || 'EPSG:3857'; + const type = geometry.getType(); if (type !== GeometryType.GEOMETRY_COLLECTION) { geometry = geometry.clone().transform(projection, 'EPSG:4326'); } - var length = 0; - var coordinates, coords, i, ii, j, jj; + let length = 0; + let coordinates, coords, i, ii, j, jj; switch (type) { case GeometryType.POINT: case GeometryType.MULTI_POINT: { @@ -123,7 +123,7 @@ export function getLength(geometry, opt_options) { break; } case GeometryType.GEOMETRY_COLLECTION: { - var geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries(); + const geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries(); for (i = 0, ii = geometries.length; i < ii; ++i) { length += getLength(geometries[i], opt_options); } @@ -152,11 +152,13 @@ export function getLength(geometry, opt_options) { * @return {number} Area (in square meters). */ function getAreaInternal(coordinates, radius) { - var area = 0, len = coordinates.length; - var x1 = coordinates[len - 1][0]; - var y1 = coordinates[len - 1][1]; - for (var i = 0; i < len; i++) { - var x2 = coordinates[i][0], y2 = coordinates[i][1]; + let area = 0; + const len = coordinates.length; + let x1 = coordinates[len - 1][0]; + let y1 = coordinates[len - 1][1]; + for (let i = 0; i < len; i++) { + const x2 = coordinates[i][0]; + const y2 = coordinates[i][1]; area += toRadians(x2 - x1) * (2 + Math.sin(toRadians(y1)) + Math.sin(toRadians(y2))); @@ -178,15 +180,15 @@ function getAreaInternal(coordinates, radius) { * @api */ export function getArea(geometry, opt_options) { - var options = opt_options || {}; - var radius = options.radius || DEFAULT_RADIUS; - var projection = options.projection || 'EPSG:3857'; - var type = geometry.getType(); + const options = opt_options || {}; + const radius = options.radius || DEFAULT_RADIUS; + const projection = options.projection || 'EPSG:3857'; + const type = geometry.getType(); if (type !== GeometryType.GEOMETRY_COLLECTION) { geometry = geometry.clone().transform(projection, 'EPSG:4326'); } - var area = 0; - var coordinates, coords, i, ii, j, jj; + let area = 0; + let coordinates, coords, i, ii, j, jj; switch (type) { case GeometryType.POINT: case GeometryType.MULTI_POINT: @@ -215,7 +217,7 @@ export function getArea(geometry, opt_options) { break; } case GeometryType.GEOMETRY_COLLECTION: { - var geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries(); + const geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries(); for (i = 0, ii = geometries.length; i < ii; ++i) { area += getArea(geometries[i], opt_options); } @@ -241,15 +243,15 @@ export function getArea(geometry, opt_options) { * @return {ol.Coordinate} The target point. */ export function offset(c1, distance, bearing, opt_radius) { - var radius = opt_radius || DEFAULT_RADIUS; - var lat1 = toRadians(c1[1]); - var lon1 = toRadians(c1[0]); - var dByR = distance / radius; - var lat = Math.asin( - Math.sin(lat1) * Math.cos(dByR) + + const radius = opt_radius || DEFAULT_RADIUS; + const lat1 = toRadians(c1[1]); + const lon1 = toRadians(c1[0]); + const dByR = distance / radius; + const lat = Math.asin( + Math.sin(lat1) * Math.cos(dByR) + Math.cos(lat1) * Math.sin(dByR) * Math.cos(bearing)); - var lon = lon1 + Math.atan2( - Math.sin(bearing) * Math.sin(dByR) * Math.cos(lat1), - Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat)); + const lon = lon1 + Math.atan2( + Math.sin(bearing) * Math.sin(dByR) * Math.cos(lat1), + Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat)); return [toDegrees(lon), toDegrees(lat)]; } diff --git a/src/ol/string.js b/src/ol/string.js index b57680b92d..5b84153d4a 100644 --- a/src/ol/string.js +++ b/src/ol/string.js @@ -1,7 +1,7 @@ /** * @module ol/string */ -var _ol_string_ = {}; +const _ol_string_ = {}; /** * @param {number} number Number to be formatted @@ -10,8 +10,8 @@ var _ol_string_ = {}; * @returns {string} Formatted string */ _ol_string_.padNumber = function(number, width, opt_precision) { - var numberString = opt_precision !== undefined ? number.toFixed(opt_precision) : '' + number; - var decimal = numberString.indexOf('.'); + const numberString = opt_precision !== undefined ? number.toFixed(opt_precision) : '' + number; + let decimal = numberString.indexOf('.'); decimal = decimal === -1 ? numberString.length : decimal; return decimal > width ? numberString : new Array(1 + width - decimal).join('0') + numberString; }; @@ -23,12 +23,12 @@ _ol_string_.padNumber = function(number, width, opt_precision) { * @returns {number} Value */ _ol_string_.compareVersions = function(v1, v2) { - var s1 = ('' + v1).split('.'); - var s2 = ('' + v2).split('.'); + const s1 = ('' + v1).split('.'); + const s2 = ('' + v2).split('.'); - for (var i = 0; i < Math.max(s1.length, s2.length); i++) { - var n1 = parseInt(s1[i] || '0', 10); - var n2 = parseInt(s2[i] || '0', 10); + for (let i = 0; i < Math.max(s1.length, s2.length); i++) { + const n1 = parseInt(s1[i] || '0', 10); + const n2 = parseInt(s2[i] || '0', 10); if (n1 > n2) { return 1; diff --git a/src/ol/structs/LRUCache.js b/src/ol/structs/LRUCache.js index d3b7b2eae2..b9dcf321ac 100644 --- a/src/ol/structs/LRUCache.js +++ b/src/ol/structs/LRUCache.js @@ -17,7 +17,7 @@ import EventType from '../events/EventType.js'; * @template T * @param {number=} opt_highWaterMark High water mark. */ -var LRUCache = function(opt_highWaterMark) { +const LRUCache = function(opt_highWaterMark) { EventTarget.call(this); @@ -93,7 +93,7 @@ LRUCache.prototype.containsKey = function(key) { * @template S */ LRUCache.prototype.forEach = function(f, opt_this) { - var entry = this.oldest_; + let entry = this.oldest_; while (entry) { f.call(opt_this, entry.value_, entry.key_, this); entry = entry.newer; @@ -106,9 +106,9 @@ LRUCache.prototype.forEach = function(f, opt_this) { * @return {T} Value. */ LRUCache.prototype.get = function(key) { - var entry = this.entries_[key]; + const entry = this.entries_[key]; assert(entry !== undefined, - 15); // Tried to get a value for a key that does not exist in the cache + 15); // Tried to get a value for a key that does not exist in the cache if (entry === this.newest_) { return entry.value_; } else if (entry === this.oldest_) { @@ -132,7 +132,7 @@ LRUCache.prototype.get = function(key) { * @return {T} The removed entry. */ LRUCache.prototype.remove = function(key) { - var entry = this.entries_[key]; + const entry = this.entries_[key]; assert(entry !== undefined, 15); // Tried to get a value for a key that does not exist in the cache if (entry === this.newest_) { this.newest_ = /** @type {ol.LRUCacheEntry} */ (entry.older); @@ -166,9 +166,9 @@ LRUCache.prototype.getCount = function() { * @return {Array.} Keys. */ LRUCache.prototype.getKeys = function() { - var keys = new Array(this.count_); - var i = 0; - var entry; + const keys = new Array(this.count_); + let i = 0; + let entry; for (entry = this.newest_; entry; entry = entry.older) { keys[i++] = entry.key_; } @@ -180,9 +180,9 @@ LRUCache.prototype.getKeys = function() { * @return {Array.} Values. */ LRUCache.prototype.getValues = function() { - var values = new Array(this.count_); - var i = 0; - var entry; + const values = new Array(this.count_); + let i = 0; + let entry; for (entry = this.newest_; entry; entry = entry.older) { values[i++] = entry.value_; } @@ -219,7 +219,7 @@ LRUCache.prototype.peekFirstKey = function() { * @return {T} value Value. */ LRUCache.prototype.pop = function() { - var entry = this.oldest_; + const entry = this.oldest_; delete this.entries_[entry.key_]; if (entry.newer) { entry.newer.older = null; @@ -249,8 +249,8 @@ LRUCache.prototype.replace = function(key, value) { */ LRUCache.prototype.set = function(key, value) { assert(!(key in this.entries_), - 16); // Tried to set a value for a key that is used already - var entry = /** @type {ol.LRUCacheEntry} */ ({ + 16); // Tried to set a value for a key that is used already + const entry = /** @type {ol.LRUCacheEntry} */ ({ key_: key, newer: null, older: this.newest_, diff --git a/src/ol/structs/LinkedList.js b/src/ol/structs/LinkedList.js index 1152d0ad0d..389df5d059 100644 --- a/src/ol/structs/LinkedList.js +++ b/src/ol/structs/LinkedList.js @@ -10,7 +10,7 @@ * @param {boolean=} opt_circular The last item is connected to the first one, * and the first item to the last one. Default is true. */ -var LinkedList = function(opt_circular) { +const LinkedList = function(opt_circular) { /** * @private @@ -51,13 +51,13 @@ var LinkedList = function(opt_circular) { LinkedList.prototype.insertItem = function(data) { /** @type {ol.LinkedListItem} */ - var item = { + const item = { prev: undefined, next: undefined, data: data }; - var head = this.head_; + const head = this.head_; //Initialize the list. if (!head) { @@ -69,7 +69,7 @@ LinkedList.prototype.insertItem = function(data) { } } else { //Link the new item to the adjacent ones. - var next = head.next; + const next = head.next; item.prev = head; item.next = next; head.next = item; @@ -90,10 +90,10 @@ LinkedList.prototype.insertItem = function(data) { * if possible. */ LinkedList.prototype.removeItem = function() { - var head = this.head_; + const head = this.head_; if (head) { - var next = head.next; - var prev = head.prev; + const next = head.next; + const prev = head.prev; if (next) { next.prev = prev; } @@ -221,7 +221,7 @@ LinkedList.prototype.setFirstItem = function() { LinkedList.prototype.concat = function(list) { if (list.head_) { if (this.head_) { - var end = this.head_.next; + const end = this.head_.next; this.head_.next = list.first_; list.first_.prev = this.head_; end.prev = list.last_; diff --git a/src/ol/structs/PriorityQueue.js b/src/ol/structs/PriorityQueue.js index 8829c3cbc0..c876855270 100644 --- a/src/ol/structs/PriorityQueue.js +++ b/src/ol/structs/PriorityQueue.js @@ -19,7 +19,7 @@ import _ol_obj_ from '../obj.js'; * @struct * @template T */ -var PriorityQueue = function(priorityFunction, keyFunction) { +const PriorityQueue = function(priorityFunction, keyFunction) { /** * @type {function(T): number} @@ -76,9 +76,9 @@ PriorityQueue.prototype.clear = function() { * @return {T} Element. */ PriorityQueue.prototype.dequeue = function() { - var elements = this.elements_; - var priorities = this.priorities_; - var element = elements[0]; + const elements = this.elements_; + const priorities = this.priorities_; + const element = elements[0]; if (elements.length == 1) { elements.length = 0; priorities.length = 0; @@ -87,7 +87,7 @@ PriorityQueue.prototype.dequeue = function() { priorities[0] = priorities.pop(); this.siftUp_(0); } - var elementKey = this.keyFunction_(element); + const elementKey = this.keyFunction_(element); delete this.queuedElements_[elementKey]; return element; }; @@ -100,8 +100,8 @@ PriorityQueue.prototype.dequeue = function() { */ PriorityQueue.prototype.enqueue = function(element) { assert(!(this.keyFunction_(element) in this.queuedElements_), - 31); // Tried to enqueue an `element` that was already added to the queue - var priority = this.priorityFunction_(element); + 31); // Tried to enqueue an `element` that was already added to the queue + const priority = this.priorityFunction_(element); if (priority != PriorityQueue.DROP) { this.elements_.push(element); this.priorities_.push(priority); @@ -159,7 +159,7 @@ PriorityQueue.prototype.getParentIndex_ = function(index) { * @private */ PriorityQueue.prototype.heapify_ = function() { - var i; + let i; for (i = (this.elements_.length >> 1) - 1; i >= 0; i--) { this.siftUp_(i); } @@ -197,18 +197,18 @@ PriorityQueue.prototype.isQueued = function(element) { * @private */ PriorityQueue.prototype.siftUp_ = function(index) { - var elements = this.elements_; - var priorities = this.priorities_; - var count = elements.length; - var element = elements[index]; - var priority = priorities[index]; - var startIndex = index; + const elements = this.elements_; + const priorities = this.priorities_; + const count = elements.length; + const element = elements[index]; + const priority = priorities[index]; + const startIndex = index; while (index < (count >> 1)) { - var lIndex = this.getLeftChildIndex_(index); - var rIndex = this.getRightChildIndex_(index); + const lIndex = this.getLeftChildIndex_(index); + const rIndex = this.getRightChildIndex_(index); - var smallerChildIndex = rIndex < count && + const smallerChildIndex = rIndex < count && priorities[rIndex] < priorities[lIndex] ? rIndex : lIndex; @@ -229,13 +229,13 @@ PriorityQueue.prototype.siftUp_ = function(index) { * @private */ PriorityQueue.prototype.siftDown_ = function(startIndex, index) { - var elements = this.elements_; - var priorities = this.priorities_; - var element = elements[index]; - var priority = priorities[index]; + const elements = this.elements_; + const priorities = this.priorities_; + const element = elements[index]; + const priority = priorities[index]; while (index > startIndex) { - var parentIndex = this.getParentIndex_(index); + const parentIndex = this.getParentIndex_(index); if (priorities[parentIndex] > priority) { elements[index] = elements[parentIndex]; priorities[index] = priorities[parentIndex]; @@ -253,12 +253,12 @@ PriorityQueue.prototype.siftDown_ = function(startIndex, index) { * FIXME empty description for jsdoc */ PriorityQueue.prototype.reprioritize = function() { - var priorityFunction = this.priorityFunction_; - var elements = this.elements_; - var priorities = this.priorities_; - var index = 0; - var n = elements.length; - var element, i, priority; + const priorityFunction = this.priorityFunction_; + const elements = this.elements_; + const priorities = this.priorities_; + let index = 0; + const n = elements.length; + let element, i, priority; for (i = 0; i < n; ++i) { element = elements[i]; priority = priorityFunction(element); diff --git a/src/ol/structs/RBush.js b/src/ol/structs/RBush.js index cd3611f9e6..5c3ea43bd0 100644 --- a/src/ol/structs/RBush.js +++ b/src/ol/structs/RBush.js @@ -15,7 +15,7 @@ import _ol_obj_ from '../obj.js'; * @struct * @template T */ -var RBush = function(opt_maxEntries) { +const RBush = function(opt_maxEntries) { /** * @private @@ -40,7 +40,7 @@ var RBush = function(opt_maxEntries) { */ RBush.prototype.insert = function(extent, value) { /** @type {ol.RBushEntry} */ - var item = { + const item = { minX: extent[0], minY: extent[1], maxX: extent[2], @@ -59,13 +59,13 @@ RBush.prototype.insert = function(extent, value) { * @param {Array.} values Values. */ RBush.prototype.load = function(extents, values) { - var items = new Array(values.length); - for (var i = 0, l = values.length; i < l; i++) { - var extent = extents[i]; - var value = values[i]; + const items = new Array(values.length); + for (let i = 0, l = values.length; i < l; i++) { + const extent = extents[i]; + const value = values[i]; /** @type {ol.RBushEntry} */ - var item = { + const item = { minX: extent[0], minY: extent[1], maxX: extent[2], @@ -85,11 +85,11 @@ RBush.prototype.load = function(extents, values) { * @return {boolean} Removed. */ RBush.prototype.remove = function(value) { - var uid = getUid(value); + const uid = getUid(value); // get the object in which the value was wrapped when adding to the // internal rbush. then use that object to do the removal. - var item = this.items_[uid]; + const item = this.items_[uid]; delete this.items_[uid]; return this.rbush_.remove(item) !== null; }; @@ -101,8 +101,8 @@ RBush.prototype.remove = function(value) { * @param {T} value Value. */ RBush.prototype.update = function(extent, value) { - var item = this.items_[getUid(value)]; - var bbox = [item.minX, item.minY, item.maxX, item.maxY]; + const item = this.items_[getUid(value)]; + const bbox = [item.minX, item.minY, item.maxX, item.maxY]; if (!equals(bbox, extent)) { this.remove(value); this.insert(extent, value); @@ -115,7 +115,7 @@ RBush.prototype.update = function(extent, value) { * @return {Array.} All. */ RBush.prototype.getAll = function() { - var items = this.rbush_.all(); + const items = this.rbush_.all(); return items.map(function(item) { return item.value; }); @@ -129,13 +129,13 @@ RBush.prototype.getAll = function() { */ RBush.prototype.getInExtent = function(extent) { /** @type {ol.RBushEntry} */ - var bbox = { + const bbox = { minX: extent[0], minY: extent[1], maxX: extent[2], maxY: extent[3] }; - var items = this.rbush_.search(bbox); + const items = this.rbush_.search(bbox); return items.map(function(item) { return item.value; }); @@ -178,8 +178,8 @@ RBush.prototype.forEachInExtent = function(extent, callback, opt_this) { * @template S */ RBush.prototype.forEach_ = function(values, callback, opt_this) { - var result; - for (var i = 0, l = values.length; i < l; i++) { + let result; + for (let i = 0, l = values.length; i < l; i++) { result = callback.call(opt_this, values[i]); if (result) { return result; @@ -212,7 +212,7 @@ RBush.prototype.clear = function() { */ RBush.prototype.getExtent = function(opt_extent) { // FIXME add getExtent() to rbush - var data = this.rbush_.data; + const data = this.rbush_.data; return createOrUpdate(data.minX, data.minY, data.maxX, data.maxY, opt_extent); }; @@ -222,7 +222,7 @@ RBush.prototype.getExtent = function(opt_extent) { */ RBush.prototype.concat = function(rbush) { this.rbush_.load(rbush.rbush_.all()); - for (var i in rbush.items_) { + for (const i in rbush.items_) { this.items_[i | 0] = rbush.items_[i | 0]; } }; diff --git a/src/ol/style.js b/src/ol/style.js index e454624e89..806387d571 100644 --- a/src/ol/style.js +++ b/src/ol/style.js @@ -7,4 +7,4 @@ import IconImageCache from './style/IconImageCache.js'; * The {@link ol.style.IconImageCache} for {@link ol.style.Icon} images. * @api */ -export var iconImageCache = new IconImageCache(); +export const iconImageCache = new IconImageCache(); diff --git a/src/ol/style/Atlas.js b/src/ol/style/Atlas.js index 7b0f802500..d07358ce60 100644 --- a/src/ol/style/Atlas.js +++ b/src/ol/style/Atlas.js @@ -20,7 +20,7 @@ import {createCanvasContext2D} from '../dom.js'; * edges overlap when being rendered). To avoid this we add a * padding around each image. */ -var Atlas = function(size, space) { +const Atlas = function(size, space) { /** * @private @@ -74,13 +74,13 @@ Atlas.prototype.get = function(id) { * @return {?ol.AtlasInfo} The position and atlas image for the entry. */ Atlas.prototype.add = function(id, width, height, renderCallback, opt_this) { - var block, i, ii; + let block, i, ii; for (i = 0, ii = this.emptyBlocks_.length; i < ii; ++i) { block = this.emptyBlocks_[i]; if (block.width >= width + this.space_ && block.height >= height + this.space_) { // we found a block that is big enough for our entry - var entry = { + const entry = { offsetX: block.x + this.space_, offsetY: block.y + this.space_, image: this.canvas_ @@ -89,7 +89,7 @@ Atlas.prototype.add = function(id, width, height, renderCallback, opt_this) { // render the image on the atlas image renderCallback.call(opt_this, this.context_, - block.x + this.space_, block.y + this.space_); + block.x + this.space_, block.y + this.space_); // split the block after the insertion, either horizontally or vertically this.split_(i, block, width + this.space_, height + this.space_); @@ -111,13 +111,13 @@ Atlas.prototype.add = function(id, width, height, renderCallback, opt_this) { * @param {number} height The height of the entry to insert. */ Atlas.prototype.split_ = function(index, block, width, height) { - var deltaWidth = block.width - width; - var deltaHeight = block.height - height; + const deltaWidth = block.width - width; + const deltaHeight = block.height - height; /** @type {ol.AtlasBlock} */ - var newBlock1; + let newBlock1; /** @type {ol.AtlasBlock} */ - var newBlock2; + let newBlock2; if (deltaWidth > deltaHeight) { // split vertically @@ -169,7 +169,7 @@ Atlas.prototype.split_ = function(index, block, width, height) { * @param {ol.AtlasBlock} newBlock2 The 2nd block to add. */ Atlas.prototype.updateBlocks_ = function(index, newBlock1, newBlock2) { - var args = [index, 1]; + const args = [index, 1]; if (newBlock1.width > 0 && newBlock1.height > 0) { args.push(newBlock1); } diff --git a/src/ol/style/AtlasManager.js b/src/ol/style/AtlasManager.js index e281735e37..7b40c260bf 100644 --- a/src/ol/style/AtlasManager.js +++ b/src/ol/style/AtlasManager.js @@ -8,12 +8,12 @@ import Atlas from '../style/Atlas.js'; /** * @type {number} The size in pixels of the first atlas image. */ -var INITIAL_ATLAS_SIZE = 256; +const INITIAL_ATLAS_SIZE = 256; /** * @type {number} The maximum size in pixels of atlas images. */ -var MAX_ATLAS_SIZE = -1; +const MAX_ATLAS_SIZE = -1; /** @@ -33,9 +33,9 @@ var MAX_ATLAS_SIZE = -1; * @api * @param {olx.style.AtlasManagerOptions=} opt_options Options. */ -var AtlasManager = function(opt_options) { +const AtlasManager = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; /** * The size in pixels of the latest atlas image. @@ -90,12 +90,12 @@ var AtlasManager = function(opt_options) { */ AtlasManager.prototype.getInfo = function(id) { /** @type {?ol.AtlasInfo} */ - var info = this.getInfo_(this.atlases_, id); + const info = this.getInfo_(this.atlases_, id); if (!info) { return null; } - var hitInfo = /** @type {ol.AtlasInfo} */ (this.getInfo_(this.hitAtlases_, id)); + const hitInfo = /** @type {ol.AtlasInfo} */ (this.getInfo_(this.hitAtlases_, id)); return this.mergeInfos_(info, hitInfo); }; @@ -109,7 +109,7 @@ AtlasManager.prototype.getInfo = function(id) { * or `null` if the entry is not part of the atlases. */ AtlasManager.prototype.getInfo_ = function(atlases, id) { - var atlas, info, i, ii; + let atlas, info, i, ii; for (i = 0, ii = atlases.length; i < ii; ++i) { atlas = atlases[i]; info = atlas.get(id); @@ -162,15 +162,15 @@ AtlasManager.prototype.mergeInfos_ = function(info, hitInfo) { * entry, or `null` if the image is too big. */ AtlasManager.prototype.add = function(id, width, height, - renderCallback, opt_renderHitCallback, opt_this) { + renderCallback, opt_renderHitCallback, opt_this) { if (width + this.space_ > this.maxSize_ || height + this.space_ > this.maxSize_) { return null; } /** @type {?ol.AtlasInfo} */ - var info = this.add_(false, - id, width, height, renderCallback, opt_this); + const info = this.add_(false, + id, width, height, renderCallback, opt_this); if (!info) { return null; } @@ -178,11 +178,11 @@ AtlasManager.prototype.add = function(id, width, height, // even if no hit-detection entry is requested, we insert a fake entry into // the hit-detection atlas, to make sure that the offset is the same for // the original image and the hit-detection image. - var renderHitCallback = opt_renderHitCallback !== undefined ? + const renderHitCallback = opt_renderHitCallback !== undefined ? opt_renderHitCallback : nullFunction; - var hitInfo = /** @type {ol.AtlasInfo} */ (this.add_(true, - id, width, height, renderHitCallback, opt_this)); + const hitInfo = /** @type {ol.AtlasInfo} */ (this.add_(true, + id, width, height, renderHitCallback, opt_this)); return this.mergeInfos_(info, hitInfo); }; @@ -202,9 +202,9 @@ AtlasManager.prototype.add = function(id, width, height, * or `null` if the image is too big. */ AtlasManager.prototype.add_ = function(isHitAtlas, id, width, height, - renderCallback, opt_this) { - var atlases = (isHitAtlas) ? this.hitAtlases_ : this.atlases_; - var atlas, info, i, ii; + renderCallback, opt_this) { + const atlases = (isHitAtlas) ? this.hitAtlases_ : this.atlases_; + let atlas, info, i, ii; for (i = 0, ii = atlases.length; i < ii; ++i) { atlas = atlases[i]; info = atlas.add(id, width, height, renderCallback, opt_this); @@ -213,7 +213,7 @@ AtlasManager.prototype.add_ = function(isHitAtlas, id, width, height, } else if (!info && i === ii - 1) { // the entry could not be added to one of the existing atlases, // create a new atlas that is twice as big and try to add to this one. - var size; + let size; if (isHitAtlas) { size = Math.min(this.currentHitSize_ * 2, this.maxSize_); this.currentHitSize_ = size; diff --git a/src/ol/style/Circle.js b/src/ol/style/Circle.js index 992e8c3390..0149a92b7f 100644 --- a/src/ol/style/Circle.js +++ b/src/ol/style/Circle.js @@ -13,9 +13,9 @@ import RegularShape from '../style/RegularShape.js'; * @extends {ol.style.RegularShape} * @api */ -var CircleStyle = function(opt_options) { +const CircleStyle = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; RegularShape.call(this, { points: Infinity, @@ -38,7 +38,7 @@ inherits(CircleStyle, RegularShape); * @api */ CircleStyle.prototype.clone = function() { - var style = new CircleStyle({ + const style = new CircleStyle({ fill: this.getFill() ? this.getFill().clone() : undefined, stroke: this.getStroke() ? this.getStroke().clone() : undefined, radius: this.getRadius(), diff --git a/src/ol/style/Fill.js b/src/ol/style/Fill.js index 30fa9d7316..edfd102109 100644 --- a/src/ol/style/Fill.js +++ b/src/ol/style/Fill.js @@ -12,9 +12,9 @@ import {asString} from '../color.js'; * @param {olx.style.FillOptions=} opt_options Options. * @api */ -var Fill = function(opt_options) { +const Fill = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; /** * @private @@ -36,7 +36,7 @@ var Fill = function(opt_options) { * @api */ Fill.prototype.clone = function() { - var color = this.getColor(); + const color = this.getColor(); return new Fill({ color: (color && color.slice) ? color.slice() : color || undefined }); diff --git a/src/ol/style/Icon.js b/src/ol/style/Icon.js index 8993a778bf..fd195e17be 100644 --- a/src/ol/style/Icon.js +++ b/src/ol/style/Icon.js @@ -21,9 +21,9 @@ import ImageStyle from '../style/Image.js'; * @extends {ol.style.Image} * @api */ -var Icon = function(opt_options) { +const Icon = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; /** * @private @@ -68,33 +68,33 @@ var Icon = function(opt_options) { /** * @type {Image|HTMLCanvasElement} */ - var image = options.img !== undefined ? options.img : null; + const image = options.img !== undefined ? options.img : null; /** * @type {ol.Size} */ - var imgSize = options.imgSize !== undefined ? options.imgSize : null; + const imgSize = options.imgSize !== undefined ? options.imgSize : null; /** * @type {string|undefined} */ - var src = options.src; + let src = options.src; assert(!(src !== undefined && image), - 4); // `image` and `src` cannot be provided at the same time + 4); // `image` and `src` cannot be provided at the same time assert(!image || (image && imgSize), - 5); // `imgSize` must be set when `image` is provided + 5); // `imgSize` must be set when `image` is provided if ((src === undefined || src.length === 0) && image) { src = image.src || getUid(image).toString(); } assert(src !== undefined && src.length > 0, - 6); // A defined and non-empty `src` or `image` must be provided + 6); // A defined and non-empty `src` or `image` must be provided /** * @type {ol.ImageState} */ - var imageState = options.src !== undefined ? + const imageState = options.src !== undefined ? ImageState.IDLE : ImageState.LOADED; /** @@ -108,7 +108,7 @@ var Icon = function(opt_options) { * @type {ol.style.IconImage} */ this.iconImage_ = IconImage.get( - image, /** @type {string} */ (src), imgSize, this.crossOrigin_, imageState, this.color_); + image, /** @type {string} */ (src), imgSize, this.crossOrigin_, imageState, this.color_); /** * @private @@ -138,28 +138,28 @@ var Icon = function(opt_options) { /** * @type {number} */ - var opacity = options.opacity !== undefined ? options.opacity : 1; + const opacity = options.opacity !== undefined ? options.opacity : 1; /** * @type {boolean} */ - var rotateWithView = options.rotateWithView !== undefined ? + const rotateWithView = options.rotateWithView !== undefined ? options.rotateWithView : false; /** * @type {number} */ - var rotation = options.rotation !== undefined ? options.rotation : 0; + const rotation = options.rotation !== undefined ? options.rotation : 0; /** * @type {number} */ - var scale = options.scale !== undefined ? options.scale : 1; + const scale = options.scale !== undefined ? options.scale : 1; /** * @type {boolean} */ - var snapToPixel = options.snapToPixel !== undefined ? + const snapToPixel = options.snapToPixel !== undefined ? options.snapToPixel : true; ImageStyle.call(this, { @@ -209,8 +209,8 @@ Icon.prototype.getAnchor = function() { if (this.normalizedAnchor_) { return this.normalizedAnchor_; } - var anchor = this.anchor_; - var size = this.getSize(); + let anchor = this.anchor_; + const size = this.getSize(); if (this.anchorXUnits_ == IconAnchorUnits.FRACTION || this.anchorYUnits_ == IconAnchorUnits.FRACTION) { if (!size) { @@ -308,11 +308,11 @@ Icon.prototype.getOrigin = function() { if (this.origin_) { return this.origin_; } - var offset = this.offset_; + let offset = this.offset_; if (this.offsetOrigin_ != IconOrigin.TOP_LEFT) { - var size = this.getSize(); - var iconImageSize = this.iconImage_.getSize(); + const size = this.getSize(); + const iconImageSize = this.iconImage_.getSize(); if (!size || !iconImageSize) { return null; } @@ -355,7 +355,7 @@ Icon.prototype.getSize = function() { */ Icon.prototype.listenImageChange = function(listener, thisArg) { return _ol_events_.listen(this.iconImage_, EventType.CHANGE, - listener, thisArg); + listener, thisArg); }; @@ -377,6 +377,6 @@ Icon.prototype.load = function() { */ Icon.prototype.unlistenImageChange = function(listener, thisArg) { _ol_events_.unlisten(this.iconImage_, EventType.CHANGE, - listener, thisArg); + listener, thisArg); }; export default Icon; diff --git a/src/ol/style/IconImage.js b/src/ol/style/IconImage.js index fb893e00a3..372cff76ae 100644 --- a/src/ol/style/IconImage.js +++ b/src/ol/style/IconImage.js @@ -19,8 +19,8 @@ import {iconImageCache} from '../style.js'; * @param {ol.Color} color Color. * @extends {ol.events.EventTarget} */ -var IconImage = function(image, src, size, crossOrigin, imageState, - color) { +const IconImage = function(image, src, size, crossOrigin, imageState, + color) { EventTarget.call(this); @@ -102,11 +102,11 @@ inherits(IconImage, EventTarget); * @return {ol.style.IconImage} Icon image. */ IconImage.get = function(image, src, size, crossOrigin, imageState, - color) { - var iconImage = iconImageCache.get(src, crossOrigin, color); + color) { + let iconImage = iconImageCache.get(src, crossOrigin, color); if (!iconImage) { iconImage = new IconImage( - image, src, size, crossOrigin, imageState, color); + image, src, size, crossOrigin, imageState, color); iconImageCache.set(src, crossOrigin, color, iconImage); } return iconImage; @@ -117,7 +117,7 @@ IconImage.get = function(image, src, size, crossOrigin, imageState, * @private */ IconImage.prototype.determineTainting_ = function() { - var context = createCanvasContext2D(1, 1); + const context = createCanvasContext2D(1, 1); try { context.drawImage(this.image_, 0, 0); context.getImageData(0, 0, 1, 1); @@ -186,9 +186,9 @@ IconImage.prototype.getImageState = function() { IconImage.prototype.getHitDetectionImage = function(pixelRatio) { if (!this.hitDetectionImage_) { if (this.tainting_) { - var width = this.size_[0]; - var height = this.size_[1]; - var context = createCanvasContext2D(width, height); + const width = this.size_[0]; + const height = this.size_[1]; + const context = createCanvasContext2D(width, height); context.fillRect(0, 0, width, height); this.hitDetectionImage_ = context.canvas; } else { @@ -223,9 +223,9 @@ IconImage.prototype.load = function() { this.imageState_ = ImageState.LOADING; this.imageListenerKeys_ = [ _ol_events_.listenOnce(this.image_, EventType.ERROR, - this.handleImageError_, this), + this.handleImageError_, this), _ol_events_.listenOnce(this.image_, EventType.LOAD, - this.handleImageLoad_, this) + this.handleImageLoad_, this) ]; try { this.image_.src = this.src_; @@ -247,16 +247,16 @@ IconImage.prototype.replaceColor_ = function() { this.canvas_.width = this.image_.width; this.canvas_.height = this.image_.height; - var ctx = this.canvas_.getContext('2d'); + const ctx = this.canvas_.getContext('2d'); ctx.drawImage(this.image_, 0, 0); - var imgData = ctx.getImageData(0, 0, this.image_.width, this.image_.height); - var data = imgData.data; - var r = this.color_[0] / 255.0; - var g = this.color_[1] / 255.0; - var b = this.color_[2] / 255.0; + const imgData = ctx.getImageData(0, 0, this.image_.width, this.image_.height); + const data = imgData.data; + const r = this.color_[0] / 255.0; + const g = this.color_[1] / 255.0; + const b = this.color_[2] / 255.0; - for (var i = 0, ii = data.length; i < ii; i += 4) { + for (let i = 0, ii = data.length; i < ii; i += 4) { data[i] *= r; data[i + 1] *= g; data[i + 2] *= b; diff --git a/src/ol/style/IconImageCache.js b/src/ol/style/IconImageCache.js index 7257247a1d..74ce90f17f 100644 --- a/src/ol/style/IconImageCache.js +++ b/src/ol/style/IconImageCache.js @@ -7,7 +7,7 @@ import {asString} from '../color.js'; * Singleton class. Available through {@link ol.style.iconImageCache}. * @constructor */ -var IconImageCache = function() { +const IconImageCache = function() { /** * @type {Object.} @@ -36,7 +36,7 @@ var IconImageCache = function() { * @return {string} Cache key. */ function getKey(src, crossOrigin, color) { - var colorString = color ? asString(color) : 'null'; + const colorString = color ? asString(color) : 'null'; return crossOrigin + ':' + src + ':' + colorString; } @@ -55,8 +55,8 @@ IconImageCache.prototype.clear = function() { */ IconImageCache.prototype.expire = function() { if (this.cacheSize_ > this.maxCacheSize_) { - var i = 0; - var key, iconImage; + let i = 0; + let key, iconImage; for (key in this.cache_) { iconImage = this.cache_[key]; if ((i++ & 3) === 0 && !iconImage.hasListener()) { @@ -75,7 +75,7 @@ IconImageCache.prototype.expire = function() { * @return {ol.style.IconImage} Icon image. */ IconImageCache.prototype.get = function(src, crossOrigin, color) { - var key = getKey(src, crossOrigin, color); + const key = getKey(src, crossOrigin, color); return key in this.cache_ ? this.cache_[key] : null; }; @@ -87,7 +87,7 @@ IconImageCache.prototype.get = function(src, crossOrigin, color) { * @param {ol.style.IconImage} iconImage Icon image. */ IconImageCache.prototype.set = function(src, crossOrigin, color, iconImage) { - var key = getKey(src, crossOrigin, color); + const key = getKey(src, crossOrigin, color); this.cache_[key] = iconImage; ++this.cacheSize_; }; diff --git a/src/ol/style/Image.js b/src/ol/style/Image.js index aa82166f24..2765867b44 100644 --- a/src/ol/style/Image.js +++ b/src/ol/style/Image.js @@ -12,7 +12,7 @@ * @param {ol.StyleImageOptions} options Options. * @api */ -var ImageStyle = function(options) { +const ImageStyle = function(options) { /** * @private diff --git a/src/ol/style/RegularShape.js b/src/ol/style/RegularShape.js index 6dd283844b..547c1229c3 100644 --- a/src/ol/style/RegularShape.js +++ b/src/ol/style/RegularShape.js @@ -20,7 +20,7 @@ import ImageStyle from '../style/Image.js'; * @extends {ol.style.Image} * @api */ -var RegularShape = function(options) { +const RegularShape = function(options) { /** * @private * @type {Array.} @@ -117,13 +117,13 @@ var RegularShape = function(options) { /** * @type {boolean} */ - var snapToPixel = options.snapToPixel !== undefined ? + const snapToPixel = options.snapToPixel !== undefined ? options.snapToPixel : true; /** * @type {boolean} */ - var rotateWithView = options.rotateWithView !== undefined ? + const rotateWithView = options.rotateWithView !== undefined ? options.rotateWithView : false; ImageStyle.call(this, { @@ -144,7 +144,7 @@ inherits(RegularShape, ImageStyle); * @api */ RegularShape.prototype.clone = function() { - var style = new RegularShape({ + const style = new RegularShape({ fill: this.getFill() ? this.getFill().clone() : undefined, points: this.getPoints(), radius: this.getRadius(), @@ -313,14 +313,14 @@ RegularShape.prototype.unlistenImageChange = function(listener, thisArg) {}; * @param {ol.style.AtlasManager|undefined} atlasManager An atlas manager. */ RegularShape.prototype.render_ = function(atlasManager) { - var imageSize; - var lineCap = ''; - var lineJoin = ''; - var miterLimit = 0; - var lineDash = null; - var lineDashOffset = 0; - var strokeStyle; - var strokeWidth = 0; + let imageSize; + let lineCap = ''; + let lineJoin = ''; + let miterLimit = 0; + let lineDash = null; + let lineDashOffset = 0; + let strokeStyle; + let strokeWidth = 0; if (this.stroke_) { strokeStyle = this.stroke_.getColor(); @@ -352,10 +352,10 @@ RegularShape.prototype.render_ = function(atlasManager) { } } - var size = 2 * (this.radius_ + strokeWidth) + 1; + let size = 2 * (this.radius_ + strokeWidth) + 1; /** @type {ol.RegularShapeRenderOptions} */ - var renderOptions = { + const renderOptions = { strokeStyle: strokeStyle, strokeWidth: strokeWidth, size: size, @@ -368,7 +368,7 @@ RegularShape.prototype.render_ = function(atlasManager) { if (atlasManager === undefined) { // no atlas manager is used, create a new canvas - var context = createCanvasContext2D(size, size); + const context = createCanvasContext2D(size, size); this.canvas_ = context.canvas; // canvas.width and height are rounded to the closest integer @@ -382,18 +382,18 @@ RegularShape.prototype.render_ = function(atlasManager) { // an atlas manager is used, add the symbol to an atlas size = Math.round(size); - var hasCustomHitDetectionImage = !this.fill_; - var renderHitDetectionCallback; + const hasCustomHitDetectionImage = !this.fill_; + let renderHitDetectionCallback; if (hasCustomHitDetectionImage) { // render the hit-detection image into a separate atlas image renderHitDetectionCallback = this.drawHitDetectionCanvas_.bind(this, renderOptions); } - var id = this.getChecksum(); - var info = atlasManager.add( - id, size, size, this.draw_.bind(this, renderOptions), - renderHitDetectionCallback); + const id = this.getChecksum(); + const info = atlasManager.add( + id, size, size, this.draw_.bind(this, renderOptions), + renderHitDetectionCallback); this.canvas_ = info.image; this.origin_ = [info.offsetX, info.offsetY]; @@ -423,7 +423,7 @@ RegularShape.prototype.render_ = function(atlasManager) { * @param {number} y The origin for the symbol (y). */ RegularShape.prototype.draw_ = function(renderOptions, context, x, y) { - var i, angle0, radiusC; + let i, angle0, radiusC; // reset transform context.setTransform(1, 0, 0, 1, 0, 0); @@ -432,13 +432,13 @@ RegularShape.prototype.draw_ = function(renderOptions, context, x, y) { context.beginPath(); - var points = this.points_; + let points = this.points_; if (points === Infinity) { context.arc( - renderOptions.size / 2, renderOptions.size / 2, - this.radius_, 0, 2 * Math.PI, true); + renderOptions.size / 2, renderOptions.size / 2, + this.radius_, 0, 2 * Math.PI, true); } else { - var radius2 = (this.radius2_ !== undefined) ? this.radius2_ + const radius2 = (this.radius2_ !== undefined) ? this.radius2_ : this.radius_; if (radius2 !== this.radius_) { points = 2 * points; @@ -447,13 +447,13 @@ RegularShape.prototype.draw_ = function(renderOptions, context, x, y) { angle0 = i * 2 * Math.PI / points - Math.PI / 2 + this.angle_; radiusC = i % 2 === 0 ? this.radius_ : radius2; context.lineTo(renderOptions.size / 2 + radiusC * Math.cos(angle0), - renderOptions.size / 2 + radiusC * Math.sin(angle0)); + renderOptions.size / 2 + radiusC * Math.sin(angle0)); } } if (this.fill_) { - var color = this.fill_.getColor(); + let color = this.fill_.getColor(); if (color === null) { color = _ol_render_canvas_.defaultFillStyle; } @@ -489,7 +489,7 @@ RegularShape.prototype.createHitDetectionCanvas_ = function(renderOptions) { // if no fill style is set, create an extra hit-detection image with a // default fill style - var context = createCanvasContext2D(renderOptions.size, renderOptions.size); + const context = createCanvasContext2D(renderOptions.size, renderOptions.size); this.hitDetectionCanvas_ = context.canvas; this.drawHitDetectionCanvas_(renderOptions, context, 0, 0); @@ -512,23 +512,23 @@ RegularShape.prototype.drawHitDetectionCanvas_ = function(renderOptions, context context.beginPath(); - var points = this.points_; + let points = this.points_; if (points === Infinity) { context.arc( - renderOptions.size / 2, renderOptions.size / 2, - this.radius_, 0, 2 * Math.PI, true); + renderOptions.size / 2, renderOptions.size / 2, + this.radius_, 0, 2 * Math.PI, true); } else { - var radius2 = (this.radius2_ !== undefined) ? this.radius2_ + const radius2 = (this.radius2_ !== undefined) ? this.radius2_ : this.radius_; if (radius2 !== this.radius_) { points = 2 * points; } - var i, radiusC, angle0; + let i, radiusC, angle0; for (i = 0; i <= points; i++) { angle0 = i * 2 * Math.PI / points - Math.PI / 2 + this.angle_; radiusC = i % 2 === 0 ? this.radius_ : radius2; context.lineTo(renderOptions.size / 2 + radiusC * Math.cos(angle0), - renderOptions.size / 2 + radiusC * Math.sin(angle0)); + renderOptions.size / 2 + radiusC * Math.sin(angle0)); } } @@ -551,12 +551,12 @@ RegularShape.prototype.drawHitDetectionCanvas_ = function(renderOptions, context * @return {string} The checksum. */ RegularShape.prototype.getChecksum = function() { - var strokeChecksum = this.stroke_ ? + const strokeChecksum = this.stroke_ ? this.stroke_.getChecksum() : '-'; - var fillChecksum = this.fill_ ? + const fillChecksum = this.fill_ ? this.fill_.getChecksum() : '-'; - var recalculate = !this.checksums_ || + const recalculate = !this.checksums_ || (strokeChecksum != this.checksums_[1] || fillChecksum != this.checksums_[2] || this.radius_ != this.checksums_[3] || @@ -565,7 +565,7 @@ RegularShape.prototype.getChecksum = function() { this.points_ != this.checksums_[6]); if (recalculate) { - var checksum = 'r' + strokeChecksum + fillChecksum + + const checksum = 'r' + strokeChecksum + fillChecksum + (this.radius_ !== undefined ? this.radius_.toString() : '-') + (this.radius2_ !== undefined ? this.radius2_.toString() : '-') + (this.angle_ !== undefined ? this.angle_.toString() : '-') + diff --git a/src/ol/style/Stroke.js b/src/ol/style/Stroke.js index d4c72ce7c4..cde489a8ee 100644 --- a/src/ol/style/Stroke.js +++ b/src/ol/style/Stroke.js @@ -14,9 +14,9 @@ import {getUid} from '../index.js'; * @param {olx.style.StrokeOptions=} opt_options Options. * @api */ -var Stroke = function(opt_options) { +const Stroke = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; /** * @private @@ -74,7 +74,7 @@ var Stroke = function(opt_options) { * @api */ Stroke.prototype.clone = function() { - var color = this.getColor(); + const color = this.getColor(); return new Stroke({ color: (color && color.slice) ? color.slice() : color || undefined, lineCap: this.getLineCap(), diff --git a/src/ol/style/Style.js b/src/ol/style/Style.js index ae33eb9d5d..54025be2cf 100644 --- a/src/ol/style/Style.js +++ b/src/ol/style/Style.js @@ -18,9 +18,9 @@ import Stroke from '../style/Stroke.js'; * @param {olx.style.StyleOptions=} opt_options Style options. * @api */ -var Style = function(opt_options) { +const Style = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; /** * @private @@ -83,7 +83,7 @@ var Style = function(opt_options) { * @api */ Style.prototype.clone = function() { - var geometry = this.getGeometry(); + let geometry = this.getGeometry(); if (geometry && geometry.clone) { geometry = geometry.clone(); } @@ -279,7 +279,7 @@ Style.prototype.setZIndex = function(zIndex) { * @return {ol.StyleFunction} A style function. */ Style.createFunction = function(obj) { - var styleFunction; + let styleFunction; if (typeof obj === 'function') { styleFunction = obj; @@ -287,12 +287,12 @@ Style.createFunction = function(obj) { /** * @type {Array.} */ - var styles; + let styles; if (Array.isArray(obj)) { styles = obj; } else { assert(obj instanceof Style, - 41); // Expected an `ol.style.Style` or an array of `ol.style.Style` + 41); // Expected an `ol.style.Style` or an array of `ol.style.Style` styles = [obj]; } styleFunction = function() { @@ -322,10 +322,10 @@ Style.defaultFunction = function(feature, resolution) { // canvas.getContext('2d') at construction time, which will cause an.error // in such browsers.) if (!Style.default_) { - var fill = new Fill({ + const fill = new Fill({ color: 'rgba(255,255,255,0.4)' }); - var stroke = new Stroke({ + const stroke = new Stroke({ color: '#3399CC', width: 1.25 }); @@ -351,10 +351,10 @@ Style.defaultFunction = function(feature, resolution) { */ Style.createDefaultEditing = function() { /** @type {Object.>} */ - var styles = {}; - var white = [255, 255, 255, 1]; - var blue = [0, 153, 255, 1]; - var width = 3; + const styles = {}; + const white = [255, 255, 255, 1]; + const blue = [0, 153, 255, 1]; + const width = 3; styles[GeometryType.POLYGON] = [ new Style({ fill: new Fill({ @@ -384,7 +384,7 @@ Style.createDefaultEditing = function() { styles[GeometryType.CIRCLE] = styles[GeometryType.POLYGON].concat( - styles[GeometryType.LINE_STRING] + styles[GeometryType.LINE_STRING] ); @@ -408,8 +408,8 @@ Style.createDefaultEditing = function() { styles[GeometryType.GEOMETRY_COLLECTION] = styles[GeometryType.POLYGON].concat( - styles[GeometryType.LINE_STRING], - styles[GeometryType.POINT] + styles[GeometryType.LINE_STRING], + styles[GeometryType.POINT] ); return styles; diff --git a/src/ol/style/Text.js b/src/ol/style/Text.js index e8beec8dd7..5de37b36e8 100644 --- a/src/ol/style/Text.js +++ b/src/ol/style/Text.js @@ -12,9 +12,9 @@ import TextPlacement from '../style/TextPlacement.js'; * @param {olx.style.TextOptions=} opt_options Options. * @api */ -var Text = function(opt_options) { +const Text = function(opt_options) { - var options = opt_options || {}; + const options = opt_options || {}; /** * @private diff --git a/src/ol/tilecoord.js b/src/ol/tilecoord.js index d9d100e5c6..b6f2a30dc4 100644 --- a/src/ol/tilecoord.js +++ b/src/ol/tilecoord.js @@ -1,7 +1,7 @@ /** * @module ol/tilecoord */ -var _ol_tilecoord_ = {}; +const _ol_tilecoord_ = {}; /** @@ -68,10 +68,10 @@ _ol_tilecoord_.hash = function(tileCoord) { * @return {string} Quad key. */ _ol_tilecoord_.quadKey = function(tileCoord) { - var z = tileCoord[0]; - var digits = new Array(z); - var mask = 1 << (z - 1); - var i, charCode; + const z = tileCoord[0]; + const digits = new Array(z); + let mask = 1 << (z - 1); + let i, charCode; for (i = 0; i < z; ++i) { // 48 is charCode for 0 - '0'.charCodeAt(0) charCode = 48; @@ -94,15 +94,15 @@ _ol_tilecoord_.quadKey = function(tileCoord) { * @return {boolean} Tile coordinate is within extent and zoom level range. */ _ol_tilecoord_.withinExtentAndZ = function(tileCoord, tileGrid) { - var z = tileCoord[0]; - var x = tileCoord[1]; - var y = tileCoord[2]; + const z = tileCoord[0]; + const x = tileCoord[1]; + const y = tileCoord[2]; if (tileGrid.getMinZoom() > z || z > tileGrid.getMaxZoom()) { return false; } - var extent = tileGrid.getExtent(); - var tileRange; + const extent = tileGrid.getExtent(); + let tileRange; if (!extent) { tileRange = tileGrid.getFullTileRange(z); } else { diff --git a/src/ol/tilegrid.js b/src/ol/tilegrid.js index 8f5a0dd27e..e7c11bdce0 100644 --- a/src/ol/tilegrid.js +++ b/src/ol/tilegrid.js @@ -9,7 +9,7 @@ import _ol_obj_ from './obj.js'; import {get as getProjection, METERS_PER_UNIT} from './proj.js'; import Units from './proj/Units.js'; import TileGrid from './tilegrid/TileGrid.js'; -var _ol_tilegrid_ = {}; +const _ol_tilegrid_ = {}; /** @@ -17,7 +17,7 @@ var _ol_tilegrid_ = {}; * @return {!ol.tilegrid.TileGrid} Default tile grid for the passed projection. */ _ol_tilegrid_.getForProjection = function(projection) { - var tileGrid = projection.getDefaultTileGrid(); + let tileGrid = projection.getDefaultTileGrid(); if (!tileGrid) { tileGrid = _ol_tilegrid_.createForProjection(projection); projection.setDefaultTileGrid(tileGrid); @@ -33,12 +33,12 @@ _ol_tilegrid_.getForProjection = function(projection) { * @return {ol.TileCoord} Tile coordinate. */ _ol_tilegrid_.wrapX = function(tileGrid, tileCoord, projection) { - var z = tileCoord[0]; - var center = tileGrid.getTileCoordCenter(tileCoord); - var projectionExtent = _ol_tilegrid_.extentFromProjection(projection); + const z = tileCoord[0]; + const center = tileGrid.getTileCoordCenter(tileCoord); + const projectionExtent = _ol_tilegrid_.extentFromProjection(projection); if (!containsCoordinate(projectionExtent, center)) { - var worldWidth = getWidth(projectionExtent); - var worldsAway = Math.ceil((projectionExtent[0] - center[0]) / worldWidth); + const worldWidth = getWidth(projectionExtent); + const worldsAway = Math.ceil((projectionExtent[0] - center[0]) / worldWidth); center[0] += worldWidth * worldsAway; return tileGrid.getTileCoordForCoordAndZ(center, z); } else { @@ -58,10 +58,10 @@ _ol_tilegrid_.wrapX = function(tileGrid, tileCoord, projection) { * @return {!ol.tilegrid.TileGrid} TileGrid instance. */ _ol_tilegrid_.createForExtent = function(extent, opt_maxZoom, opt_tileSize, opt_corner) { - var corner = opt_corner !== undefined ? opt_corner : Corner.TOP_LEFT; + const corner = opt_corner !== undefined ? opt_corner : Corner.TOP_LEFT; - var resolutions = _ol_tilegrid_.resolutionsFromExtent( - extent, opt_maxZoom, opt_tileSize); + const resolutions = _ol_tilegrid_.resolutionsFromExtent( + extent, opt_maxZoom, opt_tileSize); return new TileGrid({ extent: extent, @@ -79,14 +79,14 @@ _ol_tilegrid_.createForExtent = function(extent, opt_maxZoom, opt_tileSize, opt_ * @api */ _ol_tilegrid_.createXYZ = function(opt_options) { - var options = /** @type {olx.tilegrid.TileGridOptions} */ ({}); + const options = /** @type {olx.tilegrid.TileGridOptions} */ ({}); _ol_obj_.assign(options, opt_options !== undefined ? opt_options : /** @type {olx.tilegrid.XYZOptions} */ ({})); if (options.extent === undefined) { options.extent = getProjection('EPSG:3857').getExtent(); } options.resolutions = _ol_tilegrid_.resolutionsFromExtent( - options.extent, options.maxZoom, options.tileSize); + options.extent, options.maxZoom, options.tileSize); delete options.maxZoom; return new TileGrid(options); @@ -103,20 +103,20 @@ _ol_tilegrid_.createXYZ = function(opt_options) { * @return {!Array.} Resolutions array. */ _ol_tilegrid_.resolutionsFromExtent = function(extent, opt_maxZoom, opt_tileSize) { - var maxZoom = opt_maxZoom !== undefined ? + const maxZoom = opt_maxZoom !== undefined ? opt_maxZoom : DEFAULT_MAX_ZOOM; - var height = getHeight(extent); - var width = getWidth(extent); + const height = getHeight(extent); + const width = getWidth(extent); - var tileSize = _ol_size_.toSize(opt_tileSize !== undefined ? + const tileSize = _ol_size_.toSize(opt_tileSize !== undefined ? opt_tileSize : DEFAULT_TILE_SIZE); - var maxResolution = Math.max( - width / tileSize[0], height / tileSize[1]); + const maxResolution = Math.max( + width / tileSize[0], height / tileSize[1]); - var length = maxZoom + 1; - var resolutions = new Array(length); - for (var z = 0; z < length; ++z) { + const length = maxZoom + 1; + const resolutions = new Array(length); + for (let z = 0; z < length; ++z) { resolutions[z] = maxResolution / Math.pow(2, z); } return resolutions; @@ -134,9 +134,9 @@ _ol_tilegrid_.resolutionsFromExtent = function(extent, opt_maxZoom, opt_tileSize * @return {!ol.tilegrid.TileGrid} TileGrid instance. */ _ol_tilegrid_.createForProjection = function(projection, opt_maxZoom, opt_tileSize, opt_corner) { - var extent = _ol_tilegrid_.extentFromProjection(projection); + const extent = _ol_tilegrid_.extentFromProjection(projection); return _ol_tilegrid_.createForExtent( - extent, opt_maxZoom, opt_tileSize, opt_corner); + extent, opt_maxZoom, opt_tileSize, opt_corner); }; @@ -148,9 +148,9 @@ _ol_tilegrid_.createForProjection = function(projection, opt_maxZoom, opt_tileSi */ _ol_tilegrid_.extentFromProjection = function(projection) { projection = getProjection(projection); - var extent = projection.getExtent(); + let extent = projection.getExtent(); if (!extent) { - var half = 180 * METERS_PER_UNIT[Units.DEGREES] / + const half = 180 * METERS_PER_UNIT[Units.DEGREES] / projection.getMetersPerUnit(); extent = createOrUpdate(-half, -half, half, half); } diff --git a/src/ol/tilegrid/TileGrid.js b/src/ol/tilegrid/TileGrid.js index 47a8576f23..11808e1cc9 100644 --- a/src/ol/tilegrid/TileGrid.js +++ b/src/ol/tilegrid/TileGrid.js @@ -20,7 +20,7 @@ import _ol_tilecoord_ from '../tilecoord.js'; * @struct * @api */ -var TileGrid = function(options) { +const TileGrid = function(options) { /** * @protected @@ -39,9 +39,9 @@ var TileGrid = function(options) { // check if we've got a consistent zoom factor and origin - var zoomFactor; + let zoomFactor; if (!options.origins) { - for (var i = 0, ii = this.resolutions_.length - 1; i < ii; ++i) { + for (let i = 0, ii = this.resolutions_.length - 1; i < ii; ++i) { if (!zoomFactor) { zoomFactor = this.resolutions_[i] / this.resolutions_[i + 1]; } else { @@ -81,10 +81,10 @@ var TileGrid = function(options) { if (options.origins !== undefined) { this.origins_ = options.origins; assert(this.origins_.length == this.resolutions_.length, - 20); // Number of `origins` and `resolutions` must be equal + 20); // Number of `origins` and `resolutions` must be equal } - var extent = options.extent; + const extent = options.extent; if (extent !== undefined && !this.origin_ && !this.origins_) { @@ -92,8 +92,8 @@ var TileGrid = function(options) { } assert( - (!this.origin_ && this.origins_) || (this.origin_ && !this.origins_), - 18); // Either `origin` or `origins` must be configured, never both + (!this.origin_ && this.origins_) || (this.origin_ && !this.origins_), + 18); // Either `origin` or `origins` must be configured, never both /** * @private @@ -103,7 +103,7 @@ var TileGrid = function(options) { if (options.tileSizes !== undefined) { this.tileSizes_ = options.tileSizes; assert(this.tileSizes_.length == this.resolutions_.length, - 19); // Number of `tileSizes` and `resolutions` must be equal + 19); // Number of `tileSizes` and `resolutions` must be equal } /** @@ -114,9 +114,9 @@ var TileGrid = function(options) { options.tileSize : !this.tileSizes_ ? DEFAULT_TILE_SIZE : null; assert( - (!this.tileSize_ && this.tileSizes_) || + (!this.tileSize_ && this.tileSizes_) || (this.tileSize_ && !this.tileSizes_), - 22); // Either `tileSize` or `tileSizes` must be configured, never both + 22); // Either `tileSize` or `tileSizes` must be configured, never both /** * @private @@ -139,9 +139,9 @@ var TileGrid = function(options) { if (options.sizes !== undefined) { this.fullTileRanges_ = options.sizes.map(function(size, z) { - var tileRange = new TileRange( - Math.min(0, size[0]), Math.max(size[0] - 1, -1), - Math.min(0, size[1]), Math.max(size[1] - 1, -1)); + const tileRange = new TileRange( + Math.min(0, size[0]), Math.max(size[0] - 1, -1), + Math.min(0, size[1]), Math.max(size[1] - 1, -1)); return tileRange; }, this); } else if (extent) { @@ -167,9 +167,9 @@ TileGrid.tmpTileCoord_ = [0, 0, 0]; * @api */ TileGrid.prototype.forEachTileCoord = function(extent, zoom, callback) { - var tileRange = this.getTileRangeForExtentAndZ(extent, zoom); - for (var i = tileRange.minX, ii = tileRange.maxX; i <= ii; ++i) { - for (var j = tileRange.minY, jj = tileRange.maxY; j <= jj; ++j) { + const tileRange = this.getTileRangeForExtentAndZ(extent, zoom); + for (let i = tileRange.minX, ii = tileRange.maxX; i <= ii; ++i) { + for (let j = tileRange.minY, jj = tileRange.maxY; j <= jj; ++j) { callback([zoom, i, j]); } } @@ -186,9 +186,9 @@ TileGrid.prototype.forEachTileCoord = function(extent, zoom, callback) { * @template T */ TileGrid.prototype.forEachTileCoordParentTileRange = function(tileCoord, callback, opt_this, opt_tileRange, opt_extent) { - var tileRange, x, y; - var tileCoordExtent = null; - var z = tileCoord[0] - 1; + let tileRange, x, y; + let tileCoordExtent = null; + let z = tileCoord[0] - 1; if (this.zoomFactor_ === 2) { x = tileCoord[1]; y = tileCoord[2]; @@ -286,13 +286,13 @@ TileGrid.prototype.getResolutions = function() { TileGrid.prototype.getTileCoordChildTileRange = function(tileCoord, opt_tileRange, opt_extent) { if (tileCoord[0] < this.maxZoom) { if (this.zoomFactor_ === 2) { - var minX = tileCoord[1] * 2; - var minY = tileCoord[2] * 2; + const minX = tileCoord[1] * 2; + const minY = tileCoord[2] * 2; return TileRange.createOrUpdate(minX, minX + 1, minY, minY + 1, opt_tileRange); } - var tileCoordExtent = this.getTileCoordExtent(tileCoord, opt_extent); + const tileCoordExtent = this.getTileCoordExtent(tileCoord, opt_extent); return this.getTileRangeForExtentAndZ( - tileCoordExtent, tileCoord[0] + 1, opt_tileRange); + tileCoordExtent, tileCoord[0] + 1, opt_tileRange); } return null; }; @@ -306,13 +306,13 @@ TileGrid.prototype.getTileCoordChildTileRange = function(tileCoord, opt_tileRang * @return {ol.Extent} Extent. */ TileGrid.prototype.getTileRangeExtent = function(z, tileRange, opt_extent) { - var origin = this.getOrigin(z); - var resolution = this.getResolution(z); - var tileSize = _ol_size_.toSize(this.getTileSize(z), this.tmpSize_); - var minX = origin[0] + tileRange.minX * tileSize[0] * resolution; - var maxX = origin[0] + (tileRange.maxX + 1) * tileSize[0] * resolution; - var minY = origin[1] + tileRange.minY * tileSize[1] * resolution; - var maxY = origin[1] + (tileRange.maxY + 1) * tileSize[1] * resolution; + const origin = this.getOrigin(z); + const resolution = this.getResolution(z); + const tileSize = _ol_size_.toSize(this.getTileSize(z), this.tmpSize_); + const minX = origin[0] + tileRange.minX * tileSize[0] * resolution; + const maxX = origin[0] + (tileRange.maxX + 1) * tileSize[0] * resolution; + const minY = origin[1] + tileRange.minY * tileSize[1] * resolution; + const maxY = origin[1] + (tileRange.maxY + 1) * tileSize[1] * resolution; return createOrUpdate(minX, minY, maxX, maxY, opt_extent); }; @@ -325,13 +325,13 @@ TileGrid.prototype.getTileRangeExtent = function(z, tileRange, opt_extent) { * @return {ol.TileRange} Tile range. */ TileGrid.prototype.getTileRangeForExtentAndZ = function(extent, z, opt_tileRange) { - var tileCoord = TileGrid.tmpTileCoord_; + const tileCoord = TileGrid.tmpTileCoord_; this.getTileCoordForXYAndZ_(extent[0], extent[1], z, false, tileCoord); - var minX = tileCoord[1]; - var minY = tileCoord[2]; + const minX = tileCoord[1]; + const minY = tileCoord[2]; this.getTileCoordForXYAndZ_(extent[2], extent[3], z, true, tileCoord); return TileRange.createOrUpdate( - minX, tileCoord[1], minY, tileCoord[2], opt_tileRange); + minX, tileCoord[1], minY, tileCoord[2], opt_tileRange); }; @@ -340,9 +340,9 @@ TileGrid.prototype.getTileRangeForExtentAndZ = function(extent, z, opt_tileRange * @return {ol.Coordinate} Tile center. */ TileGrid.prototype.getTileCoordCenter = function(tileCoord) { - var origin = this.getOrigin(tileCoord[0]); - var resolution = this.getResolution(tileCoord[0]); - var tileSize = _ol_size_.toSize(this.getTileSize(tileCoord[0]), this.tmpSize_); + const origin = this.getOrigin(tileCoord[0]); + const resolution = this.getResolution(tileCoord[0]); + const tileSize = _ol_size_.toSize(this.getTileSize(tileCoord[0]), this.tmpSize_); return [ origin[0] + (tileCoord[1] + 0.5) * tileSize[0] * resolution, origin[1] + (tileCoord[2] + 0.5) * tileSize[1] * resolution @@ -359,13 +359,13 @@ TileGrid.prototype.getTileCoordCenter = function(tileCoord) { * @api */ TileGrid.prototype.getTileCoordExtent = function(tileCoord, opt_extent) { - var origin = this.getOrigin(tileCoord[0]); - var resolution = this.getResolution(tileCoord[0]); - var tileSize = _ol_size_.toSize(this.getTileSize(tileCoord[0]), this.tmpSize_); - var minX = origin[0] + tileCoord[1] * tileSize[0] * resolution; - var minY = origin[1] + tileCoord[2] * tileSize[1] * resolution; - var maxX = minX + tileSize[0] * resolution; - var maxY = minY + tileSize[1] * resolution; + const origin = this.getOrigin(tileCoord[0]); + const resolution = this.getResolution(tileCoord[0]); + const tileSize = _ol_size_.toSize(this.getTileSize(tileCoord[0]), this.tmpSize_); + const minX = origin[0] + tileCoord[1] * tileSize[0] * resolution; + const minY = origin[1] + tileCoord[2] * tileSize[1] * resolution; + const maxX = minX + tileSize[0] * resolution; + const maxY = minY + tileSize[1] * resolution; return createOrUpdate(minX, minY, maxX, maxY, opt_extent); }; @@ -383,7 +383,7 @@ TileGrid.prototype.getTileCoordExtent = function(tileCoord, opt_extent) { */ TileGrid.prototype.getTileCoordForCoordAndResolution = function(coordinate, resolution, opt_tileCoord) { return this.getTileCoordForXYAndResolution_( - coordinate[0], coordinate[1], resolution, false, opt_tileCoord); + coordinate[0], coordinate[1], resolution, false, opt_tileCoord); }; @@ -401,18 +401,18 @@ TileGrid.prototype.getTileCoordForCoordAndResolution = function(coordinate, reso * @private */ TileGrid.prototype.getTileCoordForXYAndResolution_ = function( - x, y, resolution, reverseIntersectionPolicy, opt_tileCoord) { - var z = this.getZForResolution(resolution); - var scale = resolution / this.getResolution(z); - var origin = this.getOrigin(z); - var tileSize = _ol_size_.toSize(this.getTileSize(z), this.tmpSize_); + x, y, resolution, reverseIntersectionPolicy, opt_tileCoord) { + const z = this.getZForResolution(resolution); + const scale = resolution / this.getResolution(z); + const origin = this.getOrigin(z); + const tileSize = _ol_size_.toSize(this.getTileSize(z), this.tmpSize_); - var adjustX = reverseIntersectionPolicy ? 0.5 : 0; - var adjustY = reverseIntersectionPolicy ? 0 : 0.5; - var xFromOrigin = Math.floor((x - origin[0]) / resolution + adjustX); - var yFromOrigin = Math.floor((y - origin[1]) / resolution + adjustY); - var tileCoordX = scale * xFromOrigin / tileSize[0]; - var tileCoordY = scale * yFromOrigin / tileSize[1]; + const adjustX = reverseIntersectionPolicy ? 0.5 : 0; + const adjustY = reverseIntersectionPolicy ? 0 : 0.5; + const xFromOrigin = Math.floor((x - origin[0]) / resolution + adjustX); + const yFromOrigin = Math.floor((y - origin[1]) / resolution + adjustY); + let tileCoordX = scale * xFromOrigin / tileSize[0]; + let tileCoordY = scale * yFromOrigin / tileSize[1]; if (reverseIntersectionPolicy) { tileCoordX = Math.ceil(tileCoordX) - 1; @@ -442,16 +442,16 @@ TileGrid.prototype.getTileCoordForXYAndResolution_ = function( * @private */ TileGrid.prototype.getTileCoordForXYAndZ_ = function(x, y, z, reverseIntersectionPolicy, opt_tileCoord) { - var origin = this.getOrigin(z); - var resolution = this.getResolution(z); - var tileSize = _ol_size_.toSize(this.getTileSize(z), this.tmpSize_); + const origin = this.getOrigin(z); + const resolution = this.getResolution(z); + const tileSize = _ol_size_.toSize(this.getTileSize(z), this.tmpSize_); - var adjustX = reverseIntersectionPolicy ? 0.5 : 0; - var adjustY = reverseIntersectionPolicy ? 0 : 0.5; - var xFromOrigin = Math.floor((x - origin[0]) / resolution + adjustX); - var yFromOrigin = Math.floor((y - origin[1]) / resolution + adjustY); - var tileCoordX = xFromOrigin / tileSize[0]; - var tileCoordY = yFromOrigin / tileSize[1]; + const adjustX = reverseIntersectionPolicy ? 0.5 : 0; + const adjustY = reverseIntersectionPolicy ? 0 : 0.5; + const xFromOrigin = Math.floor((x - origin[0]) / resolution + adjustX); + const yFromOrigin = Math.floor((y - origin[1]) / resolution + adjustY); + let tileCoordX = xFromOrigin / tileSize[0]; + let tileCoordY = yFromOrigin / tileSize[1]; if (reverseIntersectionPolicy) { tileCoordX = Math.ceil(tileCoordX) - 1; @@ -475,7 +475,7 @@ TileGrid.prototype.getTileCoordForXYAndZ_ = function(x, y, z, reverseIntersectio */ TileGrid.prototype.getTileCoordForCoordAndZ = function(coordinate, z, opt_tileCoord) { return this.getTileCoordForXYAndZ_( - coordinate[0], coordinate[1], z, false, opt_tileCoord); + coordinate[0], coordinate[1], z, false, opt_tileCoord); }; @@ -527,7 +527,7 @@ TileGrid.prototype.getFullTileRange = function(z) { * @api */ TileGrid.prototype.getZForResolution = function(resolution, opt_direction) { - var z = linearFindNearest(this.resolutions_, resolution, opt_direction || 0); + const z = linearFindNearest(this.resolutions_, resolution, opt_direction || 0); return clamp(z, this.minZoom, this.maxZoom); }; @@ -537,9 +537,9 @@ TileGrid.prototype.getZForResolution = function(resolution, opt_direction) { * @private */ TileGrid.prototype.calculateTileRanges_ = function(extent) { - var length = this.resolutions_.length; - var fullTileRanges = new Array(length); - for (var z = this.minZoom; z < length; ++z) { + const length = this.resolutions_.length; + const fullTileRanges = new Array(length); + for (let z = this.minZoom; z < length; ++z) { fullTileRanges[z] = this.getTileRangeForExtentAndZ(extent, z); } this.fullTileRanges_ = fullTileRanges; diff --git a/src/ol/tilegrid/WMTS.js b/src/ol/tilegrid/WMTS.js index cabb7cc7bc..0dc3985c68 100644 --- a/src/ol/tilegrid/WMTS.js +++ b/src/ol/tilegrid/WMTS.js @@ -16,7 +16,7 @@ import TileGrid from '../tilegrid/TileGrid.js'; * @struct * @api */ -var WMTSTileGrid = function(options) { +const WMTSTileGrid = function(options) { /** * @private * @type {!Array.} @@ -73,32 +73,32 @@ export default WMTSTileGrid; export function createFromCapabilitiesMatrixSet(matrixSet, opt_extent, opt_matrixLimits) { /** @type {!Array.} */ - var resolutions = []; + const resolutions = []; /** @type {!Array.} */ - var matrixIds = []; + const matrixIds = []; /** @type {!Array.} */ - var origins = []; + const origins = []; /** @type {!Array.} */ - var tileSizes = []; + const tileSizes = []; /** @type {!Array.} */ - var sizes = []; + const sizes = []; - var matrixLimits = opt_matrixLimits !== undefined ? opt_matrixLimits : []; + const matrixLimits = opt_matrixLimits !== undefined ? opt_matrixLimits : []; - var supportedCRSPropName = 'SupportedCRS'; - var matrixIdsPropName = 'TileMatrix'; - var identifierPropName = 'Identifier'; - var scaleDenominatorPropName = 'ScaleDenominator'; - var topLeftCornerPropName = 'TopLeftCorner'; - var tileWidthPropName = 'TileWidth'; - var tileHeightPropName = 'TileHeight'; + const supportedCRSPropName = 'SupportedCRS'; + const matrixIdsPropName = 'TileMatrix'; + const identifierPropName = 'Identifier'; + const scaleDenominatorPropName = 'ScaleDenominator'; + const topLeftCornerPropName = 'TopLeftCorner'; + const tileWidthPropName = 'TileWidth'; + const tileHeightPropName = 'TileHeight'; - var code = matrixSet[supportedCRSPropName]; - var projection = getProjection(code.replace(/urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/, '$1:$3')) || + const code = matrixSet[supportedCRSPropName]; + const projection = getProjection(code.replace(/urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/, '$1:$3')) || getProjection(code); - var metersPerUnit = projection.getMetersPerUnit(); + const metersPerUnit = projection.getMetersPerUnit(); // swap origin x and y coordinates if axis orientation is lat/long - var switchOriginXY = projection.getAxisOrientation().substr(0, 2) == 'ne'; + const switchOriginXY = projection.getAxisOrientation().substr(0, 2) == 'ne'; matrixSet[matrixIdsPropName].sort(function(a, b) { return b[scaleDenominatorPropName] - a[scaleDenominatorPropName]; @@ -106,23 +106,23 @@ export function createFromCapabilitiesMatrixSet(matrixSet, opt_extent, opt_matri matrixSet[matrixIdsPropName].forEach(function(elt, index, array) { - var matrixAvailable; + let matrixAvailable; // use of matrixLimits to filter TileMatrices from GetCapabilities // TileMatrixSet from unavailable matrix levels. if (matrixLimits.length > 0) { matrixAvailable = find(matrixLimits, - function(elt_ml, index_ml, array_ml) { - return elt[identifierPropName] == elt_ml[matrixIdsPropName]; - }); + function(elt_ml, index_ml, array_ml) { + return elt[identifierPropName] == elt_ml[matrixIdsPropName]; + }); } else { matrixAvailable = true; } if (matrixAvailable) { matrixIds.push(elt[identifierPropName]); - var resolution = elt[scaleDenominatorPropName] * 0.28E-3 / metersPerUnit; - var tileWidth = elt[tileWidthPropName]; - var tileHeight = elt[tileHeightPropName]; + const resolution = elt[scaleDenominatorPropName] * 0.28E-3 / metersPerUnit; + const tileWidth = elt[tileWidthPropName]; + const tileHeight = elt[tileHeightPropName]; if (switchOriginXY) { origins.push([elt[topLeftCornerPropName][1], elt[topLeftCornerPropName][0]]); diff --git a/src/ol/tilegrid/common.js b/src/ol/tilegrid/common.js index e003fba738..b43e79676f 100644 --- a/src/ol/tilegrid/common.js +++ b/src/ol/tilegrid/common.js @@ -1,9 +1,9 @@ /** * @type {number} Default maximum zoom for default tile grids. */ -export var DEFAULT_MAX_ZOOM = 42; +export const DEFAULT_MAX_ZOOM = 42; /** * @type {number} Default tile size. */ -export var DEFAULT_TILE_SIZE = 256; +export const DEFAULT_TILE_SIZE = 256; diff --git a/src/ol/tileurlfunction.js b/src/ol/tileurlfunction.js index d00c07d8fc..5e3e01b4e1 100644 --- a/src/ol/tileurlfunction.js +++ b/src/ol/tileurlfunction.js @@ -12,10 +12,10 @@ import _ol_tilecoord_ from './tilecoord.js'; * @return {ol.TileUrlFunctionType} Tile URL function. */ export function createFromTemplate(template, tileGrid) { - var zRegEx = /\{z\}/g; - var xRegEx = /\{x\}/g; - var yRegEx = /\{y\}/g; - var dashYRegEx = /\{-y\}/g; + const zRegEx = /\{z\}/g; + const xRegEx = /\{x\}/g; + const yRegEx = /\{y\}/g; + const dashYRegEx = /\{-y\}/g; return ( /** * @param {ol.TileCoord} tileCoord Tile Coordinate. @@ -28,18 +28,18 @@ export function createFromTemplate(template, tileGrid) { return undefined; } else { return template.replace(zRegEx, tileCoord[0].toString()) - .replace(xRegEx, tileCoord[1].toString()) - .replace(yRegEx, function() { - var y = -tileCoord[2] - 1; - return y.toString(); - }) - .replace(dashYRegEx, function() { - var z = tileCoord[0]; - var range = tileGrid.getFullTileRange(z); - assert(range, 55); // The {-y} placeholder requires a tile grid with extent - var y = range.getHeight() + tileCoord[2]; - return y.toString(); - }); + .replace(xRegEx, tileCoord[1].toString()) + .replace(yRegEx, function() { + const y = -tileCoord[2] - 1; + return y.toString(); + }) + .replace(dashYRegEx, function() { + const z = tileCoord[0]; + const range = tileGrid.getFullTileRange(z); + assert(range, 55); // The {-y} placeholder requires a tile grid with extent + const y = range.getHeight() + tileCoord[2]; + return y.toString(); + }); } } ); @@ -52,9 +52,9 @@ export function createFromTemplate(template, tileGrid) { * @return {ol.TileUrlFunctionType} Tile URL function. */ export function createFromTemplates(templates, tileGrid) { - var len = templates.length; - var tileUrlFunctions = new Array(len); - for (var i = 0; i < len; ++i) { + const len = templates.length; + const tileUrlFunctions = new Array(len); + for (let i = 0; i < len; ++i) { tileUrlFunctions[i] = createFromTemplate(templates[i], tileGrid); } return createFromTileUrlFunctions(tileUrlFunctions); @@ -80,8 +80,8 @@ export function createFromTileUrlFunctions(tileUrlFunctions) { if (!tileCoord) { return undefined; } else { - var h = _ol_tilecoord_.hash(tileCoord); - var index = modulo(h, tileUrlFunctions.length); + const h = _ol_tilecoord_.hash(tileCoord); + const index = modulo(h, tileUrlFunctions.length); return tileUrlFunctions[index](tileCoord, pixelRatio, projection); } } @@ -105,13 +105,13 @@ export function nullTileUrlFunction(tileCoord, pixelRatio, projection) { * @return {Array.} Array of urls. */ export function expandUrl(url) { - var urls = []; - var match = /\{([a-z])-([a-z])\}/.exec(url); + const urls = []; + let match = /\{([a-z])-([a-z])\}/.exec(url); if (match) { // char range - 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) { urls.push(url.replace(match[0], String.fromCharCode(charCode))); } @@ -120,8 +120,8 @@ export function expandUrl(url) { match = match = /\{(\d+)-(\d+)\}/.exec(url); if (match) { // number range - var stop = parseInt(match[2], 10); - for (var i = parseInt(match[1], 10); i <= stop; i++) { + const stop = parseInt(match[2], 10); + for (let i = parseInt(match[1], 10); i <= stop; i++) { urls.push(url.replace(match[0], i.toString())); } return urls; diff --git a/src/ol/transform.js b/src/ol/transform.js index e85bc7b332..b931cb284a 100644 --- a/src/ol/transform.js +++ b/src/ol/transform.js @@ -2,7 +2,7 @@ * @module ol/transform */ import {assert} from './asserts.js'; -var _ol_transform_ = {}; +const _ol_transform_ = {}; /** @@ -52,18 +52,18 @@ _ol_transform_.reset = function(transform) { * @return {!ol.Transform} transform1 multiplied with transform2. */ _ol_transform_.multiply = function(transform1, transform2) { - var a1 = transform1[0]; - var b1 = transform1[1]; - var c1 = transform1[2]; - var d1 = transform1[3]; - var e1 = transform1[4]; - var f1 = transform1[5]; - var a2 = transform2[0]; - var b2 = transform2[1]; - var c2 = transform2[2]; - var d2 = transform2[3]; - var e2 = transform2[4]; - var f2 = transform2[5]; + const a1 = transform1[0]; + const b1 = transform1[1]; + const c1 = transform1[2]; + const d1 = transform1[3]; + const e1 = transform1[4]; + const f1 = transform1[5]; + const a2 = transform2[0]; + const b2 = transform2[1]; + const c2 = transform2[2]; + const d2 = transform2[3]; + const e2 = transform2[4]; + const f2 = transform2[5]; transform1[0] = a1 * a2 + c1 * b2; transform1[1] = b1 * a2 + d1 * b2; @@ -124,7 +124,8 @@ _ol_transform_.setFromArray = function(transform1, transform2) { * chained together. */ _ol_transform_.apply = function(transform, coordinate) { - var x = coordinate[0], y = coordinate[1]; + const x = coordinate[0]; + const y = coordinate[1]; coordinate[0] = transform[0] * x + transform[2] * y + transform[4]; coordinate[1] = transform[1] * x + transform[3] * y + transform[5]; return coordinate; @@ -138,10 +139,10 @@ _ol_transform_.apply = function(transform, coordinate) { * @return {!ol.Transform} The rotated transform. */ _ol_transform_.rotate = function(transform, angle) { - var cos = Math.cos(angle); - var sin = Math.sin(angle); + const cos = Math.cos(angle); + const sin = Math.sin(angle); return _ol_transform_.multiply(transform, - _ol_transform_.set(_ol_transform_.tmp_, cos, sin, -sin, cos, 0, 0)); + _ol_transform_.set(_ol_transform_.tmp_, cos, sin, -sin, cos, 0, 0)); }; @@ -154,7 +155,7 @@ _ol_transform_.rotate = function(transform, angle) { */ _ol_transform_.scale = function(transform, x, y) { return _ol_transform_.multiply(transform, - _ol_transform_.set(_ol_transform_.tmp_, x, 0, 0, y, 0, 0)); + _ol_transform_.set(_ol_transform_.tmp_, x, 0, 0, y, 0, 0)); }; @@ -167,7 +168,7 @@ _ol_transform_.scale = function(transform, x, y) { */ _ol_transform_.translate = function(transform, dx, dy) { return _ol_transform_.multiply(transform, - _ol_transform_.set(_ol_transform_.tmp_, 1, 0, 0, 1, dx, dy)); + _ol_transform_.set(_ol_transform_.tmp_, 1, 0, 0, 1, dx, dy)); }; @@ -185,8 +186,8 @@ _ol_transform_.translate = function(transform, dx, dy) { * @return {!ol.Transform} The composite transform. */ _ol_transform_.compose = function(transform, dx1, dy1, sx, sy, angle, dx2, dy2) { - var sin = Math.sin(angle); - var cos = Math.cos(angle); + const sin = Math.sin(angle); + const cos = Math.cos(angle); transform[0] = sx * cos; transform[1] = sy * sin; transform[2] = -sx * sin; @@ -203,15 +204,15 @@ _ol_transform_.compose = function(transform, dx1, dy1, sx, sy, angle, dx2, dy2) * @return {!ol.Transform} Inverse of the transform. */ _ol_transform_.invert = function(transform) { - var det = _ol_transform_.determinant(transform); + const det = _ol_transform_.determinant(transform); assert(det !== 0, 32); // Transformation matrix cannot be inverted - var a = transform[0]; - var b = transform[1]; - var c = transform[2]; - var d = transform[3]; - var e = transform[4]; - var f = transform[5]; + const a = transform[0]; + const b = transform[1]; + const c = transform[2]; + const d = transform[3]; + const e = transform[4]; + const f = transform[5]; transform[0] = d / det; transform[1] = -b / det; diff --git a/src/ol/typedefs.js b/src/ol/typedefs.js index 4e51dfd1b0..01115f37da 100644 --- a/src/ol/typedefs.js +++ b/src/ol/typedefs.js @@ -1,31 +1,8 @@ /** * @module ol/typedefs */ -/* eslint-disable openlayers-internal/no-missing-requires */ -/** - * File for all typedefs used by the compiler, and referenced by JSDoc. - * - * These look like vars (or var properties), but in fact are simply identifiers - * for the Closure compiler. Originally they were included in the appropriate - * namespace file, but with the move away from Closure namespaces and towards - * self-contained standard modules are now all in this file. - * Unlike the other type definitions - enums and constructor functions - they - * are not code and so are not imported or exported. They are only referred to - * in type-defining comments used by the Closure compiler, and so should not - * appear in module code. - * - * They are now all in the `ol` namespace. - */ - - -/** - * @typedef {{x: number, y: number, width: number, height: number}} - */ -/** - * @module ol/typedefs - */ -/* eslint-disable openlayers-internal/no-missing-requires */ +/* global ol:false */ /** * File for all typedefs used by the compiler, and referenced by JSDoc. diff --git a/src/ol/uri.js b/src/ol/uri.js index b96f27a8c2..0fe4f0731a 100644 --- a/src/ol/uri.js +++ b/src/ol/uri.js @@ -1,7 +1,7 @@ /** * @module ol/uri */ -var _ol_uri_ = {}; +const _ol_uri_ = {}; /** @@ -13,14 +13,14 @@ var _ol_uri_ = {}; * @return {string} The new URI. */ _ol_uri_.appendParams = function(uri, params) { - var keyParams = []; + const keyParams = []; // Skip any null or undefined parameter values Object.keys(params).forEach(function(k) { if (params[k] !== null && params[k] !== undefined) { keyParams.push(k + '=' + encodeURIComponent(params[k])); } }); - var qs = keyParams.join('&'); + const qs = keyParams.join('&'); // remove any trailing ? or & uri = uri.replace(/[?&]$/, ''); // append ? or & depending on whether uri has existing parameters diff --git a/src/ol/webgl.js b/src/ol/webgl.js index 8b35027b6b..f43d768af6 100644 --- a/src/ol/webgl.js +++ b/src/ol/webgl.js @@ -1,7 +1,7 @@ /** * @module ol/webgl */ -var _ol_webgl_ = {}; +const _ol_webgl_ = {}; /** * Constants taken from goog.webgl @@ -276,10 +276,10 @@ _ol_webgl_.CONTEXT_IDS_ = [ * @return {WebGLRenderingContext} WebGL rendering context. */ _ol_webgl_.getContext = function(canvas, opt_attributes) { - var context, i, ii = _ol_webgl_.CONTEXT_IDS_.length; - for (i = 0; i < ii; ++i) { + const ii = _ol_webgl_.CONTEXT_IDS_.length; + for (let i = 0; i < ii; ++i) { try { - context = canvas.getContext(_ol_webgl_.CONTEXT_IDS_[i], opt_attributes); + const context = canvas.getContext(_ol_webgl_.CONTEXT_IDS_[i], opt_attributes); if (context) { return /** @type {!WebGLRenderingContext} */ (context); } diff --git a/src/ol/webgl/Buffer.js b/src/ol/webgl/Buffer.js index d56f2c1a2d..6fbaff5c98 100644 --- a/src/ol/webgl/Buffer.js +++ b/src/ol/webgl/Buffer.js @@ -9,7 +9,7 @@ import _ol_webgl_ from '../webgl.js'; * @param {number=} opt_usage Usage. * @struct */ -var _ol_webgl_Buffer_ = function(opt_arr, opt_usage) { +const _ol_webgl_Buffer_ = function(opt_arr, opt_usage) { /** * @private diff --git a/src/ol/webgl/Context.js b/src/ol/webgl/Context.js index de43d84ad5..2ced8e78b9 100644 --- a/src/ol/webgl/Context.js +++ b/src/ol/webgl/Context.js @@ -18,7 +18,7 @@ import ContextEventType from '../webgl/ContextEventType.js'; * @param {HTMLCanvasElement} canvas Canvas. * @param {WebGLRenderingContext} gl GL. */ -var _ol_webgl_Context_ = function(canvas, gl) { +const _ol_webgl_Context_ = function(canvas, gl) { /** * @private @@ -85,9 +85,9 @@ var _ol_webgl_Context_ = function(canvas, gl) { } _ol_events_.listen(this.canvas_, ContextEventType.LOST, - this.handleWebGLContextLost, this); + this.handleWebGLContextLost, this); _ol_events_.listen(this.canvas_, ContextEventType.RESTORED, - this.handleWebGLContextRestored, this); + this.handleWebGLContextRestored, this); }; @@ -102,16 +102,16 @@ inherits(_ol_webgl_Context_, Disposable); * @param {ol.webgl.Buffer} buf Buffer. */ _ol_webgl_Context_.prototype.bindBuffer = function(target, buf) { - var gl = this.getGL(); - var arr = buf.getArray(); - var bufferKey = String(getUid(buf)); + const gl = this.getGL(); + const arr = buf.getArray(); + const bufferKey = String(getUid(buf)); if (bufferKey in this.bufferCache_) { - var bufferCacheEntry = this.bufferCache_[bufferKey]; + const bufferCacheEntry = this.bufferCache_[bufferKey]; gl.bindBuffer(target, bufferCacheEntry.buffer); } else { - var buffer = gl.createBuffer(); + const buffer = gl.createBuffer(); gl.bindBuffer(target, buffer); - var /** @type {ArrayBufferView} */ arrayBuffer; + let /** @type {ArrayBufferView} */ arrayBuffer; if (target == _ol_webgl_.ARRAY_BUFFER) { arrayBuffer = new Float32Array(arr); } else if (target == _ol_webgl_.ELEMENT_ARRAY_BUFFER) { @@ -131,9 +131,9 @@ _ol_webgl_Context_.prototype.bindBuffer = function(target, buf) { * @param {ol.webgl.Buffer} buf Buffer. */ _ol_webgl_Context_.prototype.deleteBuffer = function(buf) { - var gl = this.getGL(); - var bufferKey = String(getUid(buf)); - var bufferCacheEntry = this.bufferCache_[bufferKey]; + const gl = this.getGL(); + const bufferKey = String(getUid(buf)); + const bufferCacheEntry = this.bufferCache_[bufferKey]; if (!gl.isContextLost()) { gl.deleteBuffer(bufferCacheEntry.buffer); } @@ -146,9 +146,9 @@ _ol_webgl_Context_.prototype.deleteBuffer = function(buf) { */ _ol_webgl_Context_.prototype.disposeInternal = function() { _ol_events_.unlistenAll(this.canvas_); - var gl = this.getGL(); + const gl = this.getGL(); if (!gl.isContextLost()) { - var key; + let key; for (key in this.bufferCache_) { gl.deleteBuffer(this.bufferCache_[key].buffer); } @@ -203,12 +203,12 @@ _ol_webgl_Context_.prototype.getHitDetectionFramebuffer = function() { * @return {WebGLShader} Shader. */ _ol_webgl_Context_.prototype.getShader = function(shaderObject) { - var shaderKey = String(getUid(shaderObject)); + const shaderKey = String(getUid(shaderObject)); if (shaderKey in this.shaderCache_) { return this.shaderCache_[shaderKey]; } else { - var gl = this.getGL(); - var shader = gl.createShader(shaderObject.getType()); + const gl = this.getGL(); + const shader = gl.createShader(shaderObject.getType()); gl.shaderSource(shader, shaderObject.getSource()); gl.compileShader(shader); this.shaderCache_[shaderKey] = shader; @@ -226,14 +226,14 @@ _ol_webgl_Context_.prototype.getShader = function(shaderObject) { * @return {WebGLProgram} Program. */ _ol_webgl_Context_.prototype.getProgram = function( - fragmentShaderObject, vertexShaderObject) { - var programKey = + fragmentShaderObject, vertexShaderObject) { + const programKey = getUid(fragmentShaderObject) + '/' + getUid(vertexShaderObject); if (programKey in this.programCache_) { return this.programCache_[programKey]; } else { - var gl = this.getGL(); - var program = gl.createProgram(); + const gl = this.getGL(); + const program = gl.createProgram(); gl.attachShader(program, this.getShader(fragmentShaderObject)); gl.attachShader(program, this.getShader(vertexShaderObject)); gl.linkProgram(program); @@ -269,18 +269,18 @@ _ol_webgl_Context_.prototype.handleWebGLContextRestored = function() { * @private */ _ol_webgl_Context_.prototype.initHitDetectionFramebuffer_ = function() { - var gl = this.gl_; - var framebuffer = gl.createFramebuffer(); + const gl = this.gl_; + const framebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); - var texture = _ol_webgl_Context_.createEmptyTexture(gl, 1, 1); - var renderbuffer = gl.createRenderbuffer(); + const texture = _ol_webgl_Context_.createEmptyTexture(gl, 1, 1); + const renderbuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, 1, 1); gl.framebufferTexture2D( - gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); + gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, - gl.RENDERBUFFER, renderbuffer); + gl.RENDERBUFFER, renderbuffer); gl.bindTexture(gl.TEXTURE_2D, null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); @@ -302,7 +302,7 @@ _ol_webgl_Context_.prototype.useProgram = function(program) { if (program == this.currentProgram_) { return false; } else { - var gl = this.getGL(); + const gl = this.getGL(); gl.useProgram(program); this.currentProgram_ = program; return true; @@ -318,18 +318,18 @@ _ol_webgl_Context_.prototype.useProgram = function(program) { * @private */ _ol_webgl_Context_.createTexture_ = function(gl, opt_wrapS, opt_wrapT) { - var texture = gl.createTexture(); + const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); if (opt_wrapS !== undefined) { gl.texParameteri( - _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_WRAP_S, opt_wrapS); + _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_WRAP_S, opt_wrapS); } if (opt_wrapT !== undefined) { gl.texParameteri( - _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_WRAP_T, opt_wrapT); + _ol_webgl_.TEXTURE_2D, _ol_webgl_.TEXTURE_WRAP_T, opt_wrapT); } return texture; @@ -345,11 +345,11 @@ _ol_webgl_Context_.createTexture_ = function(gl, opt_wrapS, opt_wrapT) { * @return {WebGLTexture} The texture. */ _ol_webgl_Context_.createEmptyTexture = function( - gl, width, height, opt_wrapS, opt_wrapT) { - var texture = _ol_webgl_Context_.createTexture_(gl, opt_wrapS, opt_wrapT); + gl, width, height, opt_wrapS, opt_wrapT) { + const texture = _ol_webgl_Context_.createTexture_(gl, opt_wrapS, opt_wrapT); gl.texImage2D( - gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, - null); + gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, + null); return texture; }; @@ -363,9 +363,9 @@ _ol_webgl_Context_.createEmptyTexture = function( * @return {WebGLTexture} The texture. */ _ol_webgl_Context_.createTexture = function(gl, image, opt_wrapS, opt_wrapT) { - var texture = _ol_webgl_Context_.createTexture_(gl, opt_wrapS, opt_wrapT); + const texture = _ol_webgl_Context_.createTexture_(gl, opt_wrapS, opt_wrapT); gl.texImage2D( - gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); + gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; }; diff --git a/src/ol/webgl/Fragment.js b/src/ol/webgl/Fragment.js index be02e2fd65..8dc538c97a 100644 --- a/src/ol/webgl/Fragment.js +++ b/src/ol/webgl/Fragment.js @@ -11,7 +11,7 @@ import _ol_webgl_Shader_ from '../webgl/Shader.js'; * @param {string} source Source. * @struct */ -var _ol_webgl_Fragment_ = function(source) { +const _ol_webgl_Fragment_ = function(source) { _ol_webgl_Shader_.call(this, source); }; diff --git a/src/ol/webgl/Shader.js b/src/ol/webgl/Shader.js index deb547a161..0605c711b0 100644 --- a/src/ol/webgl/Shader.js +++ b/src/ol/webgl/Shader.js @@ -9,7 +9,7 @@ import {FALSE} from '../functions.js'; * @param {string} source Source. * @struct */ -var _ol_webgl_Shader_ = function(source) { +const _ol_webgl_Shader_ = function(source) { /** * @private diff --git a/src/ol/webgl/Vertex.js b/src/ol/webgl/Vertex.js index e204ce7989..8ed4a74e37 100644 --- a/src/ol/webgl/Vertex.js +++ b/src/ol/webgl/Vertex.js @@ -11,7 +11,7 @@ import _ol_webgl_Shader_ from '../webgl/Shader.js'; * @param {string} source Source. * @struct */ -var _ol_webgl_Vertex_ = function(source) { +const _ol_webgl_Vertex_ = function(source) { _ol_webgl_Shader_.call(this, source); }; diff --git a/src/ol/xml.js b/src/ol/xml.js index 724a3e7594..d2e3700e0a 100644 --- a/src/ol/xml.js +++ b/src/ol/xml.js @@ -2,7 +2,7 @@ * @module ol/xml */ import {extend} from './array.js'; -var _ol_xml_ = {}; +const _ol_xml_ = {}; /** @@ -56,7 +56,7 @@ _ol_xml_.getAllTextContent_ = function(node, normalizeWhitespace, accumulator) { accumulator.push(node.nodeValue); } } else { - var n; + let n; for (n = node.firstChild; n; n = n.nextSibling) { _ol_xml_.getAllTextContent_(n, normalizeWhitespace, accumulator); } @@ -132,9 +132,9 @@ _ol_xml_.makeArrayExtender = function(valueReader, opt_this) { * @param {Array.<*>} objectStack Object stack. */ function(node, objectStack) { - var value = valueReader.call(opt_this, node, objectStack); + const value = valueReader.call(opt_this, node, objectStack); if (value !== undefined) { - var array = /** @type {Array.<*>} */ + const array = /** @type {Array.<*>} */ (objectStack[objectStack.length - 1]); extend(array, value); } @@ -158,10 +158,10 @@ _ol_xml_.makeArrayPusher = function(valueReader, opt_this) { * @param {Array.<*>} objectStack Object stack. */ function(node, objectStack) { - var value = valueReader.call(opt_this !== undefined ? opt_this : this, - node, objectStack); + const value = valueReader.call(opt_this !== undefined ? opt_this : this, + node, objectStack); if (value !== undefined) { - var array = objectStack[objectStack.length - 1]; + const array = objectStack[objectStack.length - 1]; array.push(value); } }); @@ -183,8 +183,8 @@ _ol_xml_.makeReplacer = function(valueReader, opt_this) { * @param {Array.<*>} objectStack Object stack. */ function(node, objectStack) { - var value = valueReader.call(opt_this !== undefined ? opt_this : this, - node, objectStack); + const value = valueReader.call(opt_this !== undefined ? opt_this : this, + node, objectStack); if (value !== undefined) { objectStack[objectStack.length - 1] = value; } @@ -208,14 +208,14 @@ _ol_xml_.makeObjectPropertyPusher = function(valueReader, opt_property, opt_this * @param {Array.<*>} objectStack Object stack. */ function(node, objectStack) { - var value = valueReader.call(opt_this !== undefined ? opt_this : this, - node, objectStack); + const value = valueReader.call(opt_this !== undefined ? opt_this : this, + node, objectStack); if (value !== undefined) { - var object = /** @type {Object} */ + const object = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var property = opt_property !== undefined ? + const property = opt_property !== undefined ? opt_property : node.localName; - var array; + let array; if (property in object) { array = object[property]; } else { @@ -242,12 +242,12 @@ _ol_xml_.makeObjectPropertySetter = function(valueReader, opt_property, opt_this * @param {Array.<*>} objectStack Object stack. */ function(node, objectStack) { - var value = valueReader.call(opt_this !== undefined ? opt_this : this, - node, objectStack); + const value = valueReader.call(opt_this !== undefined ? opt_this : this, + node, objectStack); if (value !== undefined) { - var object = /** @type {Object} */ + const object = /** @type {Object} */ (objectStack[objectStack.length - 1]); - var property = opt_property !== undefined ? + const property = opt_property !== undefined ? opt_property : node.localName; object[property] = value; } @@ -268,9 +268,9 @@ _ol_xml_.makeObjectPropertySetter = function(valueReader, opt_property, opt_this _ol_xml_.makeChildAppender = function(nodeWriter, opt_this) { return function(node, value, objectStack) { nodeWriter.call(opt_this !== undefined ? opt_this : this, - node, value, objectStack); - var parent = objectStack[objectStack.length - 1]; - var parentNode = parent.node; + node, value, objectStack); + const parent = objectStack[objectStack.length - 1]; + const parentNode = parent.node; parentNode.appendChild(node); }; }; @@ -290,11 +290,11 @@ _ol_xml_.makeChildAppender = function(nodeWriter, opt_this) { * @template T, V */ _ol_xml_.makeArraySerializer = function(nodeWriter, opt_this) { - var serializersNS, nodeFactory; + let serializersNS, nodeFactory; return function(node, value, objectStack) { if (serializersNS === undefined) { serializersNS = {}; - var serializers = {}; + const serializers = {}; serializers[node.localName] = nodeWriter; serializersNS[node.namespaceURI] = serializers; nodeFactory = _ol_xml_.makeSimpleNodeFactory(node.localName); @@ -318,7 +318,7 @@ _ol_xml_.makeArraySerializer = function(nodeWriter, opt_this) { * @return {function(*, Array.<*>, string=): (Node|undefined)} Node factory. */ _ol_xml_.makeSimpleNodeFactory = function(opt_nodeName, opt_namespaceURI) { - var fixedNodeName = opt_nodeName; + const fixedNodeName = opt_nodeName; return ( /** * @param {*} value Value. @@ -327,13 +327,13 @@ _ol_xml_.makeSimpleNodeFactory = function(opt_nodeName, opt_namespaceURI) { * @return {Node} Node. */ function(value, objectStack, opt_nodeName) { - var context = objectStack[objectStack.length - 1]; - var node = context.node; - var nodeName = fixedNodeName; + const context = objectStack[objectStack.length - 1]; + const node = context.node; + let nodeName = fixedNodeName; if (nodeName === undefined) { nodeName = opt_nodeName; } - var namespaceURI = opt_namespaceURI; + let namespaceURI = opt_namespaceURI; if (opt_namespaceURI === undefined) { namespaceURI = node.namespaceURI; } @@ -366,9 +366,9 @@ _ol_xml_.OBJECT_PROPERTY_NODE_FACTORY = _ol_xml_.makeSimpleNodeFactory(); * @template V */ _ol_xml_.makeSequence = function(object, orderedKeys) { - var length = orderedKeys.length; - var sequence = new Array(length); - for (var i = 0; i < length; ++i) { + const length = orderedKeys.length; + const sequence = new Array(length); + for (let i = 0; i < length; ++i) { sequence[i] = object[orderedKeys[i]]; } return sequence; @@ -389,8 +389,8 @@ _ol_xml_.makeStructureNS = function(namespaceURIs, structure, opt_structureNS) { /** * @type {Object.} */ - var structureNS = opt_structureNS !== undefined ? opt_structureNS : {}; - var i, ii; + const structureNS = opt_structureNS !== undefined ? opt_structureNS : {}; + let i, ii; for (i = 0, ii = namespaceURIs.length; i < ii; ++i) { structureNS[namespaceURIs[i]] = structure; } @@ -407,11 +407,11 @@ _ol_xml_.makeStructureNS = function(namespaceURIs, structure, opt_structureNS) { * @param {*=} opt_this The object to use as `this`. */ _ol_xml_.parseNode = function(parsersNS, node, objectStack, opt_this) { - var n; + let n; for (n = node.firstElementChild; n; n = n.nextElementSibling) { - var parsers = parsersNS[n.namespaceURI]; + const parsers = parsersNS[n.namespaceURI]; if (parsers !== undefined) { - var parser = parsers[n.localName]; + const parser = parsers[n.localName]; if (parser !== undefined) { parser.call(opt_this, n, objectStack); } @@ -432,7 +432,7 @@ _ol_xml_.parseNode = function(parsersNS, node, objectStack, opt_this) { * @template T */ _ol_xml_.pushParseAndPop = function( - object, parsersNS, node, objectStack, opt_this) { + object, parsersNS, node, objectStack, opt_this) { objectStack.push(object); _ol_xml_.parseNode(parsersNS, node, objectStack, opt_this); return objectStack.pop(); @@ -462,17 +462,17 @@ _ol_xml_.pushParseAndPop = function( * @template T */ _ol_xml_.serialize = function( - serializersNS, nodeFactory, values, objectStack, opt_keys, opt_this) { - var length = (opt_keys !== undefined ? opt_keys : values).length; - var value, node; - for (var i = 0; i < length; ++i) { + serializersNS, nodeFactory, values, objectStack, opt_keys, opt_this) { + const length = (opt_keys !== undefined ? opt_keys : values).length; + let value, node; + for (let i = 0; i < length; ++i) { value = values[i]; if (value !== undefined) { node = nodeFactory.call(opt_this, value, objectStack, - opt_keys !== undefined ? opt_keys[i] : undefined); + opt_keys !== undefined ? opt_keys[i] : undefined); if (node !== undefined) { serializersNS[node.namespaceURI][node.localName] - .call(opt_this, node, value, objectStack); + .call(opt_this, node, value, objectStack); } } } @@ -503,10 +503,10 @@ _ol_xml_.serialize = function( * @template O, T */ _ol_xml_.pushSerializeAndPop = function(object, - serializersNS, nodeFactory, values, objectStack, opt_keys, opt_this) { + serializersNS, nodeFactory, values, objectStack, opt_keys, opt_this) { objectStack.push(object); _ol_xml_.serialize( - serializersNS, nodeFactory, values, objectStack, opt_keys, opt_this); + serializersNS, nodeFactory, values, objectStack, opt_keys, opt_this); return objectStack.pop(); }; export default _ol_xml_; diff --git a/tasks/generate-exports.js b/tasks/generate-exports.js index 4ab5e1733d..7b85e93554 100644 --- a/tasks/generate-exports.js +++ b/tasks/generate-exports.js @@ -1,9 +1,9 @@ -var fs = require('fs-extra'); +const fs = require('fs-extra'); -var async = require('async'); -var nomnom = require('nomnom'); +const async = require('async'); +const nomnom = require('nomnom'); -var generateInfo = require('./generate-info'); +const generateInfo = require('./generate-info'); /** @@ -21,19 +21,19 @@ function getConfig(configPath, callback) { callback(err); return; } - var obj; + let obj; try { obj = JSON.parse(String(data)); } catch (err2) { callback(new Error('Trouble parsing file as JSON: ' + configPath)); return; } - var patterns = obj.exports; + const patterns = obj.exports; if (patterns && !Array.isArray(patterns)) { callback(new Error('Expected an exports array, got: ' + patterns)); return; } - var namespace = obj.namespace; + const namespace = obj.namespace; if (namespace && typeof namespace !== 'string') { callback(new Error('Expected an namespace string, got: ' + namespace)); @@ -61,7 +61,7 @@ function getSymbols(patterns, callback) { callback(new Error('Trouble generating info: ' + err.message)); return; } - var symbols = require('../build/info.json').symbols; + const symbols = require('../build/info.json').symbols; callback(null, patterns, symbols); }); } @@ -80,10 +80,10 @@ function getSymbols(patterns, callback) { * the filtered list of symbols and a list of all provides (or any error). */ function filterSymbols(patterns, symbols, callback) { - var matches = []; + const matches = []; - var provides = {}; - var lookup = {}; + const provides = {}; + const lookup = {}; symbols.forEach(function(symbol) { lookup[symbol.name] = symbol; symbol.provides.forEach(function(provide) { @@ -92,8 +92,8 @@ function filterSymbols(patterns, symbols, callback) { }); patterns.forEach(function(name) { - var match = false; - var pattern = (name.substr(-1) === '*'); + let match = false; + const pattern = (name.substr(-1) === '*'); if (pattern) { name = name.substr(0, name.length - 1); symbols.forEach(function(symbol) { @@ -103,14 +103,14 @@ function filterSymbols(patterns, symbols, callback) { } }); } else { - var symbol = lookup[name]; + const symbol = lookup[name]; if (symbol) { matches.push(symbol); match = true; } } if (!match) { - var message = 'No matching symbol found: ' + name + (pattern ? '*' : ''); + const message = 'No matching symbol found: ' + name + (pattern ? '*' : ''); callback(new Error(message)); } }); @@ -140,9 +140,9 @@ function formatSymbolExport(name, namespace) { * @return {string} Export code. */ function formatPropertyExport(name) { - var parts = name.split('#'); - var prototype = parts[0] + '.prototype'; - var property = parts[1]; + const parts = name.split('#'); + const prototype = parts[0] + '.prototype'; + const property = parts[1]; return 'goog.exportProperty(\n' + ' ' + prototype + ',\n' + ' \'' + property + '\',\n' + @@ -158,13 +158,13 @@ function formatPropertyExport(name) { * @return {string} Export code. */ function generateExports(symbols, namespace, provides) { - var blocks = []; + const blocks = []; provides.forEach(function(provide) { blocks.push('goog.require(\'' + provide + '\');'); }); blocks.push('\n\n'); symbols.forEach(function(symbol) { - var name = symbol.name; + const name = symbol.name; if (name.indexOf('#') > 0) { blocks.push(formatPropertyExport(name)); } else { @@ -172,7 +172,7 @@ function generateExports(symbols, namespace, provides) { } }); blocks.unshift( - '/**\n' + + '/**\n' + ' * @fileoverview Custom exports file.\n' + ' * @suppress {checkVars,extraRequire}\n' + ' */\n'); @@ -192,7 +192,7 @@ function main(config, callback) { getSymbols.bind(null, config.exports), filterSymbols, function(symbols, provides, done) { - var code, err; + let code, err; try { code = generateExports(symbols, config.namespace, provides); } catch (e) { @@ -209,7 +209,7 @@ function main(config, callback) { * function, and write the output file. */ if (require.main === module) { - var options = nomnom.options({ + const options = nomnom.options({ output: { position: 0, required: true, diff --git a/tasks/generate-externs.js b/tasks/generate-externs.js index 8201b56d48..79a81e8393 100644 --- a/tasks/generate-externs.js +++ b/tasks/generate-externs.js @@ -1,10 +1,10 @@ -var async = require('async'); -var fs = require('fs-extra'); -var nomnom = require('nomnom'); +const async = require('async'); +const fs = require('fs-extra'); +const nomnom = require('nomnom'); -var generateInfo = require('./generate-info'); +const generateInfo = require('./generate-info'); -var googRegEx = /^goog\..*$/; +const googRegEx = /^goog\..*$/; /** * Read the symbols from info file. @@ -17,7 +17,7 @@ function getInfo(callback) { callback(new Error('Trouble generating info: ' + err.message)); return; } - var info = require('../build/info.json'); + const info = require('../build/info.json'); callback(null, info.typedefs, info.symbols, info.externs, info.base); }); } @@ -33,18 +33,18 @@ function getInfo(callback) { * @return {string} Export code. */ function generateExterns(typedefs, symbols, externs, base) { - var lines = []; - var processedSymbols = {}; - var constructors = {}; - var constructorOptionsTypes = {}; + const lines = []; + const processedSymbols = {}; + const constructors = {}; + const constructorOptionsTypes = {}; function addNamespaces(name) { - var parts = name.split('.'); + const parts = name.split('.'); parts.pop(); - var namespace = []; + const namespace = []; parts.forEach(function(part) { namespace.push(part); - var partialNamespace = namespace.join('.'); + const partialNamespace = namespace.join('.'); if (!(partialNamespace in processedSymbols || partialNamespace in constructors)) { lines.push('/**'); @@ -77,10 +77,10 @@ function generateExterns(typedefs, symbols, externs, base) { function processSymbol(symbol) { addNamespaces(symbol.name.split('#')[0]); - var name = symbol.name; + let name = symbol.name; if (name.indexOf('#') > 0) { name = symbol.name.replace('#', '.prototype.'); - var constructor = symbol.name.split('#')[0]; + const constructor = symbol.name.split('#')[0]; if (!(constructor in constructors)) { constructors[constructor] = true; lines.push('/**'); @@ -102,7 +102,7 @@ function generateExterns(typedefs, symbols, externs, base) { if (symbol.types) { lines.push(' * @type {' + symbol.types.join('|') + '}'); } - var args = []; + const args = []; if (symbol.params) { symbol.params.forEach(function(param) { findConstructorOptionsTypes(param.types); @@ -183,7 +183,7 @@ function main(callback) { async.waterfall([ getInfo, function(typedefs, symbols, externs, base, done) { - var code, err; + let code, err; try { code = generateExterns(typedefs, symbols, externs, base); } catch (e) { @@ -200,7 +200,7 @@ function main(callback) { * function, and write the output file. */ if (require.main === module) { - var options = nomnom.options({ + const options = nomnom.options({ output: { position: 0, required: true, diff --git a/tasks/generate-info.js b/tasks/generate-info.js index a5e7fba30a..089f203415 100644 --- a/tasks/generate-info.js +++ b/tasks/generate-info.js @@ -1,18 +1,18 @@ -var fs = require('fs-extra'); -var path = require('path'); -var spawn = require('child_process').spawn; +const fs = require('fs-extra'); +const path = require('path'); +const spawn = require('child_process').spawn; -var async = require('async'); -var walk = require('walk').walk; -var isWindows = process.platform.indexOf('win') === 0; +const async = require('async'); +const walk = require('walk').walk; +const isWindows = process.platform.indexOf('win') === 0; -var sourceDir = path.join(__dirname, '..', 'src'); -var externsDir = path.join(__dirname, '..', 'externs'); -var externsPaths = [ +const sourceDir = path.join(__dirname, '..', 'src'); +const externsDir = path.join(__dirname, '..', 'externs'); +const externsPaths = [ path.join(externsDir, 'olx.js'), path.join(externsDir, 'geojson.js') ]; -var infoPath = path.join(__dirname, '..', 'build', 'info.json'); +const infoPath = path.join(__dirname, '..', 'build', 'info.json'); /** * Get checked path of a binary. @@ -24,14 +24,14 @@ function getBinaryPath(binaryName) { binaryName += '.cmd'; } - var jsdocResolved = require.resolve('jsdoc/jsdoc.js'); - var expectedPaths = [ + const jsdocResolved = require.resolve('jsdoc/jsdoc.js'); + const expectedPaths = [ path.join(__dirname, '..', 'node_modules', '.bin', binaryName), path.resolve(path.join(path.dirname(jsdocResolved), '..', '.bin', binaryName)) ]; - for (var i = 0; i < expectedPaths.length; i++) { - var expectedPath = expectedPaths[i]; + for (let i = 0; i < expectedPaths.length; i++) { + const expectedPath = expectedPaths[i]; if (fs.existsSync(expectedPath)) { return expectedPath; } @@ -40,10 +40,10 @@ function getBinaryPath(binaryName) { throw Error('JsDoc binary was not found in any of the expected paths: ' + expectedPaths); } -var jsdoc = getBinaryPath('jsdoc'); +const jsdoc = getBinaryPath('jsdoc'); -var jsdocConfig = path.join( - __dirname, '..', 'config', 'jsdoc', 'info', 'conf.json'); +const jsdocConfig = path.join( + __dirname, '..', 'config', 'jsdoc', 'info', 'conf.json'); /** @@ -74,10 +74,10 @@ function getInfoTime(callback) { * whether any externs are newer than that date. */ function getNewerExterns(date, callback) { - var newer = false; - var walker = walk(externsDir); + let newer = false; + const walker = walk(externsDir); walker.on('file', function(root, stats, next) { - var sourcePath = path.join(root, stats.name); + const sourcePath = path.join(root, stats.name); externsPaths.forEach(function(path) { if (sourcePath === path && stats.mtime > date) { newer = true; @@ -103,11 +103,11 @@ function getNewerExterns(date, callback) { * error and the array of source paths (empty if none newer). */ function getNewer(date, newer, callback) { - var paths = [].concat(externsPaths); + let paths = [].concat(externsPaths); - var walker = walk(sourceDir); + const walker = walk(sourceDir); walker.on('file', function(root, stats, next) { - var sourcePath = path.join(root, stats.name); + const sourcePath = path.join(root, stats.name); if (/\.js$/.test(sourcePath)) { paths.push(sourcePath); if (stats.mtime > date) { @@ -146,7 +146,7 @@ function parseOutput(output) { throw new Error('Expected JSON output'); } - var info; + let info; try { info = JSON.parse(String(output)); } catch (err) { @@ -178,10 +178,10 @@ function spawnJSDoc(paths, callback) { return; } - var output = ''; - var errors = ''; - var cwd = path.join(__dirname, '..'); - var child = spawn(jsdoc, ['-c', jsdocConfig].concat(paths), {cwd: cwd}); + let output = ''; + let errors = ''; + const cwd = path.join(__dirname, '..'); + const child = spawn(jsdoc, ['-c', jsdocConfig].concat(paths), {cwd: cwd}); child.stdout.on('data', function(data) { output += String(data); @@ -195,7 +195,7 @@ function spawnJSDoc(paths, callback) { if (code) { callback(new Error(errors || 'JSDoc failed with no output')); } else { - var info; + let info; try { info = parseOutput(output); } catch (err) { @@ -214,16 +214,16 @@ function spawnJSDoc(paths, callback) { * @param {function(Error, Array.)} callback Called with a list of * provides or any error. */ -var getProvides = async.memoize(function(srcPath, callback) { +const getProvides = async.memoize(function(srcPath, callback) { fs.readFile(srcPath, function(err, data) { if (err) { callback(err); return; } - var provides = []; - var matcher = /goog\.provide\('(.*)'\)/; + const provides = []; + const matcher = /goog\.provide\('(.*)'\)/; String(data).split('\n').forEach(function(line) { - var match = line.match(matcher); + const match = line.match(matcher); if (match) { provides.push(match[1]); } @@ -271,7 +271,7 @@ function addSymbolProvides(info, callback) { */ function writeInfo(info, callback) { if (info) { - var str = JSON.stringify(info, null, ' '); + const str = JSON.stringify(info, null, ' '); fs.outputFile(infoPath, str, callback); } else { process.nextTick(function() { diff --git a/tasks/glslunit.js b/tasks/glslunit.js index 236719951c..a81342c9a9 100644 --- a/tasks/glslunit.js +++ b/tasks/glslunit.js @@ -25,17 +25,17 @@ function glsl_compress(s, shortNames) { s = s.replace(/\s+/g, ' '); // remove whitespace between non-word tokens s = s.replace(/(\S)\s+([^\w])/g, '$1$2') - .replace(/([^\w])\s+(\S)/g, '$1$2'); + .replace(/([^\w])\s+(\S)/g, '$1$2'); // replace original names with short names - for (var originalName in shortNames) { + for (const originalName in shortNames) { s = s.replace(new RegExp(originalName, 'gm'), shortNames[originalName]); } return s; } function main(argv) { - var options = {}; - for (var i = 2, ii = argv.length; i < ii; i += 2) { + const options = {}; + for (let i = 2, ii = argv.length; i < ii; i += 2) { options[argv[i].replace(/^../, '')] = argv[i + 1]; } if (!options.input) { diff --git a/test/rendering/ol/layer/clip.test.js b/test/rendering/ol/layer/clip.test.js index f179e8c3d9..567543a7e6 100644 --- a/test/rendering/ol/layer/clip.test.js +++ b/test/rendering/ol/layer/clip.test.js @@ -10,9 +10,9 @@ import Style from '../../../../src/ol/style/Style.js'; describe('layer clipping', function() { function onLoad(source, callback) { - var loading = 0; - var loaded = 0; - var called = false; + let loading = 0; + let loaded = 0; + let called = false; function check() { if (!called && loading > 0 && loaded === loading) { @@ -36,7 +36,7 @@ describe('layer clipping', function() { describe('MultiPolygon clipping', function() { - var map = null; + let map = null; beforeEach(function() { map = new Map({ pixelRatio: 1, @@ -55,21 +55,21 @@ describe('layer clipping', function() { it('clips to all parts of the MultiPolygon', function(done) { - var source = new XYZ({ + const source = new XYZ({ url: 'rendering/ol/data/tiles/osm/{z}/{x}/{y}.png', transition: 0 }); - var layer = new TileLayer({ + const layer = new TileLayer({ source: source }); - var geometry = new MultiPolygon([ + const geometry = new MultiPolygon([ [[[-80, -40], [-40, 0], [-80, 40], [-120, 0], [-80, -40]]], [[[80, -40], [120, 0], [80, 40], [40, 0], [80, -40]]] ]).transform('EPSG:4326', 'EPSG:3857'); - var style = new Style({ + const style = new Style({ stroke: new Stroke({ width: 2, color: 'blue' @@ -77,10 +77,10 @@ describe('layer clipping', function() { }); layer.on('precompose', function(event) { - var context = event.context; + const context = event.context; context.save(); - var vectorContext = event.vectorContext; + const vectorContext = event.vectorContext; vectorContext.setStyle(style); vectorContext.drawGeometry(geometry); @@ -88,10 +88,10 @@ describe('layer clipping', function() { }); layer.on('postcompose', function(event) { - var context = event.context; + const context = event.context; context.restore(); - var vectorContext = event.vectorContext; + const vectorContext = event.vectorContext; vectorContext.setStyle(style); vectorContext.drawGeometry(geometry); }); diff --git a/test/rendering/ol/layer/image.test.js b/test/rendering/ol/layer/image.test.js index 4d7f9343ff..b7929c1c55 100644 --- a/test/rendering/ol/layer/image.test.js +++ b/test/rendering/ol/layer/image.test.js @@ -9,7 +9,7 @@ import _ol_tilegrid_ from '../../../../src/ol/tilegrid.js'; describe('ol.rendering.layer.Image', function() { - var map; + let map; function createMap(renderer) { map = new Map({ @@ -18,7 +18,7 @@ describe('ol.rendering.layer.Image', function() { renderer: renderer, view: new View({ center: transform( - [-122.416667, 37.783333], 'EPSG:4326', 'EPSG:3857'), + [-122.416667, 37.783333], 'EPSG:4326', 'EPSG:3857'), zoom: 5 }) }); @@ -32,10 +32,10 @@ describe('ol.rendering.layer.Image', function() { }); function waitForImages(sources, layerOptions, onImagesLoaded) { - var imagesLoading = 0; - var imagesLoaded = 0; + let imagesLoading = 0; + let imagesLoaded = 0; - var update = function() { + const update = function() { if (imagesLoading === imagesLoaded) { onImagesLoaded(); } @@ -53,7 +53,7 @@ describe('ol.rendering.layer.Image', function() { expect().fail('Image failed to load'); }); - var options = { + const options = { source: source }; _ol_obj_.assign(options, layerOptions); @@ -62,13 +62,13 @@ describe('ol.rendering.layer.Image', function() { } describe('single image layer', function() { - var source; + let source; beforeEach(function() { source = new Static({ url: 'rendering/ol/data/tiles/osm/5/5/12.png', imageExtent: _ol_tilegrid_.createXYZ().getTileCoordExtent( - [5, 5, -12 - 1]), + [5, 5, -12 - 1]), projection: getProjection('EPSG:3857') }); }); @@ -77,7 +77,7 @@ describe('ol.rendering.layer.Image', function() { createMap('canvas'); waitForImages([source], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/image-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -86,19 +86,19 @@ describe('ol.rendering.layer.Image', function() { createMap('webgl'); waitForImages([source], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/image-webgl.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); }); describe('single image layer - scaled', function() { - var source; + let source; beforeEach(function() { source = new Static({ url: 'rendering/ol/data/tiles/osm/5/5/12.png', imageExtent: transformExtent( - [-123, 37, -122, 38], 'EPSG:4326', 'EPSG:3857') + [-123, 37, -122, 38], 'EPSG:4326', 'EPSG:3857') }); }); @@ -106,7 +106,7 @@ describe('ol.rendering.layer.Image', function() { createMap('canvas'); waitForImages([source], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/image-scaled.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); }); diff --git a/test/rendering/ol/layer/tile.test.js b/test/rendering/ol/layer/tile.test.js index d3b2c3783e..da11991f08 100644 --- a/test/rendering/ol/layer/tile.test.js +++ b/test/rendering/ol/layer/tile.test.js @@ -15,10 +15,10 @@ import _ol_tilegrid_ from '../../../../src/ol/tilegrid.js'; describe('ol.rendering.layer.Tile', function() { - var map; + let map; function createMap(renderer, opt_center, opt_size, opt_pixelRatio, opt_resolutions) { - var size = opt_size !== undefined ? opt_size : [50, 50]; + const size = opt_size !== undefined ? opt_size : [50, 50]; map = new Map({ pixelRatio: opt_pixelRatio || 1, @@ -26,7 +26,7 @@ describe('ol.rendering.layer.Tile', function() { renderer: renderer, view: new View({ center: opt_center !== undefined ? opt_center : transform( - [-122.416667, 37.783333], 'EPSG:4326', 'EPSG:3857'), + [-122.416667, 37.783333], 'EPSG:4326', 'EPSG:3857'), resolutions: opt_resolutions, zoom: 5 }) @@ -41,10 +41,10 @@ describe('ol.rendering.layer.Tile', function() { }); function waitForTiles(sources, layerOptions, onTileLoaded) { - var tilesLoading = 0; - var tileLoaded = 0; + let tilesLoading = 0; + let tileLoaded = 0; - var update = function() { + const update = function() { if (tilesLoading === tileLoaded) { onTileLoaded(); } @@ -62,7 +62,7 @@ describe('ol.rendering.layer.Tile', function() { expect().fail('Tile failed to load'); }); - var options = { + const options = { source: source }; _ol_obj_.assign(options, layerOptions[i] || layerOptions); @@ -73,20 +73,20 @@ describe('ol.rendering.layer.Tile', function() { describe('with tile transition', function() { it('renders correctly after the transition', function(done) { createMap('canvas'); - var source = new XYZ({ + const source = new XYZ({ url: 'rendering/ol/data/tiles/osm/{z}/{x}/{y}.png' }); waitForTiles([source], {}, function() { setTimeout(function() { expectResemble(map, 'rendering/ol/layer/expected/osm-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }, 500); }); }); }); describe('single tile layer', function() { - var source; + let source; beforeEach(function() { source = new XYZ({ @@ -99,7 +99,7 @@ describe('ol.rendering.layer.Tile', function() { createMap('canvas'); waitForTiles([source], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/osm-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -108,13 +108,13 @@ describe('ol.rendering.layer.Tile', function() { createMap('webgl'); waitForTiles([source], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/osm-webgl.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); }); describe('two tile layers', function() { - var source1, source2; + let source1, source2; beforeEach(function() { source1 = new XYZ({ @@ -131,7 +131,7 @@ describe('ol.rendering.layer.Tile', function() { createMap('canvas'); waitForTiles([source1, source2], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/2-layers-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -140,14 +140,14 @@ describe('ol.rendering.layer.Tile', function() { createMap('webgl'); waitForTiles([source1, source2], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/2-layers-webgl.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); function centerExtent(map) { - var c = map.getView().calculateExtent(map.getSize()); - var qw = _ol_extent_.getSize(c)[0] / 4; - var qh = _ol_extent_.getSize(c)[1] / 4; + const c = map.getView().calculateExtent(map.getSize()); + const qw = _ol_extent_.getSize(c)[0] / 4; + const qh = _ol_extent_.getSize(c)[1] / 4; return [c[0] + qw, c[1] + qh, c[2] - qw, c[3] - qh]; } @@ -155,7 +155,7 @@ describe('ol.rendering.layer.Tile', function() { createMap('canvas'); waitForTiles([source1, source2], [{}, {extent: centerExtent(map)}], function() { expectResemble(map, 'rendering/ol/layer/expected/2-layers-canvas-extent.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -164,7 +164,7 @@ describe('ol.rendering.layer.Tile', function() { map.getView().setRotation(Math.PI / 2); waitForTiles([source1, source2], [{}, {extent: centerExtent(map)}], function() { expectResemble(map, 'rendering/ol/layer/expected/2-layers-canvas-extent-rotate.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -172,7 +172,7 @@ describe('ol.rendering.layer.Tile', function() { createMap('canvas', undefined, undefined, 2); waitForTiles([source1, source2], [{}, {extent: centerExtent(map)}], function() { expectResemble(map, 'rendering/ol/layer/expected/2-layers-canvas-extent-hidpi.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -181,14 +181,14 @@ describe('ol.rendering.layer.Tile', function() { map.getView().setRotation(Math.PI / 2); waitForTiles([source1, source2], [{}, {extent: centerExtent(map)}], function() { expectResemble(map, 'rendering/ol/layer/expected/2-layers-canvas-extent-rotate-hidpi.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); }); describe('tile layer with opacity', function() { - var source; + let source; beforeEach(function() { source = new XYZ({ @@ -201,7 +201,7 @@ describe('ol.rendering.layer.Tile', function() { createMap('canvas'); waitForTiles([source], {opacity: 0.2}, function() { expectResemble(map, 'rendering/ol/layer/expected/opacity-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -210,7 +210,7 @@ describe('ol.rendering.layer.Tile', function() { createMap('webgl'); waitForTiles([source], {opacity: 0.2}, function() { expectResemble(map, 'rendering/ol/layer/expected/opacity-webgl.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); }); @@ -228,48 +228,48 @@ describe('ol.rendering.layer.Tile', function() { } it('512x256 renders correcly using the canvas renderer', function(done) { - var source = createSource('512x256'); + const source = createSource('512x256'); createMap('canvas', [-10997148, 4569099]); waitForTiles([source], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/512x256-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); where('WebGL').it('512x256 renders correcly using the webgl renderer', function(done) { assertWebGL(); - var source = createSource('512x256'); + const source = createSource('512x256'); createMap('webgl', [-10997148, 4569099]); waitForTiles([source], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/512x256-webgl.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); it('192x256 renders correcly using the canvas renderer', function(done) { - var source = createSource('192x256'); + const source = createSource('192x256'); createMap('canvas', [-11271098, 3747248], [100, 100], undefined, - source.getTileGrid().getResolutions()); + source.getTileGrid().getResolutions()); waitForTiles([source], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/192x256-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); where('WebGL').it('192x256 renders correcly using the webgl renderer', function(done) { assertWebGL(); - var source = createSource('192x256'); + const source = createSource('192x256'); createMap('webgl', [-11271098, 3747248], [100, 100], undefined, - source.getTileGrid().getResolutions()); + source.getTileGrid().getResolutions()); waitForTiles([source], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/192x256-webgl.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); }); describe('tile layer with render listener', function() { - var source, onAddLayer; + let source, onAddLayer; beforeEach(function() { source = new XYZ({ @@ -285,7 +285,7 @@ describe('ol.rendering.layer.Tile', function() { stroke: new Stroke({color: 'red', width: 1}) })); e.vectorContext.drawPoint(new Point( - transform([-123, 38], 'EPSG:4326', 'EPSG:3857'))); + transform([-123, 38], 'EPSG:4326', 'EPSG:3857'))); }); }; }); @@ -295,7 +295,7 @@ describe('ol.rendering.layer.Tile', function() { map.getLayers().on('add', onAddLayer); waitForTiles([source], {}, function() { expectResemble(map, 'rendering/ol/layer/expected/render-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); }); diff --git a/test/rendering/ol/layer/vector.test.js b/test/rendering/ol/layer/vector.test.js index b8e2e35a52..ce3a1ac883 100644 --- a/test/rendering/ol/layer/vector.test.js +++ b/test/rendering/ol/layer/vector.test.js @@ -17,9 +17,9 @@ import Text from '../../../../src/ol/style/Text.js'; describe('ol.rendering.layer.Vector', function() { - var center = [1825927.7316762917, 6143091.089223046]; + const center = [1825927.7316762917, 6143091.089223046]; - var map; + let map; function createMap(renderer) { map = new Map({ pixelRatio: 1, @@ -39,7 +39,7 @@ describe('ol.rendering.layer.Vector', function() { map = null; }); - var source; + let source; function addCircle(r) { source.addFeature(new Feature(new Circle(center, r))); @@ -75,7 +75,7 @@ describe('ol.rendering.layer.Vector', function() { it('renders opacity correctly with the canvas renderer', function(done) { createMap('canvas'); - var smallLine = new Feature(new LineString([ + const smallLine = new Feature(new LineString([ [center[0], center[1] - 1], [center[0], center[1] + 1] ])); @@ -95,13 +95,13 @@ describe('ol.rendering.layer.Vector', function() { })); map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas.png', - 17, done); + 17, done); }); }); it('renders opacity correctly with renderMode: \'image\'', function(done) { createMap('canvas'); - var smallLine = new Feature(new LineString([ + const smallLine = new Feature(new LineString([ [center[0], center[1] - 1], [center[0], center[1] + 1] ])); @@ -122,13 +122,13 @@ describe('ol.rendering.layer.Vector', function() { })); map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas.png', - 17, done); + 17, done); }); }); it('renders transparent layers correctly with the canvas renderer', function(done) { createMap('canvas'); - var smallLine = new Feature(new LineString([ + const smallLine = new Feature(new LineString([ [center[0], center[1] - 1], [center[0], center[1] + 1] ])); @@ -141,7 +141,7 @@ describe('ol.rendering.layer.Vector', function() { }) ]); source.addFeature(smallLine); - var smallLine2 = new Feature(new LineString([ + const smallLine2 = new Feature(new LineString([ [center[0], center[1] - 1000], [center[0], center[1] + 1000] ])); @@ -161,13 +161,13 @@ describe('ol.rendering.layer.Vector', function() { })); map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-transparent.png', - 7, done); + 7, done); }); }); it('renders transparent layers correctly with renderMode: \'image\'', function(done) { createMap('canvas'); - var smallLine = new Feature(new LineString([ + const smallLine = new Feature(new LineString([ [center[0], center[1] - 1], [center[0], center[1] + 1] ])); @@ -180,7 +180,7 @@ describe('ol.rendering.layer.Vector', function() { }) ]); source.addFeature(smallLine); - var smallLine2 = new Feature(new LineString([ + const smallLine2 = new Feature(new LineString([ [center[0], center[1] - 1000], [center[0], center[1] + 1000] ])); @@ -201,7 +201,7 @@ describe('ol.rendering.layer.Vector', function() { })); map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-transparent.png', - 7, done); + 7, done); }); }); @@ -221,7 +221,7 @@ describe('ol.rendering.layer.Vector', function() { })); map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-rotated.png', - 1.7, done); + 1.7, done); }); }); @@ -242,7 +242,7 @@ describe('ol.rendering.layer.Vector', function() { })); map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-rotated.png', - 2.9, done); + 2.9, done); }); }); @@ -268,7 +268,7 @@ describe('ol.rendering.layer.Vector', function() { map.unskipFeature(source.getFeatures()[1]); map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -294,7 +294,7 @@ describe('ol.rendering.layer.Vector', function() { })); map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-opaque.png', - 24.34, done); + 24.34, done); }); }); @@ -318,13 +318,13 @@ describe('ol.rendering.layer.Vector', function() { })); map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-stroke.png', - 7, done); + 7, done); }); }); it('interrupts fill/stroke batches correctly with the canvas renderer', function(done) { createMap('canvas'); - var color; + let color; function createSource(overlaps) { color = '#3399CC'; source = new VectorSource({ @@ -346,7 +346,7 @@ describe('ol.rendering.layer.Vector', function() { } return color; } - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: createSource(true), style: function(feature) { alternateColor(); @@ -363,9 +363,9 @@ describe('ol.rendering.layer.Vector', function() { }); map.addLayer(layer); map.once('postrender', function() { - var canvas = map.getRenderer().canvas_; + const canvas = map.getRenderer().canvas_; // take a snapshot of this `overlaps: true` image - var referenceImage = canvas.toDataURL('image/png'); + const referenceImage = canvas.toDataURL('image/png'); // now render the same with `overlaps: false` layer.setSource(createSource(false)); // result should be the same as with `overlaps: true` @@ -377,7 +377,7 @@ describe('ol.rendering.layer.Vector', function() { it('interrupts stroke batches correctly with the canvas renderer', function(done) { createMap('canvas'); - var color; + let color; function createSource(overlaps) { color = '#3399CC'; source = new VectorSource({ @@ -397,7 +397,7 @@ describe('ol.rendering.layer.Vector', function() { } return color; } - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: createSource(true), style: function(feature) { alternateColor(); @@ -414,9 +414,9 @@ describe('ol.rendering.layer.Vector', function() { }); map.addLayer(layer); map.once('postrender', function() { - var canvas = map.getRenderer().canvas_; + const canvas = map.getRenderer().canvas_; // take a snapshot of this `overlaps: true` image - var referenceImage = canvas.toDataURL('image/png'); + const referenceImage = canvas.toDataURL('image/png'); // now render the same with `overlaps: false` layer.setSource(createSource(false)); // result should be exactly the same as with `overlaps: true` @@ -429,7 +429,7 @@ describe('ol.rendering.layer.Vector', function() { describe('polygon rendering', function() { - var map2; + let map2; beforeEach(function() { map2 = new Map({ pixelRatio: 1, @@ -447,7 +447,7 @@ describe('ol.rendering.layer.Vector', function() { }); it('renders a feature that spans the world', function(done) { - var json = { + const json = { type: 'Feature', geometry: { type: 'Polygon', @@ -463,10 +463,10 @@ describe('ol.rendering.layer.Vector', function() { properties: {} }; - var format = new GeoJSON({featureProjection: 'EPSG:3857'}); - var feature = format.readFeature(json); + const format = new GeoJSON({featureProjection: 'EPSG:3857'}); + const feature = format.readFeature(json); - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: new VectorSource({ features: [feature] }), @@ -489,10 +489,10 @@ describe('ol.rendering.layer.Vector', function() { describe('Polygon simplification', function() { - var layer, map3; + let layer, map3; beforeEach(function() { - var src = new VectorSource({ + const src = new VectorSource({ features: [ new Feature(new Polygon([[ [-22, 58], @@ -514,7 +514,7 @@ describe('ol.rendering.layer.Vector', function() { renderBuffer: 0, source: src }); - var view = new View({ + const view = new View({ center: [-9.5, 78], zoom: 2, projection: 'EPSG:4326' @@ -545,7 +545,7 @@ describe('ol.rendering.layer.Vector', function() { })); map3.once('postrender', function() { expectResemble(map3, 'rendering/ol/layer/expected/vector-canvas-simplified.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -557,7 +557,7 @@ describe('ol.rendering.layer.Vector', function() { })); map3.once('postrender', function() { expectResemble(map3, 'rendering/ol/layer/expected/vector-canvas-simplified-fill.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -570,7 +570,7 @@ describe('ol.rendering.layer.Vector', function() { })); map3.once('postrender', function() { expectResemble(map3, 'rendering/ol/layer/expected/vector-canvas-simplified-stroke.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -584,12 +584,12 @@ describe('ol.rendering.layer.Vector', function() { it('declutters text', function(done) { createMap('canvas'); - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: source }); map.addLayer(layer); - var centerFeature = new Feature({ + const centerFeature = new Feature({ geometry: new Point(center), text: 'center' }); @@ -614,23 +614,23 @@ describe('ol.rendering.layer.Vector', function() { }); map.once('postrender', function() { - var hitDetected = map.getFeaturesAtPixel([42, 42]); + const hitDetected = map.getFeaturesAtPixel([42, 42]); expect(hitDetected).to.have.length(1); expect(hitDetected[0]).to.equal(centerFeature); expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-declutter.png', - 2.2, done); + 2.2, done); }); }); it('declutters text with renderMode: \'image\'', function(done) { createMap('canvas'); - var layer = new VectorLayer({ + const layer = new VectorLayer({ renderMode: 'image', source: source }); map.addLayer(layer); - var centerFeature = new Feature({ + const centerFeature = new Feature({ geometry: new Point(center), text: 'center' }); @@ -655,17 +655,17 @@ describe('ol.rendering.layer.Vector', function() { }); map.once('postrender', function() { - var hitDetected = map.getFeaturesAtPixel([42, 42]); + const hitDetected = map.getFeaturesAtPixel([42, 42]); expect(hitDetected).to.have.length(1); expect(hitDetected[0]).to.equal(centerFeature); expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-declutter.png', - 2.2, done); + 2.2, done); }); }); it('declutters text and respects z-index', function(done) { createMap('canvas'); - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: source }); map.addLayer(layer); @@ -699,18 +699,18 @@ describe('ol.rendering.layer.Vector', function() { map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-declutter-zindex.png', - 3.9, done); + 3.9, done); }); }); it('declutters images', function(done) { createMap('canvas'); - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: source }); map.addLayer(layer); - var centerFeature = new Feature({ + const centerFeature = new Feature({ geometry: new Point(center) }); source.addFeature(centerFeature); @@ -734,23 +734,23 @@ describe('ol.rendering.layer.Vector', function() { }); map.once('postrender', function() { - var hitDetected = map.getFeaturesAtPixel([40, 40]); + const hitDetected = map.getFeaturesAtPixel([40, 40]); expect(hitDetected).to.have.length(1); expect(hitDetected[0]).to.equal(centerFeature); expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-declutter-image.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); it('declutters images with renderMode: \'image\'', function(done) { createMap('canvas'); - var layer = new VectorLayer({ + const layer = new VectorLayer({ renderMode: 'image', source: source }); map.addLayer(layer); - var centerFeature = new Feature({ + const centerFeature = new Feature({ geometry: new Point(center) }); source.addFeature(centerFeature); @@ -774,17 +774,17 @@ describe('ol.rendering.layer.Vector', function() { }); map.once('postrender', function() { - var hitDetected = map.getFeaturesAtPixel([40, 40]); + const hitDetected = map.getFeaturesAtPixel([40, 40]); expect(hitDetected).to.have.length(1); expect(hitDetected[0]).to.equal(centerFeature); expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-declutter-image.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); it('declutters images and respects z-index', function(done) { createMap('canvas'); - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: source }); map.addLayer(layer); @@ -817,13 +817,13 @@ describe('ol.rendering.layer.Vector', function() { map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-declutter-image-zindex.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); it('declutters image & text groups', function(done) { createMap('canvas'); - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: source }); map.addLayer(layer); @@ -861,18 +861,18 @@ describe('ol.rendering.layer.Vector', function() { map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-declutter-group.png', - 2.2, done); + 2.2, done); }); }); it('declutters text along lines and images', function(done) { createMap('canvas'); - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: source }); map.addLayer(layer); - var point = new Feature(new Point(center)); + const point = new Feature(new Point(center)); point.setStyle(new Style({ image: new CircleStyle({ radius: 8, @@ -881,7 +881,7 @@ describe('ol.rendering.layer.Vector', function() { }) }) })); - var line = new Feature(new LineString([ + const line = new Feature(new LineString([ [center[0] - 650, center[1] - 200], [center[0] + 650, center[1] - 200] ])); @@ -904,18 +904,18 @@ describe('ol.rendering.layer.Vector', function() { map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-declutter-line.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); it('declutters text along lines and images with renderMode: \'image\'', function(done) { createMap('canvas'); - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: source }); map.addLayer(layer); - var point = new Feature(new Point(center)); + const point = new Feature(new Point(center)); point.setStyle(new Style({ image: new CircleStyle({ radius: 8, @@ -924,7 +924,7 @@ describe('ol.rendering.layer.Vector', function() { }) }) })); - var line = new Feature(new LineString([ + const line = new Feature(new LineString([ [center[0] - 650, center[1] - 200], [center[0] + 650, center[1] - 200] ])); @@ -947,18 +947,18 @@ describe('ol.rendering.layer.Vector', function() { map.once('postrender', function() { expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-declutter-line.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); it('declutters text along lines and images with z-index', function(done) { createMap('canvas'); - var layer = new VectorLayer({ + const layer = new VectorLayer({ source: source }); map.addLayer(layer); - var point = new Feature(new Point(center)); + const point = new Feature(new Point(center)); point.setStyle(new Style({ zIndex: 2, image: new CircleStyle({ @@ -968,7 +968,7 @@ describe('ol.rendering.layer.Vector', function() { }) }) })); - var line = new Feature(new LineString([ + const line = new Feature(new LineString([ [center[0] - 650, center[1] - 200], [center[0] + 650, center[1] - 200] ])); @@ -991,11 +991,11 @@ describe('ol.rendering.layer.Vector', function() { layer.setDeclutter(true); map.once('postrender', function() { - var hitDetected = map.getFeaturesAtPixel([35, 46]); + const hitDetected = map.getFeaturesAtPixel([35, 46]); expect(hitDetected).to.have.length(1); expect(hitDetected[0]).to.equal(line); expectResemble(map, 'rendering/ol/layer/expected/vector-canvas-declutter-line-zindex.png', - 4.1, done); + 4.1, done); }); }); }); diff --git a/test/rendering/ol/layer/vectortile.test.js b/test/rendering/ol/layer/vectortile.test.js index afbf12b35a..93f9770237 100644 --- a/test/rendering/ol/layer/vectortile.test.js +++ b/test/rendering/ol/layer/vectortile.test.js @@ -17,10 +17,10 @@ import _ol_tilegrid_ from '../../../../src/ol/tilegrid.js'; describe('ol.rendering.layer.VectorTile', function() { - var map; + let map; function createMap(renderer, opt_pixelRatio, opt_size) { - var size = opt_size || 50; + const size = opt_size || 50; map = new Map({ pixelRatio: opt_pixelRatio || 1, target: createMapDiv(size, size), @@ -38,10 +38,10 @@ describe('ol.rendering.layer.VectorTile', function() { }); function waitForTiles(source, layerOptions, onTileLoaded) { - var tilesLoading = 0; - var tileLoaded = 0; + let tilesLoading = 0; + let tileLoaded = 0; - var update = function() { + const update = function() { if (tilesLoading === tileLoaded) { onTileLoaded(); } @@ -58,7 +58,7 @@ describe('ol.rendering.layer.VectorTile', function() { expect().fail('Tile failed to load'); }); - var options = { + const options = { source: source }; _ol_obj_.assign(options, layerOptions); @@ -66,7 +66,7 @@ describe('ol.rendering.layer.VectorTile', function() { } describe('vector tile layer', function() { - var source; + let source; beforeEach(function() { source = new VectorTileSource({ @@ -81,7 +81,7 @@ describe('ol.rendering.layer.VectorTile', function() { createMap('canvas'); waitForTiles(source, {}, function() { expectResemble(map, 'rendering/ol/layer/expected/vectortile-canvas.png', - 22, done); + 22, done); }); }); @@ -90,13 +90,13 @@ describe('ol.rendering.layer.VectorTile', function() { map.getView().setRotation(Math.PI / 4); waitForTiles(source, {}, function() { expectResemble(map, 'rendering/ol/layer/expected/vectortile-canvas-rotated.png', - 14, done); + 14, done); }); }); it('renders rotated view correctly with vector layer on top', function(done) { createMap('canvas'); - var vectorSource = new VectorSource({ + const vectorSource = new VectorSource({ features: [ new Feature(new Point([1825727.7316762917, 6143091.089223046])) ] @@ -116,7 +116,7 @@ describe('ol.rendering.layer.VectorTile', function() { map.getView().setRotation(Math.PI / 4); waitForTiles(source, {}, function() { expectResemble(map, 'rendering/ol/layer/expected/vectortile-vector-rotated.png', - 14, done); + 14, done); }); }); @@ -124,7 +124,7 @@ describe('ol.rendering.layer.VectorTile', function() { createMap('canvas', 2); waitForTiles(source, {}, function() { expectResemble(map, 'rendering/ol/layer/expected/vectortile-canvas-hidpi.png', - 11.3, done); + 11.3, done); }); }); @@ -133,15 +133,15 @@ describe('ol.rendering.layer.VectorTile', function() { map.getView().setRotation(Math.PI / 4); waitForTiles(source, {}, function() { expectResemble(map, 'rendering/ol/layer/expected/vectortile-canvas-rotated-hidpi.png', - 14.8, done); + 14.8, done); }); }); it('declutters text and images', function(done) { createMap('canvas', 1, 100); map.getView().setZoom(13.8); - var style = function(feature, resolution) { - var geom = feature.getGeometry(); + const style = function(feature, resolution) { + const geom = feature.getGeometry(); if (geom.getType() == 'Point') { return new Style({ image: new CircleStyle({ @@ -161,7 +161,7 @@ describe('ol.rendering.layer.VectorTile', function() { }; waitForTiles(source, {declutter: true, style: style}, function() { expectResemble(map, 'rendering/ol/layer/expected/vectortile-canvas-declutter.png', - 8.5, done); + 8.5, done); }); }); diff --git a/test/rendering/ol/map.test.js b/test/rendering/ol/map.test.js index 0942db006e..9e84ee11e9 100644 --- a/test/rendering/ol/map.test.js +++ b/test/rendering/ol/map.test.js @@ -8,9 +8,9 @@ import VectorSource from '../../../src/ol/source/Vector.js'; describe('ol.rendering.Map', function() { - var map; + let map; function createMap(renderer) { - var vectorLayer = new VectorLayer({ + const vectorLayer = new VectorLayer({ source: new VectorSource({ features: [new Feature({ geometry: new Point([0, 0]) @@ -43,7 +43,7 @@ describe('ol.rendering.Map', function() { it('tests the canvas renderer', function(done) { createMap('canvas'); map.once('postrender', function() { - var initialSize = map.getSize(); + const initialSize = map.getSize(); map.updateSize(); expect(map.getSize()).to.eql(initialSize); done(); @@ -54,7 +54,7 @@ describe('ol.rendering.Map', function() { assertWebGL(); createMap('webgl'); map.once('postrender', function() { - var initialSize = map.getSize(); + const initialSize = map.getSize(); map.updateSize(); expect(map.getSize()).to.eql(initialSize); done(); @@ -67,14 +67,14 @@ describe('ol.rendering.Map', function() { it('tests the canvas renderer', function(done) { createMap('canvas'); expectResemble( - map, 'rendering/ol/expected/render-canvas.png', IMAGE_TOLERANCE, done); + map, 'rendering/ol/expected/render-canvas.png', IMAGE_TOLERANCE, done); }); where('WebGL').it('tests the WebGL renderer', function(done) { assertWebGL(); createMap('webgl'); expectResemble( - map, 'rendering/ol/expected/render-webgl.png', IMAGE_TOLERANCE, done); + map, 'rendering/ol/expected/render-webgl.png', IMAGE_TOLERANCE, done); }); }); @@ -84,7 +84,7 @@ describe('ol.rendering.Map', function() { createMap('canvas'); map.getView().setCenter([10, 10]); expectResemble( - map, 'rendering/ol/expected/pan-canvas.png', IMAGE_TOLERANCE, done); + map, 'rendering/ol/expected/pan-canvas.png', IMAGE_TOLERANCE, done); }); where('WebGL').it('tests the WebGL renderer', function(done) { @@ -92,7 +92,7 @@ describe('ol.rendering.Map', function() { createMap('webgl'); map.getView().setCenter([10, 10]); expectResemble( - map, 'rendering/ol/expected/pan-webgl.png', IMAGE_TOLERANCE, done); + map, 'rendering/ol/expected/pan-webgl.png', IMAGE_TOLERANCE, done); }); }); @@ -103,7 +103,7 @@ describe('ol.rendering.Map', function() { map.getView().setRotation(90); map.getView().setCenter([10, 10]); expectResemble( - map, 'rendering/ol/expected/rotate-canvas.png', 2.8, done); + map, 'rendering/ol/expected/rotate-canvas.png', 2.8, done); }); where('WebGL').it('tests the WebGL renderer', function(done) { @@ -112,7 +112,7 @@ describe('ol.rendering.Map', function() { map.getView().setRotation(90); map.getView().setCenter([10, 10]); expectResemble( - map, 'rendering/ol/expected/rotate-webgl.png', IMAGE_TOLERANCE, done); + map, 'rendering/ol/expected/rotate-webgl.png', IMAGE_TOLERANCE, done); }); }); @@ -123,7 +123,7 @@ describe('ol.rendering.Map', function() { map.getView().setCenter([10, 10]); map.getView().setResolution(2); expectResemble( - map, 'rendering/ol/expected/zoom-canvas.png', IMAGE_TOLERANCE, done); + map, 'rendering/ol/expected/zoom-canvas.png', IMAGE_TOLERANCE, done); }); where('WebGL').it('tests the WebGL renderer', function(done) { @@ -132,7 +132,7 @@ describe('ol.rendering.Map', function() { map.getView().setCenter([10, 10]); map.getView().setResolution(2); expectResemble( - map, 'rendering/ol/expected/zoom-webgl.png', IMAGE_TOLERANCE, done); + map, 'rendering/ol/expected/zoom-webgl.png', IMAGE_TOLERANCE, done); }); }); }); diff --git a/test/rendering/ol/render.test.js b/test/rendering/ol/render.test.js index 7756e93ab0..eadba2ebf6 100644 --- a/test/rendering/ol/render.test.js +++ b/test/rendering/ol/render.test.js @@ -18,7 +18,7 @@ describe('ol.render', function() { describe('ol.render.toContext()', function() { it('creates a vector context from a Canvas 2d context', function() { - var vectorContext = _ol_render_.toContext(getContext(), { + const vectorContext = _ol_render_.toContext(getContext(), { pixelRatio: 1, size: [100, 100] }); @@ -27,13 +27,13 @@ describe('ol.render', function() { }); it('can be used to render a point geometry', function(done) { - var context = getContext(); - var vectorContext = _ol_render_.toContext(context, { + const context = getContext(); + const vectorContext = _ol_render_.toContext(context, { pixelRatio: 1, size: [100, 100] }); - var style = new Style({ + const style = new Style({ image: new CircleStyle({ fill: new Fill({ color: 'green' @@ -46,18 +46,18 @@ describe('ol.render', function() { vectorContext.drawGeometry(new Point([50, 50])); resembleCanvas(context.canvas, - 'rendering/ol/expected/render-point.png', IMAGE_TOLERANCE, done); + 'rendering/ol/expected/render-point.png', IMAGE_TOLERANCE, done); }); it('can be used to render a linestring geometry', function(done) { - var context = getContext(); - var vectorContext = _ol_render_.toContext(context, { + const context = getContext(); + const vectorContext = _ol_render_.toContext(context, { pixelRatio: 1, size: [100, 100] }); - var style = new Style({ + const style = new Style({ stroke: new Stroke({ color: 'red', width: 14 @@ -70,18 +70,18 @@ describe('ol.render', function() { ])); resembleCanvas(context.canvas, - 'rendering/ol/expected/render-linestring.png', IMAGE_TOLERANCE, done); + 'rendering/ol/expected/render-linestring.png', IMAGE_TOLERANCE, done); }); it('respects lineCap for linestring', function(done) { - var context = getContext(); - var vectorContext = _ol_render_.toContext(context, { + const context = getContext(); + const vectorContext = _ol_render_.toContext(context, { pixelRatio: 1, size: [100, 100] }); - var style = new Style({ + const style = new Style({ stroke: new Stroke({ lineCap: 'butt', color: 'red', @@ -95,18 +95,18 @@ describe('ol.render', function() { ])); resembleCanvas(context.canvas, - 'rendering/ol/expected/render-linestring-butt.png', IMAGE_TOLERANCE, done); + 'rendering/ol/expected/render-linestring-butt.png', IMAGE_TOLERANCE, done); }); it('respects lineJoin for linestring', function(done) { - var context = getContext(); - var vectorContext = _ol_render_.toContext(context, { + const context = getContext(); + const vectorContext = _ol_render_.toContext(context, { pixelRatio: 1, size: [100, 100] }); - var style = new Style({ + const style = new Style({ stroke: new Stroke({ lineJoin: 'bevel', color: 'red', @@ -120,18 +120,18 @@ describe('ol.render', function() { ])); resembleCanvas(context.canvas, - 'rendering/ol/expected/render-linestring-bevel.png', IMAGE_TOLERANCE, done); + 'rendering/ol/expected/render-linestring-bevel.png', IMAGE_TOLERANCE, done); }); it('can be used to render a polygon geometry', function(done) { - var context = getContext(); - var vectorContext = _ol_render_.toContext(context, { + const context = getContext(); + const vectorContext = _ol_render_.toContext(context, { pixelRatio: 1, size: [100, 100] }); - var style = new Style({ + const style = new Style({ stroke: new Stroke({ color: 'blue', width: 8 @@ -149,18 +149,18 @@ describe('ol.render', function() { ])); resembleCanvas(context.canvas, - 'rendering/ol/expected/render-polygon.png', IMAGE_TOLERANCE, done); + 'rendering/ol/expected/render-polygon.png', IMAGE_TOLERANCE, done); }); it('supports lineDash styles', function(done) { - var context = getContext(); - var vectorContext = _ol_render_.toContext(context, { + const context = getContext(); + const vectorContext = _ol_render_.toContext(context, { pixelRatio: 1, size: [100, 100] }); - var style = new Style({ + const style = new Style({ stroke: new Stroke({ lineDash: [10, 5] }) @@ -174,18 +174,18 @@ describe('ol.render', function() { ])); resembleCanvas(context.canvas, - 'rendering/ol/expected/render-polygon-linedash.png', IMAGE_TOLERANCE, done); + 'rendering/ol/expected/render-polygon-linedash.png', IMAGE_TOLERANCE, done); }); it('supports lineDashOffset', function(done) { - var context = getContext(); - var vectorContext = _ol_render_.toContext(context, { + const context = getContext(); + const vectorContext = _ol_render_.toContext(context, { pixelRatio: 1, size: [100, 100] }); - var style = new Style({ + const style = new Style({ stroke: new Stroke({ lineDash: [10, 5], lineDashOffset: 5 @@ -200,7 +200,7 @@ describe('ol.render', function() { ])); resembleCanvas(context.canvas, - 'rendering/ol/expected/render-polygon-linedashoffset.png', IMAGE_TOLERANCE, done); + 'rendering/ol/expected/render-polygon-linedashoffset.png', IMAGE_TOLERANCE, done); }); diff --git a/test/rendering/ol/reproj/image.test.js b/test/rendering/ol/reproj/image.test.js index eb8b7fb916..30ea332901 100644 --- a/test/rendering/ol/reproj/image.test.js +++ b/test/rendering/ol/reproj/image.test.js @@ -9,17 +9,17 @@ import _ol_tilegrid_ from '../../../../src/ol/tilegrid.js'; describe('ol.rendering.reproj.Image', function() { function testSingleImage(source, targetProj, - targetExtent, targetResolution, pixelRatio, expectedUrl, done) { - var sourceProj = source.getProjection(); + targetExtent, targetResolution, pixelRatio, expectedUrl, done) { + const sourceProj = source.getProjection(); - var imagesRequested = 0; + let imagesRequested = 0; - var image = new ReprojImage(sourceProj, getProjection(targetProj), - targetExtent, targetResolution, pixelRatio, - function(extent, resolution, pixelRatio) { - imagesRequested++; - return source.getImage(extent, resolution, pixelRatio, sourceProj); - }); + const image = new ReprojImage(sourceProj, getProjection(targetProj), + targetExtent, targetResolution, pixelRatio, + function(extent, resolution, pixelRatio) { + imagesRequested++; + return source.getImage(extent, resolution, pixelRatio, sourceProj); + }); if (image.getState() == 0) { // IDLE _ol_events_.listen(image, 'change', function(e) { if (image.getState() == 2) { // LOADED @@ -31,7 +31,7 @@ describe('ol.rendering.reproj.Image', function() { } } - var source; + let source; describe('image reprojections from EPSG:3857', function() { beforeEach(function() { @@ -44,17 +44,17 @@ describe('ol.rendering.reproj.Image', function() { it('works for identity reprojection', function(done) { testSingleImage(source, 'EPSG:3857', - _ol_tilegrid_.createXYZ().getTileCoordExtent([5, 5, -13]), - 2 * _ol_proj_EPSG3857_.HALF_SIZE / (256 * (1 << 5)), 1, - 'rendering/ol/data/tiles/osm/5/5/12.png', done); + _ol_tilegrid_.createXYZ().getTileCoordExtent([5, 5, -13]), + 2 * _ol_proj_EPSG3857_.HALF_SIZE / (256 * (1 << 5)), 1, + 'rendering/ol/data/tiles/osm/5/5/12.png', done); }); it('to EPSG:4326', function(done) { testSingleImage(source, 'EPSG:4326', - _ol_tilegrid_.createForProjection('EPSG:4326'). - getTileCoordExtent([6, 10, -10]), - 360 / (256 * (1 << 4)), 1, - 'rendering/ol/reproj/expected/image-3857-to-4326.png', done); + _ol_tilegrid_.createForProjection('EPSG:4326'). + getTileCoordExtent([6, 10, -10]), + 360 / (256 * (1 << 4)), 1, + 'rendering/ol/reproj/expected/image-3857-to-4326.png', done); }); }); }); diff --git a/test/rendering/ol/reproj/tile.test.js b/test/rendering/ol/reproj/tile.test.js index 7e71000b86..1a18100905 100644 --- a/test/rendering/ol/reproj/tile.test.js +++ b/test/rendering/ol/reproj/tile.test.js @@ -10,19 +10,19 @@ import {register} from '../../../../src/ol/proj/proj4.js'; describe('ol.rendering.reproj.Tile', function() { function testSingleTile(source, targetProjection, targetTileGrid, z, x, y, - pixelRatio, expectedUrl, expectedRequests, done) { - var sourceProjection = source.getProjection(); - var sourceGutter = source.getGutter(sourceProjection); + pixelRatio, expectedUrl, expectedRequests, done) { + const sourceProjection = source.getProjection(); + const sourceGutter = source.getGutter(sourceProjection); - var tilesRequested = 0; + let tilesRequested = 0; - var tile = new ReprojTile(sourceProjection, source.getTileGrid(), - getProjection(targetProjection), targetTileGrid, - [z, x, y], null, pixelRatio, sourceGutter, - function(z, x, y, pixelRatio) { - tilesRequested++; - return source.getTile(z, x, y, pixelRatio, sourceProjection); - }); + const tile = new ReprojTile(sourceProjection, source.getTileGrid(), + getProjection(targetProjection), targetTileGrid, + [z, x, y], null, pixelRatio, sourceGutter, + function(z, x, y, pixelRatio) { + tilesRequested++; + return source.getTile(z, x, y, pixelRatio, sourceProjection); + }); if (tile.getState() == TileState.IDLE) { _ol_events_.listen(tile, 'change', function(e) { if (tile.getState() == TileState.LOADED) { @@ -34,7 +34,7 @@ describe('ol.rendering.reproj.Tile', function() { } } - var source; + let source; describe('single tile reprojections from EPSG:3857', function() { beforeEach(function() { @@ -46,38 +46,38 @@ describe('ol.rendering.reproj.Tile', function() { it('works for identity reprojection', function(done) { testSingleTile(source, 'EPSG:3857', source.getTileGrid(), 5, 5, -13, 1, - 'rendering/ol/data/tiles/osm/5/5/12.png', 1, done); + 'rendering/ol/data/tiles/osm/5/5/12.png', 1, done); }); it('to EPSG:4326', function(done) { - var tileGrid = _ol_tilegrid_.createForProjection('EPSG:4326', 7, [64, 64]); + const tileGrid = _ol_tilegrid_.createForProjection('EPSG:4326', 7, [64, 64]); testSingleTile(source, 'EPSG:4326', tileGrid, 7, 21, -20, 1, - 'rendering/ol/reproj/expected/osm4326.png', 1, done); + 'rendering/ol/reproj/expected/osm4326.png', 1, done); }); it('to EPSG:5070', function(done) { proj4.defs('EPSG:5070', - '+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 ' + + '+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 ' + '+y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs'); register(proj4); - var proj5070 = getProjection('EPSG:5070'); + const proj5070 = getProjection('EPSG:5070'); proj5070.setExtent([-6e6, 0, 4e6, 6e6]); - var tileGrid = _ol_tilegrid_.createForProjection('EPSG:5070', 5, [64, 64]); + const tileGrid = _ol_tilegrid_.createForProjection('EPSG:5070', 5, [64, 64]); testSingleTile(source, 'EPSG:5070', tileGrid, 5, 13, -15, 1, - 'rendering/ol/reproj/expected/osm5070.png', 1, done); + 'rendering/ol/reproj/expected/osm5070.png', 1, done); }); it('to ESRI:54009', function(done) { proj4.defs('ESRI:54009', - '+proj=moll +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs'); + '+proj=moll +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs'); register(proj4); - var proj54009 = getProjection('ESRI:54009'); + const proj54009 = getProjection('ESRI:54009'); proj54009.setExtent([-18e6, -9e6, 18e6, 9e6]); - var tileGrid = _ol_tilegrid_.createForProjection('ESRI:54009', 7, [64, 64]); + const tileGrid = _ol_tilegrid_.createForProjection('ESRI:54009', 7, [64, 64]); testSingleTile(source, 'ESRI:54009', tileGrid, 7, 27, -16, 1, - 'rendering/ol/reproj/expected/osm54009.png', 1, done); + 'rendering/ol/reproj/expected/osm54009.png', 1, done); }); }); @@ -90,22 +90,22 @@ describe('ol.rendering.reproj.Tile', function() { }); it('to EPSG:4326', function(done) { - var tileGrid = _ol_tilegrid_.createForProjection('EPSG:4326', 7, [64, 64]); + const tileGrid = _ol_tilegrid_.createForProjection('EPSG:4326', 7, [64, 64]); testSingleTile(source, 'EPSG:4326', tileGrid, 7, 23, -21, 1, - 'rendering/ol/reproj/expected/stitch-osm4326.png', 2, done); + 'rendering/ol/reproj/expected/stitch-osm4326.png', 2, done); }); it('to EPSG:3740', function(done) { proj4.defs('EPSG:3740', - '+proj=utm +zone=10 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 ' + + '+proj=utm +zone=10 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 ' + '+units=m +no_defs'); register(proj4); - var proj3740 = getProjection('EPSG:3740'); + const proj3740 = getProjection('EPSG:3740'); proj3740.setExtent([318499.05, 2700792.39, 4359164.89, 7149336.98]); - var tileGrid = _ol_tilegrid_.createForProjection('EPSG:3740', 4, [64, 64]); + const tileGrid = _ol_tilegrid_.createForProjection('EPSG:3740', 4, [64, 64]); testSingleTile(source, 'EPSG:3740', tileGrid, 4, 4, -13, 1, - 'rendering/ol/reproj/expected/stitch-osm3740.png', 4, done); + 'rendering/ol/reproj/expected/stitch-osm3740.png', 4, done); }); }); @@ -120,13 +120,13 @@ describe('ol.rendering.reproj.Tile', function() { it('works for identity reprojection', function(done) { testSingleTile(source, 'EPSG:4326', source.getTileGrid(), 0, 0, -1, 1, - 'rendering/ol/data/tiles/4326/0/0/0.png', 1, done); + 'rendering/ol/data/tiles/4326/0/0/0.png', 1, done); }); it('to EPSG:3857', function(done) { - var tileGrid = _ol_tilegrid_.createForProjection('EPSG:3857', 0, [64, 64]); + const tileGrid = _ol_tilegrid_.createForProjection('EPSG:3857', 0, [64, 64]); testSingleTile(source, 'EPSG:3857', tileGrid, 0, 0, -1, 1, - 'rendering/ol/reproj/expected/4326-to-3857.png', 1, done); + 'rendering/ol/reproj/expected/4326-to-3857.png', 1, done); }); }); @@ -141,13 +141,13 @@ describe('ol.rendering.reproj.Tile', function() { it('works for identity reprojection', function(done) { testSingleTile(source, 'EPSG:3857', source.getTileGrid(), 5, 3, -13, 1, - 'rendering/ol/data/tiles/osm-512x256/5/3/12.png', 1, done); + 'rendering/ol/data/tiles/osm-512x256/5/3/12.png', 1, done); }); it('to 64x128 EPSG:4326', function(done) { - var tileGrid = _ol_tilegrid_.createForProjection('EPSG:4326', 7, [64, 128]); + const tileGrid = _ol_tilegrid_.createForProjection('EPSG:4326', 7, [64, 128]); testSingleTile(source, 'EPSG:4326', tileGrid, 7, 27, -10, 1, - 'rendering/ol/reproj/expected/512x256-to-64x128.png', 1, done); + 'rendering/ol/reproj/expected/512x256-to-64x128.png', 1, done); }); }); @@ -163,24 +163,24 @@ describe('ol.rendering.reproj.Tile', function() { it('wraps X when prime meridian is shifted', function(done) { proj4.defs('merc_180', '+proj=merc +lon_0=180 +units=m +no_defs'); register(proj4); - var proj_ = getProjection('merc_180'); + const proj_ = getProjection('merc_180'); proj_.setExtent([-20026376.39, -20048966.10, 20026376.39, 20048966.10]); - var tileGrid = _ol_tilegrid_.createForProjection('merc_180', 0, [64, 64]); + const tileGrid = _ol_tilegrid_.createForProjection('merc_180', 0, [64, 64]); testSingleTile(source, 'merc_180', tileGrid, 0, 0, -1, 1, - 'rendering/ol/reproj/expected/dateline-merc-180.png', 2, done); + 'rendering/ol/reproj/expected/dateline-merc-180.png', 2, done); }); it('displays north pole correctly (EPSG:3413)', function(done) { proj4.defs('EPSG:3413', '+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 ' + '+k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs'); register(proj4); - var proj3413 = getProjection('EPSG:3413'); + const proj3413 = getProjection('EPSG:3413'); proj3413.setExtent([-4194304, -4194304, 4194304, 4194304]); - var tileGrid = _ol_tilegrid_.createForProjection('EPSG:3413', 0, [64, 64]); + const tileGrid = _ol_tilegrid_.createForProjection('EPSG:3413', 0, [64, 64]); testSingleTile(source, 'EPSG:3413', tileGrid, 0, 0, -1, 1, - 'rendering/ol/reproj/expected/dateline-pole.png', 2, done); + 'rendering/ol/reproj/expected/dateline-pole.png', 2, done); }); }); }); diff --git a/test/rendering/ol/source/raster.test.js b/test/rendering/ol/source/raster.test.js index 5ffe7671f2..d102917f87 100644 --- a/test/rendering/ol/source/raster.test.js +++ b/test/rendering/ol/source/raster.test.js @@ -7,7 +7,7 @@ import XYZ from '../../../../src/ol/source/XYZ.js'; where('Uint8ClampedArray').describe('ol.rendering.source.Raster', function() { function afterRender(source, raster, callback) { - var loading = 0; + let loading = 0; source.on('tileloadstart', function(event) { loading++; @@ -26,7 +26,7 @@ where('Uint8ClampedArray').describe('ol.rendering.source.Raster', function() { } - var map; + let map; function createMap(renderer, pixelRatio) { map = new Map({ target: createMapDiv(200, 200), @@ -50,17 +50,17 @@ where('Uint8ClampedArray').describe('ol.rendering.source.Raster', function() { it('renders the result of an operation', function(done) { createMap('canvas', 1); - var source = new XYZ({ + const source = new XYZ({ url: 'rendering/ol/data/tiles/osm/{z}/{x}/{y}.png', transition: 0 }); - var raster = new RasterSource({ + const raster = new RasterSource({ sources: [source], operation: function(pixels) { - var pixel = pixels[0]; + const pixel = pixels[0]; // swap blue and red - var red = pixel[0]; + const red = pixel[0]; pixel[0] = pixel[2]; pixel[2] = red; return pixel; @@ -75,7 +75,7 @@ where('Uint8ClampedArray').describe('ol.rendering.source.Raster', function() { expectResemble(map, 'rendering/ol/source/expected/raster-1.png', IMAGE_TOLERANCE, done); }); - var layer = new ImageLayer({source: raster}); + const layer = new ImageLayer({source: raster}); map.addLayer(layer); }); diff --git a/test/rendering/ol/source/tilewms.test.js b/test/rendering/ol/source/tilewms.test.js index 1e5fef4c80..c01f753790 100644 --- a/test/rendering/ol/source/tilewms.test.js +++ b/test/rendering/ol/source/tilewms.test.js @@ -6,7 +6,7 @@ import TileWMS from '../../../../src/ol/source/TileWMS.js'; describe('ol.rendering.source.TileWMS', function() { function tilesLoaded(source, callback) { - var loading = 0; + let loading = 0; source.on('tileloadstart', function(event) { loading++; @@ -23,7 +23,7 @@ describe('ol.rendering.source.TileWMS', function() { } - var map; + let map; function createMap(renderer, pixelRatio) { map = new Map({ target: createMapDiv(200, 200), @@ -58,7 +58,7 @@ describe('ol.rendering.source.TileWMS', function() { describe('0px gutter, 1 pixel ratio', function() { it('tests the canvas renderer', function(done) { createMap('canvas', 1); - var source = createSource(0); + const source = createSource(0); tilesLoaded(source, function() { expectResemble(map, 'rendering/ol/source/expected/0_1.canvas.png', IMAGE_TOLERANCE, done); }); @@ -70,7 +70,7 @@ describe('ol.rendering.source.TileWMS', function() { where('WebGL').it('tests the WebGL renderer', function(done) { assertWebGL(); createMap('webgl', 1); - var source = createSource(0); + const source = createSource(0); tilesLoaded(source, function() { expectResemble(map, 'rendering/ol/source/expected/0_1.webgl.png', IMAGE_TOLERANCE, done); }); @@ -83,7 +83,7 @@ describe('ol.rendering.source.TileWMS', function() { describe('0px gutter, 2 pixel ratio', function() { it('tests the canvas renderer', function(done) { createMap('canvas', 2); - var source = createSource(0); + const source = createSource(0); tilesLoaded(source, function() { expectResemble(map, 'rendering/ol/source/expected/0_2.canvas.png', IMAGE_TOLERANCE, done); }); @@ -95,7 +95,7 @@ describe('ol.rendering.source.TileWMS', function() { where('WebGL').it('tests the WebGL renderer', function(done) { assertWebGL(); createMap('webgl', 2); - var source = createSource(0); + const source = createSource(0); tilesLoaded(source, function() { expectResemble(map, 'rendering/ol/source/expected/0_2.webgl.png', IMAGE_TOLERANCE, done); }); @@ -109,7 +109,7 @@ describe('ol.rendering.source.TileWMS', function() { describe('20px gutter, 1 pixel ratio', function() { it('tests the canvas renderer', function(done) { createMap('canvas', 1); - var source = createSource(20); + const source = createSource(20); tilesLoaded(source, function() { expectResemble(map, 'rendering/ol/source/expected/20_1.canvas.png', IMAGE_TOLERANCE, done); }); @@ -121,7 +121,7 @@ describe('ol.rendering.source.TileWMS', function() { where('WebGL').it('tests the WebGL renderer', function(done) { assertWebGL(); createMap('webgl', 1); - var source = createSource(20); + const source = createSource(20); tilesLoaded(source, function() { expectResemble(map, 'rendering/ol/source/expected/20_1.webgl.png', IMAGE_TOLERANCE, done); }); @@ -134,7 +134,7 @@ describe('ol.rendering.source.TileWMS', function() { describe('20px gutter, 2 pixel ratio', function() { it('tests the canvas renderer', function(done) { createMap('canvas', 2); - var source = createSource(20); + const source = createSource(20); tilesLoaded(source, function() { expectResemble(map, 'rendering/ol/source/expected/20_2.canvas.png', IMAGE_TOLERANCE, done); }); @@ -146,7 +146,7 @@ describe('ol.rendering.source.TileWMS', function() { where('WebGL').it('tests the WebGL renderer', function(done) { assertWebGL(); createMap('webgl', 2); - var source = createSource(20); + const source = createSource(20); tilesLoaded(source, function() { expectResemble(map, 'rendering/ol/source/expected/20_2.webgl.png', IMAGE_TOLERANCE, done); }); diff --git a/test/rendering/ol/style/circle.test.js b/test/rendering/ol/style/circle.test.js index 97f042e3a8..394be3e15d 100644 --- a/test/rendering/ol/style/circle.test.js +++ b/test/rendering/ol/style/circle.test.js @@ -13,11 +13,11 @@ import Stroke from '../../../../src/ol/style/Stroke.js'; describe('ol.rendering.style.Circle', function() { - var map, vectorSource; + let map, vectorSource; function createMap(renderer) { vectorSource = new VectorSource(); - var vectorLayer = new VectorLayer({ + const vectorLayer = new VectorLayer({ source: vectorSource }); @@ -44,7 +44,7 @@ describe('ol.rendering.style.Circle', function() { describe('#render', function() { function createFeatures(multi) { - var feature; + let feature; feature = new Feature({ geometry: multi ? new MultiPoint([[-20, 18]]) : new Point([-20, 18]) }); @@ -188,14 +188,14 @@ describe('ol.rendering.style.Circle', function() { createMap('canvas'); createFeatures(); expectResemble(map, 'rendering/ol/style/expected/circle-canvas.png', - 8.0, done); + 8.0, done); }); it('renders multipoint geometries', function(done) { createMap('canvas'); createFeatures(true); expectResemble(map, 'rendering/ol/style/expected/circle-canvas.png', - 8.0, done); + 8.0, done); }); where('WebGL').it('tests the WebGL renderer', function(done) { @@ -203,7 +203,7 @@ describe('ol.rendering.style.Circle', function() { createMap('webgl'); createFeatures(); expectResemble(map, 'rendering/ol/style/expected/circle-webgl.png', - 8.0, done); + 8.0, done); }); }); }); diff --git a/test/rendering/ol/style/icon.test.js b/test/rendering/ol/style/icon.test.js index 4ec3ab1fbc..df1566db8d 100644 --- a/test/rendering/ol/style/icon.test.js +++ b/test/rendering/ol/style/icon.test.js @@ -10,9 +10,9 @@ import Style from '../../../../src/ol/style/Style.js'; describe('ol.rendering.style.Icon', function() { - var map, vectorSource; + let map, vectorSource; - var imgInfo = { + const imgInfo = { anchor: [0.5, 46], anchorXUnits: 'fraction', anchorYUnits: 'pixels', @@ -23,7 +23,7 @@ describe('ol.rendering.style.Icon', function() { function createMap(renderer, width, height) { vectorSource = new VectorSource(); - var vectorLayer = new VectorLayer({ + const vectorLayer = new VectorLayer({ source: vectorSource }); @@ -50,12 +50,11 @@ describe('ol.rendering.style.Icon', function() { describe('#render', function() { function createFeatures(src, imgInfo, callback) { - var feature; - feature = new Feature({ + const feature = new Feature({ geometry: new Point([0, 0]) }); - var img = new Image(); + const img = new Image(); img.onload = function() { imgInfo.img = img; feature.setStyle(new Style({ @@ -71,7 +70,7 @@ describe('ol.rendering.style.Icon', function() { createMap('canvas'); createFeatures('rendering/ol/data/icon.png', imgInfo, function() { expectResemble(map, 'rendering/ol/style/expected/icon-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -82,7 +81,7 @@ describe('ol.rendering.style.Icon', function() { imgSize: [512, 512] }, function() { expectResemble(map, 'rendering/ol/style/expected/icon-canvas-svg-scale.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -94,7 +93,7 @@ describe('ol.rendering.style.Icon', function() { imgSize: [512, 512] }, function() { expectResemble(map, 'rendering/ol/style/expected/icon-canvas-svg-offset.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -106,7 +105,7 @@ describe('ol.rendering.style.Icon', function() { imgSize: [512, 512] }, function() { expectResemble(map, 'rendering/ol/style/expected/icon-canvas-svg-offset2.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); @@ -115,7 +114,7 @@ describe('ol.rendering.style.Icon', function() { createMap('webgl'); createFeatures('rendering/ol/data/icon.png', imgInfo, function() { expectResemble(map, 'rendering/ol/style/expected/icon-webgl.png', - 2.0, done); + 2.0, done); }); }); }); diff --git a/test/rendering/ol/style/linestring.test.js b/test/rendering/ol/style/linestring.test.js index 6286668361..19e46ba959 100644 --- a/test/rendering/ol/style/linestring.test.js +++ b/test/rendering/ol/style/linestring.test.js @@ -10,11 +10,11 @@ import Stroke from '../../../../src/ol/style/Stroke.js'; describe('ol.rendering.style.LineString', function() { - var map, vectorSource; + let map, vectorSource; function createMap(renderer, opt_pixelRatio) { vectorSource = new VectorSource(); - var vectorLayer = new VectorLayer({ + const vectorLayer = new VectorLayer({ source: vectorSource }); @@ -41,11 +41,11 @@ describe('ol.rendering.style.LineString', function() { describe('different strokes', function() { function createFeatures() { - var feature; + let feature; feature = new Feature({ geometry: new LineString( - [[-20, 20], [15, 20]] + [[-20, 20], [15, 20]] ) }); feature.setStyle(new Style({ @@ -55,7 +55,7 @@ describe('ol.rendering.style.LineString', function() { feature = new Feature({ geometry: new LineString( - [[-20, 15], [15, 15]] + [[-20, 15], [15, 15]] ) }); feature.setStyle(new Style({ @@ -65,7 +65,7 @@ describe('ol.rendering.style.LineString', function() { feature = new Feature({ geometry: new LineString( - [[-20, 10], [15, 10]] + [[-20, 10], [15, 10]] ) }); feature.setStyle([new Style({ @@ -77,7 +77,7 @@ describe('ol.rendering.style.LineString', function() { feature = new Feature({ geometry: new LineString( - [[-20, -20], [-2, 0], [15, -20]] + [[-20, -20], [-2, 0], [15, -20]] ) }); feature.setStyle(new Style({ @@ -93,7 +93,7 @@ describe('ol.rendering.style.LineString', function() { feature = new Feature({ geometry: new LineString( - [[-20, -15], [-2, 5], [15, -15]] + [[-20, -15], [-2, 5], [15, -15]] ) }); feature.setStyle(new Style({ @@ -113,23 +113,23 @@ describe('ol.rendering.style.LineString', function() { createMap('canvas'); createFeatures(); expectResemble( - map, 'rendering/ol/style/expected/linestring-strokes-canvas.png', - 3.0, done); + map, 'rendering/ol/style/expected/linestring-strokes-canvas.png', + 3.0, done); }); where('WebGL').it('tests the WebGL renderer', function(done) { assertWebGL(); createMap('webgl'); createFeatures(); expectResemble(map, 'rendering/ol/style/expected/linestring-strokes-webgl.png', - 14.6, done); + 14.6, done); }); it('tests the canvas renderer (HiDPI)', function(done) { createMap('canvas', 2); createFeatures(); expectResemble( - map, 'rendering/ol/style/expected/linestring-strokes-canvas-hidpi.png', - 3.0, done); + map, 'rendering/ol/style/expected/linestring-strokes-canvas-hidpi.png', + 3.0, done); }); }); }); diff --git a/test/rendering/ol/style/polygon.test.js b/test/rendering/ol/style/polygon.test.js index 905e9764a2..fadfd3e039 100644 --- a/test/rendering/ol/style/polygon.test.js +++ b/test/rendering/ol/style/polygon.test.js @@ -11,13 +11,13 @@ import Stroke from '../../../../src/ol/style/Stroke.js'; describe('ol.rendering.style.Polygon', function() { - var map, vectorSource; + let map, vectorSource; function createMap(renderer, opt_size) { - var size = opt_size || 50; + const size = opt_size || 50; vectorSource = new VectorSource(); - var vectorLayer = new VectorLayer({ + const vectorLayer = new VectorLayer({ source: vectorSource }); @@ -44,9 +44,9 @@ describe('ol.rendering.style.Polygon', function() { describe('different types', function() { function createFeatures() { - var fill = new Fill({color: 'red'}); + const fill = new Fill({color: 'red'}); - var feature; + let feature; // rectangle feature = new Feature({ geometry: new Polygon([ @@ -90,28 +90,28 @@ describe('ol.rendering.style.Polygon', function() { createMap('canvas'); createFeatures(); expectResemble(map, 'rendering/ol/style/expected/polygon-types-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); where('WebGL').it('tests the webgl renderer', function(done) { createMap('webgl'); createFeatures(); expectResemble(map, 'rendering/ol/style/expected/polygon-types-webgl.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); describe('different types with stroke', function() { function createFeatures() { - var stroke = new Stroke({ + const stroke = new Stroke({ width: 10, color: '#000', lineJoin: 'round', lineCap: 'butt' }); - var feature; + let feature; // rectangle feature = new Feature({ geometry: new Polygon([ @@ -156,7 +156,7 @@ describe('ol.rendering.style.Polygon', function() { map.getView().setResolution(0.5); createFeatures(); expectResemble(map, 'rendering/ol/style/expected/polygon-types-canvas-stroke.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); where('WebGL').it('tests the webgl renderer', function(done) { @@ -164,14 +164,14 @@ describe('ol.rendering.style.Polygon', function() { map.getView().setResolution(0.5); createFeatures(); expectResemble(map, 'rendering/ol/style/expected/polygon-types-webgl-stroke.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); describe('z-index', function() { function createFeatures() { - var feature; + let feature; // rectangle with z-index 2 feature = new Feature({ geometry: new Polygon([ @@ -214,21 +214,21 @@ describe('ol.rendering.style.Polygon', function() { createMap('canvas'); createFeatures(); expectResemble(map, 'rendering/ol/style/expected/polygon-zindex-canvas.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); where('WebGL').it('tests the webgl renderer', function(done) { createMap('webgl'); createFeatures(); expectResemble(map, 'rendering/ol/style/expected/polygon-zindex-webgl.png', - IMAGE_TOLERANCE, done); + IMAGE_TOLERANCE, done); }); }); describe('different fills and strokes', function() { function createFeatures() { - var feature; + let feature; // rectangle feature = new Feature({ geometry: new Polygon([ @@ -270,25 +270,25 @@ describe('ol.rendering.style.Polygon', function() { createMap('canvas'); createFeatures(); expectResemble( - map, 'rendering/ol/style/expected/polygon-fill-and-strokes-canvas.png', - IMAGE_TOLERANCE, done); + map, 'rendering/ol/style/expected/polygon-fill-and-strokes-canvas.png', + IMAGE_TOLERANCE, done); }); where('WebGL').it('tests the webgl renderer', function(done) { createMap('webgl'); createFeatures(); expectResemble( - map, 'rendering/ol/style/expected/polygon-fill-and-strokes-webgl.png', - 5.76, done); + map, 'rendering/ol/style/expected/polygon-fill-and-strokes-webgl.png', + 5.76, done); }); }); describe('CanvasPattern and LinearGradient as fills and strokes', function() { function createRainbowGradient() { - var canvas = document.createElement('canvas'); - var context = canvas.getContext('2d'); - var gradient = context.createLinearGradient(0, 0, 30, 0); + const canvas = document.createElement('canvas'); + const context = canvas.getContext('2d'); + const gradient = context.createLinearGradient(0, 0, 30, 0); gradient.addColorStop(0, 'red'); gradient.addColorStop(1 / 6, 'orange'); gradient.addColorStop(2 / 6, 'yellow'); @@ -300,8 +300,8 @@ describe('ol.rendering.style.Polygon', function() { } function createPattern() { - var canvas = document.createElement('canvas'); - var context = canvas.getContext('2d'); + const canvas = document.createElement('canvas'); + const context = canvas.getContext('2d'); canvas.width = 11; canvas.height = 11; context.fillStyle = 'rgba(102, 0, 102, 0.5)'; @@ -316,7 +316,7 @@ describe('ol.rendering.style.Polygon', function() { } function createFeatures() { - var feature = new Feature({ + const feature = new Feature({ geometry: new Polygon([ [[-20, -20], [-20, 20], [18, 20], [-20, -20]] ]) @@ -332,8 +332,8 @@ describe('ol.rendering.style.Polygon', function() { createMap('canvas'); createFeatures(); expectResemble( - map, 'rendering/ol/style/expected/polygon-pattern-gradient-canvas.png', - 2.75, done); + map, 'rendering/ol/style/expected/polygon-pattern-gradient-canvas.png', + 2.75, done); }); }); diff --git a/test/rendering/ol/style/regularshape.test.js b/test/rendering/ol/style/regularshape.test.js index fca045054e..5ee362fb33 100644 --- a/test/rendering/ol/style/regularshape.test.js +++ b/test/rendering/ol/style/regularshape.test.js @@ -12,11 +12,11 @@ import Stroke from '../../../../src/ol/style/Stroke.js'; describe('ol.rendering.style.RegularShape', function() { - var map, vectorSource; + let map, vectorSource; function createMap(renderer) { vectorSource = new VectorSource(); - var vectorLayer = new VectorLayer({ + const vectorLayer = new VectorLayer({ source: vectorSource }); @@ -41,7 +41,7 @@ describe('ol.rendering.style.RegularShape', function() { }); function createFeatures(stroke, fill) { - var feature; + let feature; feature = new Feature({ geometry: new Point([-15, 15]) }); @@ -108,8 +108,8 @@ describe('ol.rendering.style.RegularShape', function() { describe('#render', function() { - var stroke = new Stroke({width: 2}); - var fill = new Fill({color: 'red'}); + const stroke = new Stroke({width: 2}); + const fill = new Fill({color: 'red'}); it('tests the canvas renderer', function(done) { createMap('canvas'); @@ -143,8 +143,8 @@ describe('ol.rendering.style.RegularShape', function() { }); describe('uses the default fill and stroke color', function() { - var stroke = new Stroke(); - var fill = new Fill(); + const stroke = new Stroke(); + const fill = new Fill(); it('tests the canvas renderer', function(done) { createMap('canvas'); diff --git a/test/rendering/ol/style/text.test.js b/test/rendering/ol/style/text.test.js index 9bd39dab7d..2d18baae36 100644 --- a/test/rendering/ol/style/text.test.js +++ b/test/rendering/ol/style/text.test.js @@ -15,12 +15,12 @@ import Stroke from '../../../../src/ol/style/Stroke.js'; describe('ol.rendering.style.Text', function() { - var map, vectorSource; + let map, vectorSource; function createMap(renderer, opt_pixelRatio) { - var pixelRatio = opt_pixelRatio || 1; + const pixelRatio = opt_pixelRatio || 1; vectorSource = new VectorSource(); - var vectorLayer = new VectorLayer({ + const vectorLayer = new VectorLayer({ source: vectorSource }); @@ -47,8 +47,8 @@ describe('ol.rendering.style.Text', function() { describe('#render', function() { function createFeatures(opt_scale) { - var scale = opt_scale || 1; - var feature; + const scale = opt_scale || 1; + let feature; feature = new Feature({ geometry: new Point([-20, 18]) }); @@ -97,17 +97,17 @@ describe('ol.rendering.style.Text', function() { vectorSource.addFeature(feature); } - var nicePath = [ + const nicePath = [ 20, 33, 40, 31, 60, 30, 80, 31, 100, 33, 120, 37, 140, 39, 160, 40, 180, 39, 200, 37, 220, 33, 240, 31, 260, 30, 280, 31, 300, 33 ]; - var uglyPath = [163, 22, 159, 30, 150, 30, 143, 24, 151, 17]; - var polygon = [151, 17, 163, 22, 159, 30, 150, 30, 143, 24, 151, 17]; + const uglyPath = [163, 22, 159, 30, 150, 30, 143, 24, 151, 17]; + const polygon = [151, 17, 163, 22, 159, 30, 150, 30, 143, 24, 151, 17]; function createLineString(coords, textAlign, maxAngle, strokeColor, strokeWidth, scale) { - var geom = new LineString(); + let geom = new LineString(); geom.setFlatCoordinates('XY', coords); - var style = new Style({ + let style = new Style({ stroke: new Stroke({ color: 'red' }), @@ -124,7 +124,7 @@ describe('ol.rendering.style.Text', function() { }) }) }); - var feature = new Feature(geom); + let feature = new Feature(geom); feature.setStyle(style); vectorSource.addFeature(feature); @@ -174,7 +174,7 @@ describe('ol.rendering.style.Text', function() { it('renders multiline text with alignment options', function(done) { createMap('canvas'); - var feature; + let feature; feature = new Feature(new Point([25, 0])); feature.setStyle(new Style({ text: new Text({ @@ -216,7 +216,7 @@ describe('ol.rendering.style.Text', function() { it('renders multiline text with positioning options', function(done) { createMap('canvas'); - var feature; + let feature; feature = new Feature(new Point([0, 0])); feature.setStyle(new Style({ text: new Text({ @@ -262,9 +262,9 @@ describe('ol.rendering.style.Text', function() { it('renders text along a MultiLineString', function(done) { createMap('canvas'); - var line = new LineString(); + let line = new LineString(); line.setFlatCoordinates('XY', nicePath); - var geom = new MultiLineString(null); + const geom = new MultiLineString(null); geom.appendLineString(line); line = line.clone(); line.translate(0, 50); @@ -272,7 +272,7 @@ describe('ol.rendering.style.Text', function() { line = line.clone(); line.translate(0, -100); geom.appendLineString(line); - var feature = new Feature(geom); + const feature = new Feature(geom); feature.setStyle(new Style({ text: new Text({ text: 'Hello world', @@ -287,9 +287,9 @@ describe('ol.rendering.style.Text', function() { it('renders text along a Polygon', function(done) { createMap('canvas'); - var geom = new Polygon(null); + const geom = new Polygon(null); geom.setFlatCoordinates('XY', polygon, [polygon.length]); - var feature = new Feature(geom); + const feature = new Feature(geom); feature.setStyle(new Style({ text: new Text({ text: 'Hello world', @@ -305,9 +305,9 @@ describe('ol.rendering.style.Text', function() { it('renders text along a MultiPolygon', function(done) { createMap('canvas'); - var geom = new Polygon(null); + let geom = new Polygon(null); geom.setFlatCoordinates('XY', polygon, [polygon.length]); - var multiPolygon = new MultiPolygon(null); + const multiPolygon = new MultiPolygon(null); multiPolygon.appendPolygon(geom); geom = geom.clone(); geom.translate(0, 30); @@ -315,7 +315,7 @@ describe('ol.rendering.style.Text', function() { geom = geom.clone(); geom.translate(0, -60); multiPolygon.appendPolygon(geom); - var feature = new Feature(multiPolygon); + const feature = new Feature(multiPolygon); feature.setStyle(new Style({ text: new Text({ text: 'Hello world', @@ -332,7 +332,7 @@ describe('ol.rendering.style.Text', function() { it('renders text background', function(done) { createMap('canvas'); createFeatures(); - var features = vectorSource.getFeatures(); + const features = vectorSource.getFeatures(); features[0].getStyle().getText().setBackgroundFill(new Fill({ color: 'red' })); diff --git a/test/spec/ol/array.test.js b/test/spec/ol/array.test.js index 471f9eed8c..6ef07f980b 100644 --- a/test/spec/ol/array.test.js +++ b/test/spec/ol/array.test.js @@ -17,15 +17,15 @@ describe('ol.array', function() { describe('binarySearch', function() { - var insertionPoint = function(position) { + const insertionPoint = function(position) { return -(position + 1); }; - var revNumCompare = function(a, b) { + const revNumCompare = function(a, b) { return b - a; }; describe('default comparison on array of String(s)', function() { - var a = [ + const a = [ '1000', '9', 'AB', 'ABC', 'ABCABC', 'ABD', 'ABDA', 'B', 'B', 'B', 'C', 'CA', 'CC', 'ZZZ', 'ab', 'abc', 'abcabc', 'abd', 'abda', 'b', 'c', 'ca', 'cc', 'zzz' @@ -41,81 +41,81 @@ describe('ol.array', function() { expect(binarySearch(a, 'C')).to.be(10); }); it('should find \'B\' at index 7 || 8 || 9', function() { - var pos = binarySearch(a, 'B'); + const pos = binarySearch(a, 'B'); expect(pos == 7 || pos == 8 || pos == 9).to.be.ok(); }); it('should not find \'100\'', function() { - var pos = binarySearch(a, '100'); + const pos = binarySearch(a, '100'); expect(pos < 0).to.be.ok(); }); it('should have an insertion point of 0 for \'100\'', function() { - var pos = binarySearch(a, '100'); + const pos = binarySearch(a, '100'); expect(insertionPoint(pos)).to.be(0); }); it('should not find \'zzz0\'', function() { - var pos = binarySearch(a, 'zzz0'); + const pos = binarySearch(a, 'zzz0'); expect(pos < 0).to.be.ok(); }); it('should have an insertion point of ' + (a.length) + ' for \'zzz0\'', - function() { - var pos = binarySearch(a, 'zzz0'); - expect(insertionPoint(pos)).to.be(a.length); - } + function() { + const pos = binarySearch(a, 'zzz0'); + expect(insertionPoint(pos)).to.be(a.length); + } ); it('should not find \'BA\'', function() { - var pos = binarySearch(a, 'zzz0'); + const pos = binarySearch(a, 'zzz0'); expect(pos < 0).to.be.ok(); }); it('should have an insertion point of 10 for \'BA\'', - function() { - var pos = binarySearch(a, 'BA'); - expect(insertionPoint(pos)).to.be(10); - } + function() { + const pos = binarySearch(a, 'BA'); + expect(insertionPoint(pos)).to.be(10); + } ); }); describe('0 length array with default comparison', function() { - var b = []; + const b = []; it('should not find \'a\'', function() { expect(binarySearch(b, 'a') < 0).to.be.ok(); }); it('should have an insertion point of 0 for \'a\'', - function() { - var pos = binarySearch(b, 'a'); - expect(insertionPoint(pos)).to.be(0); - } + function() { + const pos = binarySearch(b, 'a'); + expect(insertionPoint(pos)).to.be(0); + } ); }); describe('single element array with default lexiographical comparison', - function() { - var c = ['only item']; - it('should find \'only item\' at index 0', function() { - expect(binarySearch(c, 'only item')).to.be(0); - }); - it('should not find \'a\'', function() { - expect(binarySearch(c, 'a') < 0).to.be.ok(); - }); - it('should have an insertion point of 0 for \'a\'', - function() { - var pos = binarySearch(c, 'a'); - expect(insertionPoint(pos)).to.be(0); - } - ); - it('should not find \'z\'', function() { - expect(binarySearch(c, 'z') < 0).to.be.ok(); - }); - it('should have an insertion point of 1 for \'z\'', - function() { - var pos = binarySearch(c, 'z'); - expect(insertionPoint(pos)).to.be(1); - } - ); - } + function() { + const c = ['only item']; + it('should find \'only item\' at index 0', function() { + expect(binarySearch(c, 'only item')).to.be(0); + }); + it('should not find \'a\'', function() { + expect(binarySearch(c, 'a') < 0).to.be.ok(); + }); + it('should have an insertion point of 0 for \'a\'', + function() { + const pos = binarySearch(c, 'a'); + expect(insertionPoint(pos)).to.be(0); + } + ); + it('should not find \'z\'', function() { + expect(binarySearch(c, 'z') < 0).to.be.ok(); + }); + it('should have an insertion point of 1 for \'z\'', + function() { + const pos = binarySearch(c, 'z'); + expect(insertionPoint(pos)).to.be(1); + } + ); + } ); describe('default comparison on array of Number(s)', function() { - var d = [ + const d = [ -897123.9, -321434.58758, -1321.3124, -324, -9, -3, 0, 0, 0, 0.31255, 5, 142.88888708, 334, 342, 453, 54254 ]; @@ -129,124 +129,124 @@ describe('ol.array', function() { expect(binarySearch(d, -3)).to.be(5); }); it('should find 0 at index 6 || 7 || 8', function() { - var pos = binarySearch(d, 0); + const pos = binarySearch(d, 0); expect(pos == 6 || pos == 7 || pos == 8).to.be(true); }); it('should not find -900000', function() { - var pos = binarySearch(d, -900000); + const pos = binarySearch(d, -900000); expect(pos < 0).to.be(true); }); it('should have an insertion point of 0 for -900000', function() { - var pos = binarySearch(d, -900000); + const pos = binarySearch(d, -900000); expect(insertionPoint(pos)).to.be(0); }); it('should not find 54255', function() { - var pos = binarySearch(d, 54255); + const pos = binarySearch(d, 54255); expect(pos < 0).to.be(true); }); it('should have an insertion point of ' + (d.length) + ' for 54255', - function() { - var pos = binarySearch(d, 54255); - expect(insertionPoint(pos)).to.be(d.length); - } + function() { + const pos = binarySearch(d, 54255); + expect(insertionPoint(pos)).to.be(d.length); + } ); it('should not find 1.1', function() { - var pos = binarySearch(d, 1.1); + const pos = binarySearch(d, 1.1); expect(pos < 0).to.be(true); }); it('should have an insertion point of 10 for 1.1', function() { - var pos = binarySearch(d, 1.1); + const pos = binarySearch(d, 1.1); expect(insertionPoint(pos)).to.be(10); }); }); describe('custom comparison function, which reverse orders numbers', - function() { - var e = [ - 54254, 453, 342, 334, 142.88888708, 5, 0.31255, 0, 0, 0, -3, - -9, -324, -1321.3124, -321434.58758, -897123.9 - ]; - it('should find 54254 at index 0', function() { - var pos = binarySearch(e, 54254, revNumCompare); - expect(pos).to.be(0); - }); - it('should find -897123.9 at index ' + (e.length - 1), function() { - var pos = binarySearch(e, -897123.9, revNumCompare); - expect(pos).to.be(e.length - 1); - }); - it('should find -3 at index 10', function() { - var pos = binarySearch(e, -3, revNumCompare); - expect(pos).to.be(10); - }); - it('should find 0 at index 7 || 8 || 9', function() { - var pos = binarySearch(e, 0, revNumCompare); - expect(pos == 7 || pos == 8 || pos == 9).to.be(true); - }); - it('should not find 54254.1', function() { - var pos = binarySearch(e, 54254.1, revNumCompare); - expect(pos < 0).to.be(true); - }); - it('should have an insertion point of 0 for 54254.1', function() { - var pos = binarySearch(e, 54254.1, revNumCompare); - expect(insertionPoint(pos)).to.be(0); - }); - it('should not find -897124', function() { - var pos = binarySearch(e, -897124, revNumCompare); - expect(pos < 0).to.be(true); - }); - it('should have an insertion point of ' + e.length + ' for -897124', - function() { - var pos = binarySearch(e, -897124, revNumCompare); - expect(insertionPoint(pos)).to.be(e.length); - } - ); - it('should not find 1.1', function() { - var pos = binarySearch(e, 1.1, revNumCompare); - expect(pos < 0).to.be(true); - }); - it('should have an insertion point of 0 for 1.1', function() { - var pos = binarySearch(e, 1.1, revNumCompare); - expect(insertionPoint(pos)).to.be(6); - }); - } + function() { + const e = [ + 54254, 453, 342, 334, 142.88888708, 5, 0.31255, 0, 0, 0, -3, + -9, -324, -1321.3124, -321434.58758, -897123.9 + ]; + it('should find 54254 at index 0', function() { + const pos = binarySearch(e, 54254, revNumCompare); + expect(pos).to.be(0); + }); + it('should find -897123.9 at index ' + (e.length - 1), function() { + const pos = binarySearch(e, -897123.9, revNumCompare); + expect(pos).to.be(e.length - 1); + }); + it('should find -3 at index 10', function() { + const pos = binarySearch(e, -3, revNumCompare); + expect(pos).to.be(10); + }); + it('should find 0 at index 7 || 8 || 9', function() { + const pos = binarySearch(e, 0, revNumCompare); + expect(pos == 7 || pos == 8 || pos == 9).to.be(true); + }); + it('should not find 54254.1', function() { + const pos = binarySearch(e, 54254.1, revNumCompare); + expect(pos < 0).to.be(true); + }); + it('should have an insertion point of 0 for 54254.1', function() { + const pos = binarySearch(e, 54254.1, revNumCompare); + expect(insertionPoint(pos)).to.be(0); + }); + it('should not find -897124', function() { + const pos = binarySearch(e, -897124, revNumCompare); + expect(pos < 0).to.be(true); + }); + it('should have an insertion point of ' + e.length + ' for -897124', + function() { + const pos = binarySearch(e, -897124, revNumCompare); + expect(insertionPoint(pos)).to.be(e.length); + } + ); + it('should not find 1.1', function() { + const pos = binarySearch(e, 1.1, revNumCompare); + expect(pos < 0).to.be(true); + }); + it('should have an insertion point of 0 for 1.1', function() { + const pos = binarySearch(e, 1.1, revNumCompare); + expect(insertionPoint(pos)).to.be(6); + }); + } ); describe('0 length array with custom comparison function', function() { - var f = []; + const f = []; it('should not find 0', function() { - var pos = binarySearch(f, 0, revNumCompare); + const pos = binarySearch(f, 0, revNumCompare); expect(pos < 0).to.be(true); }); it('should have an insertion point of 0 for 0', function() { - var pos = binarySearch(f, 0, revNumCompare); + const pos = binarySearch(f, 0, revNumCompare); expect(insertionPoint(pos)).to.be(0); }); }); describe('single element array with custom comparison function', - function() { - var g = [1]; - it('should find 1 at index 0', function() { - var pos = binarySearch(g, 1, revNumCompare); - expect(pos).to.be(0); - }); - it('should not find 2', function() { - var pos = binarySearch(g, 2, revNumCompare); - expect(pos < 0).to.be(true); - }); - it('should have an insertion point of 0 for 2', function() { - var pos = binarySearch(g, 2, revNumCompare); - expect(insertionPoint(pos)).to.be(0); - }); - it('should not find 0', function() { - var pos = binarySearch(g, 0, revNumCompare); - expect(pos < 0).to.be(true); - }); - it('should have an insertion point of 1 for 0', function() { - var pos = binarySearch(g, 0, revNumCompare); - expect(insertionPoint(pos)).to.be(1); - }); - } + function() { + const g = [1]; + it('should find 1 at index 0', function() { + const pos = binarySearch(g, 1, revNumCompare); + expect(pos).to.be(0); + }); + it('should not find 2', function() { + const pos = binarySearch(g, 2, revNumCompare); + expect(pos < 0).to.be(true); + }); + it('should have an insertion point of 0 for 2', function() { + const pos = binarySearch(g, 2, revNumCompare); + expect(insertionPoint(pos)).to.be(0); + }); + it('should not find 0', function() { + const pos = binarySearch(g, 0, revNumCompare); + expect(pos < 0).to.be(true); + }); + it('should have an insertion point of 1 for 0', function() { + const pos = binarySearch(g, 0, revNumCompare); + expect(insertionPoint(pos)).to.be(1); + }); + } ); describe('finding first index when multiple candidates', function() { @@ -259,55 +259,55 @@ describe('ol.array', function() { }); describe('Don\'t use Array#slice, Function#apply and Function#call', - function() { - var a = [1, 5, 7, 11, 13, 16, 19, 24, 28, 31, 33, 36, 40, 50, 52, 55]; - var calls = { - 'Array#slice': false, - 'Function#apply': false, - 'Function#call': false - }; - var origArraySlice; - var origFunctionApply; - var origFunctionCall; + function() { + const a = [1, 5, 7, 11, 13, 16, 19, 24, 28, 31, 33, 36, 40, 50, 52, 55]; + const calls = { + 'Array#slice': false, + 'Function#apply': false, + 'Function#call': false + }; + let origArraySlice; + let origFunctionApply; + let origFunctionCall; - it('does not use potentially slow methods (default & custom compare)', - function() { - // Mockup (I failed to use sinon.spy and beforeEach-hooks) - origArraySlice = Array.prototype.slice; - origFunctionApply = Function.prototype.apply; - origFunctionCall = Function.prototype.call; - Array.prototype.slice = function() { - calls['Array#slice'] = true; - }; - Function.prototype.apply = function() { - calls['Function#apply'] = true; - }; - Function.prototype.call = function() { - calls['Function#call'] = true; - }; + it('does not use potentially slow methods (default & custom compare)', + function() { + // Mockup (I failed to use sinon.spy and beforeEach-hooks) + origArraySlice = Array.prototype.slice; + origFunctionApply = Function.prototype.apply; + origFunctionCall = Function.prototype.call; + Array.prototype.slice = function() { + calls['Array#slice'] = true; + }; + Function.prototype.apply = function() { + calls['Function#apply'] = true; + }; + Function.prototype.call = function() { + calls['Function#call'] = true; + }; - // Now actually call and test the method twice - binarySearch(a, 48); - binarySearch(a, 13, function(a, b) { - return a > b ? 1 : a < b ? -1 : 0; - }); + // Now actually call and test the method twice + binarySearch(a, 48); + binarySearch(a, 13, function(a, b) { + return a > b ? 1 : a < b ? -1 : 0; + }); - // Restore mocked up methods - Array.prototype.slice = origArraySlice; - Function.prototype.apply = origFunctionApply; - Function.prototype.call = origFunctionCall; + // Restore mocked up methods + Array.prototype.slice = origArraySlice; + Function.prototype.apply = origFunctionApply; + Function.prototype.call = origFunctionCall; - // Expectations - expect(calls['Array#slice']).to.be(false); - expect(calls['Function#apply']).to.be(false); - expect(calls['Function#call']).to.be(false); - } - ); - } + // Expectations + expect(calls['Array#slice']).to.be(false); + expect(calls['Function#apply']).to.be(false); + expect(calls['Function#call']).to.be(false); + } + ); + } ); describe('when items are not found', function() { - var arr = [1, 2, 2, 2, 3, 5, 9]; + const arr = [1, 2, 2, 2, 3, 5, 9]; it('should return the index of where the item would go plus one, negated, if the item is not found', function() { expect(binarySearch(arr, 4)).to.equal(-6); @@ -358,19 +358,19 @@ describe('ol.array', function() { }); describe('extend', function() { it('extends an array in place with an array', function() { - var a = [0, 1]; + const a = [0, 1]; extend(a, [2, 3]); expect(a).to.eql([0, 1, 2, 3]); }); it('extends an array in place with a number', function() { - var a = [0, 1]; + const a = [0, 1]; extend(a, 2); expect(a).to.eql([0, 1, 2]); }); it('extends an array in place with a big array', function() { - var a = []; - var i = 250000; // original test has 1.000.000, but that was too slow - var bigArray = Array(i); + const a = []; + let i = 250000; // original test has 1.000.000, but that was too slow + const bigArray = Array(i); while (i--) { bigArray[i] = i; } @@ -381,8 +381,8 @@ describe('ol.array', function() { describe('find', function() { it('finds numbers in an array', function() { - var a = [0, 1, 2, 3]; - var b = find(a, function(val, index, a2) { + const a = [0, 1, 2, 3]; + const b = find(a, function(val, index, a2) { expect(a).to.equal(a2); expect(typeof index).to.be('number'); return val > 1; @@ -391,16 +391,16 @@ describe('ol.array', function() { }); it('returns null when an item in an array is not found', function() { - var a = [0, 1, 2, 3]; - var b = find(a, function(val, index, a2) { + const a = [0, 1, 2, 3]; + const b = find(a, function(val, index, a2) { return val > 100; }); expect(b).to.be(null); }); it('finds items in an array-like', function() { - var a = 'abCD'; - var b = find(a, function(val, index, a2) { + const a = 'abCD'; + const b = find(a, function(val, index, a2) { expect(a).to.equal(a2); expect(typeof index).to.be('number'); return val >= 'A' && val <= 'Z'; @@ -409,8 +409,8 @@ describe('ol.array', function() { }); it('returns null when nothing in an array-like is found', function() { - var a = 'abcd'; - var b = find(a, function(val, index, a2) { + const a = 'abcd'; + const b = find(a, function(val, index, a2) { return val >= 'A' && val <= 'Z'; }); expect(b).to.be(null); @@ -419,8 +419,8 @@ describe('ol.array', function() { describe('findIndex', function() { it('finds index of numbers in an array', function() { - var a = [0, 1, 2, 3]; - var b = findIndex(a, function(val, index, a2) { + const a = [0, 1, 2, 3]; + const b = findIndex(a, function(val, index, a2) { expect(a).to.equal(a2); expect(typeof index).to.be('number'); return val > 1; @@ -429,8 +429,8 @@ describe('ol.array', function() { }); it('returns -1 when an item in an array is not found', function() { - var a = [0, 1, 2, 3]; - var b = findIndex(a, function(val, index, a2) { + const a = [0, 1, 2, 3]; + const b = findIndex(a, function(val, index, a2) { return val > 100; }); expect(b).to.be(-1); @@ -461,7 +461,7 @@ describe('ol.array', function() { describe('linearFindNearest', function() { it('returns expected value', function() { - var arr = [1000, 500, 100]; + const arr = [1000, 500, 100]; expect(linearFindNearest(arr, 10000, 0)).to.eql(0); expect(linearFindNearest(arr, 10000, 1)).to.eql(0); @@ -511,7 +511,7 @@ describe('ol.array', function() { describe('numberSafeCompareFunction', function() { it('sorts as expected', function() { - var arr = [40, 200, 3000]; + const arr = [40, 200, 3000]; // default sort would yield [200, 3000, 40] arr.sort(numberSafeCompareFunction); expect(arr).to.eql(arr); @@ -520,7 +520,7 @@ describe('ol.array', function() { describe('remove', function() { it('removes elements from an array', function() { - var a = ['a', 'b', 'c', 'd']; + const a = ['a', 'b', 'c', 'd']; remove(a, 'c'); expect(a).to.eql(['a', 'b', 'd']); remove(a, 'x'); @@ -530,8 +530,8 @@ describe('ol.array', function() { describe('reverseSubArray', function() { it('returns expected value', function() { - var arr; - var expected = [1, 2, 3, 4, 5, 6]; + let arr; + const expected = [1, 2, 3, 4, 5, 6]; arr = [1, 5, 4, 3, 2, 6]; reverseSubArray(arr, 1, 4); @@ -552,7 +552,7 @@ describe('ol.array', function() { }); describe('stableSort', function() { - var arr, wantedSortedValues; + let arr, wantedSortedValues; beforeEach(function() { arr = [{key: 3, val: 'a'}, {key: 2, val: 'b'}, {key: 3, val: 'c'}, @@ -565,8 +565,8 @@ describe('ol.array', function() { return obj1.key - obj2.key; } stableSort(arr, comparisonFn); - var sortedValues = []; - for (var i = 0; i < arr.length; i++) { + const sortedValues = []; + for (let i = 0; i < arr.length; i++) { sortedValues.push(arr[i].val); } expect(wantedSortedValues).to.eql(sortedValues); diff --git a/test/spec/ol/assertionerror.test.js b/test/spec/ol/assertionerror.test.js index 03999ebe16..6a6a4febce 100644 --- a/test/spec/ol/assertionerror.test.js +++ b/test/spec/ol/assertionerror.test.js @@ -3,23 +3,23 @@ import AssertionError from '../../../src/ol/AssertionError.js'; describe('ol.AssertionError', function() { it('generates an error', function() { - var error = new AssertionError(42); + const error = new AssertionError(42); expect(error).to.be.an(Error); }); it('generates a message with a versioned url', function() { - var error = new AssertionError(42); - var path = VERSION ? VERSION.split('-')[0] : 'latest'; + const error = new AssertionError(42); + const path = VERSION ? VERSION.split('-')[0] : 'latest'; expect(error.message).to.be('Assertion failed. See https://openlayers.org/en/' + path + '/doc/errors/#42 for details.'); }); it('has an error code', function() { - var error = new AssertionError(42); + const error = new AssertionError(42); expect(error.code).to.be(42); }); it('has a name', function() { - var error = new AssertionError(42); + const error = new AssertionError(42); expect(error.name).to.be('AssertionError'); }); }); diff --git a/test/spec/ol/collection.test.js b/test/spec/ol/collection.test.js index 5bf7137a98..53622b0f94 100644 --- a/test/spec/ol/collection.test.js +++ b/test/spec/ol/collection.test.js @@ -4,7 +4,7 @@ import CollectionEventType from '../../../src/ol/CollectionEventType.js'; describe('ol.collection', function() { - var collection; + let collection; beforeEach(function() { collection = new Collection(); @@ -20,8 +20,8 @@ describe('ol.collection', function() { describe('create a collection from an array', function() { it('creates the expected collection', function() { - var array = [0, 1, 2]; - var collection = new Collection(array); + const array = [0, 1, 2]; + const collection = new Collection(array); expect(collection.item(0)).to.eql(0); expect(collection.item(1)).to.eql(1); expect(collection.item(2)).to.eql(2); @@ -30,13 +30,13 @@ describe('ol.collection', function() { describe('push to a collection', function() { it('adds elements to the collection', function() { - var length = collection.push(1); + const length = collection.push(1); expect(collection.getLength()).to.eql(length); expect(collection.getArray()).to.eql([1]); expect(collection.item(0)).to.eql(1); }); it('returns the correct new length of the collection', function() { - var length; + let length; _ol_events_.listen(collection, 'add', function(event) { if (event.element === 'remove_me') { collection.remove(event.element); @@ -80,7 +80,7 @@ describe('ol.collection', function() { describe('removeAt', function() { it('removes elements at the correction', function() { - var collection = new Collection([0, 1, 2]); + const collection = new Collection([0, 1, 2]); collection.removeAt(1); expect(collection.item(0)).to.eql(0); expect(collection.item(1)).to.eql(2); @@ -88,7 +88,7 @@ describe('ol.collection', function() { }); describe('forEach', function() { - var cb; + let cb; beforeEach(function() { cb = sinon.spy(); }); @@ -110,27 +110,27 @@ describe('ol.collection', function() { describe('remove', function() { it('removes the first matching element', function() { - var collection = new Collection([0, 1, 2]); + const collection = new Collection([0, 1, 2]); expect(collection.remove(1)).to.eql(1); expect(collection.getArray()).to.eql([0, 2]); expect(collection.getLength()).to.eql(2); }); it('fires a remove event', function() { - var collection = new Collection([0, 1, 2]); - var cb = sinon.spy(); + const collection = new Collection([0, 1, 2]); + const cb = sinon.spy(); _ol_events_.listen(collection, CollectionEventType.REMOVE, cb); expect(collection.remove(1)).to.eql(1); expect(cb).to.be.called(); expect(cb.lastCall.args[0].element).to.eql(1); }); it('does not remove more than one matching element', function() { - var collection = new Collection([0, 1, 1, 2]); + const collection = new Collection([0, 1, 1, 2]); expect(collection.remove(1)).to.eql(1); expect(collection.getArray()).to.eql([0, 1, 2]); expect(collection.getLength()).to.eql(3); }); it('returns undefined if the element is not found', function() { - var collection = new Collection([0, 1, 2]); + const collection = new Collection([0, 1, 2]); expect(collection.remove(3)).to.be(undefined); expect(collection.getArray()).to.eql([0, 1, 2]); expect(collection.getLength()).to.eql(3); @@ -139,15 +139,15 @@ describe('ol.collection', function() { describe('setAt and event', function() { it('does dispatch events', function() { - var collection = new Collection(['a', 'b']); - var added, removed; + const collection = new Collection(['a', 'b']); + let added, removed; _ol_events_.listen(collection, CollectionEventType.ADD, function(e) { added = e.element; }); _ol_events_.listen( - collection, CollectionEventType.REMOVE, function(e) { - removed = e.element; - }); + collection, CollectionEventType.REMOVE, function(e) { + removed = e.element; + }); collection.setAt(1, 1); expect(added).to.eql(1); expect(removed).to.eql('b'); @@ -156,12 +156,12 @@ describe('ol.collection', function() { describe('removeAt and event', function() { it('does dispatch events', function() { - var collection = new Collection(['a']); - var removed; + const collection = new Collection(['a']); + let removed; _ol_events_.listen( - collection, CollectionEventType.REMOVE, function(e) { - removed = e.element; - }); + collection, CollectionEventType.REMOVE, function(e) { + removed = e.element; + }); collection.pop(); expect(removed).to.eql('a'); }); @@ -169,12 +169,12 @@ describe('ol.collection', function() { describe('insertAt and event', function() { it('does dispatch events', function() { - var collection = new Collection([0, 2]); - var added; + const collection = new Collection([0, 2]); + let added; _ol_events_.listen( - collection, CollectionEventType.ADD, function(e) { - added = e.element; - }); + collection, CollectionEventType.ADD, function(e) { + added = e.element; + }); collection.insertAt(1, 1); expect(added).to.eql(1); }); @@ -182,11 +182,11 @@ describe('ol.collection', function() { describe('setAt beyond end', function() { it('triggers events properly', function() { - var added = []; + const added = []; _ol_events_.listen( - collection, CollectionEventType.ADD, function(e) { - added.push(e.element); - }); + collection, CollectionEventType.ADD, function(e) { + added.push(e.element); + }); collection.setAt(2, 0); expect(collection.getLength()).to.eql(3); expect(collection.item(0)).to.be(undefined); @@ -200,7 +200,7 @@ describe('ol.collection', function() { }); describe('change:length event', function() { - var collection, cb; + let collection, cb; beforeEach(function() { collection = new Collection([0, 1, 2]); cb = sinon.spy(); @@ -231,18 +231,18 @@ describe('ol.collection', function() { describe('add event', function() { it('triggers add when pushing', function() { - var collection = new Collection(); - var elem; + const collection = new Collection(); + let elem; _ol_events_.listen(collection, CollectionEventType.ADD, function(e) { elem = e.element; }); - var length = collection.push(1); + const length = collection.push(1); expect(elem).to.eql(length); }); }); describe('remove event', function() { - var collection, cb1, cb2; + let collection, cb1, cb2; beforeEach(function() { collection = new Collection([1]); cb1 = sinon.spy(); @@ -275,8 +275,8 @@ describe('ol.collection', function() { expect(collection.item(1)).to.eql(2); }); it('fires events', function() { - var collection = new Collection(); - var elems = []; + const collection = new Collection(); + const elems = []; _ol_events_.listen(collection, CollectionEventType.ADD, function(e) { elems.push(e.element); }); @@ -291,63 +291,63 @@ describe('ol.collection', function() { }); it('throws if duplicate items are passed to the constructor', function() { - var item = {}; - var call = function() { + const item = {}; + const call = function() { new Collection([item, item], {unique: true}); }; expect(call).to.throwException(); }); it('allows unique items to be added via push', function() { - var unique = new Collection(undefined, {unique: true}); + const unique = new Collection(undefined, {unique: true}); unique.push({}); unique.push({}); }); it('throws if duplicate items are added via push', function() { - var unique = new Collection(undefined, {unique: true}); - var item = {}; + const unique = new Collection(undefined, {unique: true}); + const item = {}; unique.push(item); - var call = function() { + const call = function() { unique.push(item); }; expect(call).to.throwException(); }); it('allows unique items to be added via insertAt', function() { - var unique = new Collection(undefined, {unique: true}); + const unique = new Collection(undefined, {unique: true}); unique.insertAt(0, {}); unique.insertAt(0, {}); }); it('throws if duplicate items are added via insertAt', function() { - var unique = new Collection(undefined, {unique: true}); - var item = {}; + const unique = new Collection(undefined, {unique: true}); + const item = {}; unique.insertAt(0, item); - var call = function() { + const call = function() { unique.insertAt(0, item); }; expect(call).to.throwException(); }); it('allows unique items to be added via setAt', function() { - var unique = new Collection(undefined, {unique: true}); + const unique = new Collection(undefined, {unique: true}); unique.setAt(0, {}); unique.setAt(1, {}); }); it('allows items to be reset via setAt', function() { - var unique = new Collection(undefined, {unique: true}); - var item = {}; + const unique = new Collection(undefined, {unique: true}); + const item = {}; unique.setAt(0, item); unique.setAt(0, item); }); it('throws if duplicate items are added via setAt', function() { - var unique = new Collection(undefined, {unique: true}); - var item = {}; + const unique = new Collection(undefined, {unique: true}); + const item = {}; unique.setAt(0, item); - var call = function() { + const call = function() { unique.setAt(1, item); }; expect(call).to.throwException(); diff --git a/test/spec/ol/color.test.js b/test/spec/ol/color.test.js index 4703ea4f32..ad0993f5c1 100644 --- a/test/spec/ol/color.test.js +++ b/test/spec/ol/color.test.js @@ -11,28 +11,28 @@ describe('ol.color', function() { describe('asArray()', function() { it('returns the same for an array', function() { - var color = [1, 2, 3, 0.4]; - var got = asArray(color); + const color = [1, 2, 3, 0.4]; + const got = asArray(color); expect(got).to.be(color); }); it('returns an array given an rgba string', function() { - var color = asArray('rgba(1,2,3,0.4)'); + const color = asArray('rgba(1,2,3,0.4)'); expect(color).to.eql([1, 2, 3, 0.4]); }); it('returns an array given an rgb string', function() { - var color = asArray('rgb(1,2,3)'); + const color = asArray('rgb(1,2,3)'); expect(color).to.eql([1, 2, 3, 1]); }); it('returns an array given a hex string', function() { - var color = asArray('#00ccff'); + const color = asArray('#00ccff'); expect(color).to.eql([0, 204, 255, 1]); }); it('returns an array given a hex string with alpha', function() { - var color = asArray('#00ccffb0'); + const color = asArray('#00ccffb0'); expect(color).to.eql([0, 204, 255, 176 / 255]); }); @@ -41,18 +41,18 @@ describe('ol.color', function() { describe('asString()', function() { it('returns the same for a string', function() { - var color = 'rgba(0,1,2,0.3)'; - var got = asString(color); + const color = 'rgba(0,1,2,0.3)'; + const got = asString(color); expect(got).to.be(color); }); it('returns a string given an rgba array', function() { - var color = asString([1, 2, 3, 0.4]); + const color = asString([1, 2, 3, 0.4]); expect(color).to.eql('rgba(1,2,3,0.4)'); }); it('returns a string given an rgb array', function() { - var color = asString([1, 2, 3]); + const color = asString([1, 2, 3]); expect(color).to.eql('rgba(1,2,3,1)'); }); @@ -82,47 +82,47 @@ describe('ol.color', function() { it('ignores whitespace before, between & after numbers (rgb)', function() { expect(fromString('rgb( \t 0 , 0 \n , 255 )')).to.eql( - [0, 0, 255, 1]); + [0, 0, 255, 1]); }); it('can parse rgba colors', function() { // opacity 0 expect(fromString('rgba(255, 255, 0, 0)')).to.eql( - [255, 255, 0, 0]); + [255, 255, 0, 0]); // opacity 0.0 (simple float) expect(fromString('rgba(255, 255, 0, 0.0)')).to.eql( - [255, 255, 0, 0]); + [255, 255, 0, 0]); // opacity 0.0000000000000000 (float with 16 digits) expect(fromString('rgba(255, 255, 0, 0.0000000000000000)')).to.eql( - [255, 255, 0, 0]); + [255, 255, 0, 0]); // opacity 0.1 (simple float) expect(fromString('rgba(255, 255, 0, 0.1)')).to.eql( - [255, 255, 0, 0.1]); + [255, 255, 0, 0.1]); // opacity 0.1111111111111111 (float with 16 digits) expect(fromString('rgba(255, 255, 0, 0.1111111111111111)')).to.eql( - [255, 255, 0, 0.1111111111111111]); + [255, 255, 0, 0.1111111111111111]); // opacity 1 expect(fromString('rgba(255, 255, 0, 1)')).to.eql( - [255, 255, 0, 1]); + [255, 255, 0, 1]); // opacity 1.0 expect(fromString('rgba(255, 255, 0, 1.0)')).to.eql( - [255, 255, 0, 1]); + [255, 255, 0, 1]); // opacity 1.0000000000000000 expect(fromString('rgba(255, 255, 0, 1.0000000000000000)')).to.eql( - [255, 255, 0, 1]); + [255, 255, 0, 1]); // with 30 decimal digits expect(fromString('rgba(255, 255, 0, 0.123456789012345678901234567890)')).to.eql( - [255, 255, 0, 0.123456789012345678901234567890]); + [255, 255, 0, 0.123456789012345678901234567890]); }); it('ignores whitespace before, between & after numbers (rgba)', function() { expect(fromString('rgba( \t 0 , 0 \n , 255 , 0.4711 )')).to.eql( - [0, 0, 255, 0.4711]); + [0, 0, 255, 0.4711]); }); it('throws an error on invalid colors', function() { - var invalidColors = ['tuesday', '#12345', '#1234567', 'rgb(255.0,0,0)']; - var i, ii; + const invalidColors = ['tuesday', '#12345', '#1234567', 'rgb(255.0,0,0)']; + let i, ii; for (i = 0, ii < invalidColors.length; i < ii; ++i) { expect(function() { fromString(invalidColors[i]); diff --git a/test/spec/ol/control/attribution.test.js b/test/spec/ol/control/attribution.test.js index 6f7cf3f035..4a548b2c54 100644 --- a/test/spec/ol/control/attribution.test.js +++ b/test/spec/ol/control/attribution.test.js @@ -8,9 +8,9 @@ import _ol_tilegrid_ from '../../../../src/ol/tilegrid.js'; describe('ol.control.Attribution', function() { - var map; + let map; beforeEach(function() { - var target = document.createElement('div'); + const target = document.createElement('div'); target.style.width = target.style.height = '100px'; document.body.appendChild(target); map = new Map({ @@ -48,11 +48,11 @@ describe('ol.control.Attribution', function() { }) }); map.getLayers().forEach(function(layer) { - var source = layer.getSource(); + const source = layer.getSource(); source.getTile = function() { - var tile = new Tile([0, 0, -1], 2 /* LOADED */); + const tile = new Tile([0, 0, -1], 2 /* LOADED */); tile.getImage = function() { - var image = new Image(); + const image = new Image(); image.width = 256; image.height = 256; return image; @@ -69,7 +69,7 @@ describe('ol.control.Attribution', function() { it('does not add duplicate attributions', function() { map.renderSync(); - var attribution = map.getTarget().querySelectorAll('.ol-attribution li'); + const attribution = map.getTarget().querySelectorAll('.ol-attribution li'); expect(attribution.length).to.be(2); }); diff --git a/test/spec/ol/control/control.test.js b/test/spec/ol/control/control.test.js index 2991ff77c1..8909a53516 100644 --- a/test/spec/ol/control/control.test.js +++ b/test/spec/ol/control/control.test.js @@ -2,13 +2,13 @@ import Map from '../../../../src/ol/Map.js'; import Control from '../../../../src/ol/control/Control.js'; describe('ol.control.Control', function() { - var map, control; + let map, control; beforeEach(function() { map = new Map({ target: document.createElement('div') }); - var element = document.createElement('DIV'); + const element = document.createElement('DIV'); control = new Control({element: element}); control.setMap(map); }); @@ -30,25 +30,25 @@ describe('ol.control.Control', function() { describe('ol.control.Control\'s target', function() { describe('target as string or element', function() { it('transforms target from string to element', function() { - var target = document.createElement('div'); + const target = document.createElement('div'); target.id = 'mycontrol'; document.body.appendChild(target); - var ctrl = new Control({target: 'mycontrol'}); + const ctrl = new Control({target: 'mycontrol'}); expect(ctrl.target_.id).to.equal('mycontrol'); ctrl.dispose(); target.parentNode.removeChild(target); }); it('accepts element for target', function() { - var target = document.createElement('div'); + const target = document.createElement('div'); target.id = 'mycontrol'; document.body.appendChild(target); - var ctrl = new Control({target: target}); + const ctrl = new Control({target: target}); expect(ctrl.target_.id).to.equal('mycontrol'); ctrl.dispose(); target.parentNode.removeChild(target); }); it('ignores non-existing target id', function() { - var ctrl = new Control({target: 'doesnotexist'}); + const ctrl = new Control({target: 'doesnotexist'}); expect(ctrl.target_).to.equal(null); ctrl.dispose(); }); diff --git a/test/spec/ol/control/fullscreen.test.js b/test/spec/ol/control/fullscreen.test.js index 46207b75bb..3ad3a96488 100644 --- a/test/spec/ol/control/fullscreen.test.js +++ b/test/spec/ol/control/fullscreen.test.js @@ -5,7 +5,7 @@ describe('ol.control.FullScreen', function() { describe('constructor', function() { it('can be constructed without arguments', function() { - var instance = new FullScreen(); + const instance = new FullScreen(); expect(instance).to.be.an(FullScreen); }); diff --git a/test/spec/ol/control/mouseposition.test.js b/test/spec/ol/control/mouseposition.test.js index bb43e80813..d0de8ae158 100644 --- a/test/spec/ol/control/mouseposition.test.js +++ b/test/spec/ol/control/mouseposition.test.js @@ -5,14 +5,14 @@ describe('ol.control.MousePosition', function() { describe('constructor', function() { it('can be constructed without arguments', function() { - var instance = new MousePosition(); + const instance = new MousePosition(); expect(instance).to.be.an(MousePosition); expect(instance.element.className).to.be('ol-mouse-position'); }); it('creates the element with the provided class name', function() { - var className = 'foobar'; - var instance = new MousePosition({ + const className = 'foobar'; + const instance = new MousePosition({ className: className }); expect(instance.element.className).to.be(className); diff --git a/test/spec/ol/control/overviewmap.test.js b/test/spec/ol/control/overviewmap.test.js index 8dd21efb02..60b6206863 100644 --- a/test/spec/ol/control/overviewmap.test.js +++ b/test/spec/ol/control/overviewmap.test.js @@ -4,7 +4,7 @@ import Control from '../../../../src/ol/control/Control.js'; import OverviewMap from '../../../../src/ol/control/OverviewMap.js'; describe('ol.control.OverviewMap', function() { - var map, target; + let map, target; beforeEach(function() { target = document.createElement('div'); @@ -23,7 +23,7 @@ describe('ol.control.OverviewMap', function() { describe('constructor', function() { it('creates an overview map with the default options', function() { - var control = new OverviewMap(); + const control = new OverviewMap(); expect(control).to.be.a(OverviewMap); expect(control).to.be.a(Control); }); @@ -32,16 +32,16 @@ describe('ol.control.OverviewMap', function() { describe('setMap()', function() { it('keeps ovmap view rotation in sync with map view rotation', function() { - var view = new View({ + const view = new View({ center: [0, 0], zoom: 0, rotation: 0 }); map.setView(view); - var control = new OverviewMap(); + const control = new OverviewMap(); map.addControl(control); - var ovView = control.ovmap_.getView(); + const ovView = control.ovmap_.getView(); expect(ovView.getRotation()).to.be(0); view.setRotation(Math.PI / 4); @@ -49,12 +49,12 @@ describe('ol.control.OverviewMap', function() { }); it('maintains rotation in sync if view added later', function() { - var control = new OverviewMap(); + const control = new OverviewMap(); map.addControl(control); - var ovView = control.ovmap_.getView(); + const ovView = control.ovmap_.getView(); expect(ovView.getRotation()).to.be(0); - var view = new View({ + const view = new View({ center: [0, 0], zoom: 0, rotation: 0 @@ -65,10 +65,10 @@ describe('ol.control.OverviewMap', function() { }); it('stops listening to old maps', function() { - var control = new OverviewMap(); - var ovView = control.ovmap_.getView(); + const control = new OverviewMap(); + const ovView = control.ovmap_.getView(); - var view = new View({ + const view = new View({ center: [0, 0], zoom: 0, rotation: 0 @@ -86,7 +86,7 @@ describe('ol.control.OverviewMap', function() { }); it('set target to null', function() { - var control = new OverviewMap(); + const control = new OverviewMap(); map.addControl(control); diff --git a/test/spec/ol/control/rotate.test.js b/test/spec/ol/control/rotate.test.js index bfa0367df8..e18c0c96f0 100644 --- a/test/spec/ol/control/rotate.test.js +++ b/test/spec/ol/control/rotate.test.js @@ -5,7 +5,7 @@ describe('ol.control.Rotate', function() { describe('constructor', function() { it('can be constructed without arguments', function() { - var instance = new Rotate(); + const instance = new Rotate(); expect(instance).to.be.an(Rotate); }); diff --git a/test/spec/ol/control/scaleline.test.js b/test/spec/ol/control/scaleline.test.js index 179dc5f12f..19aae64c72 100644 --- a/test/spec/ol/control/scaleline.test.js +++ b/test/spec/ol/control/scaleline.test.js @@ -5,9 +5,9 @@ import {fromLonLat} from '../../../../src/ol/proj.js'; import Projection from '../../../../src/ol/proj/Projection.js'; describe('ol.control.ScaleLine', function() { - var map; + let map; beforeEach(function() { - var target = document.createElement('div'); + const target = document.createElement('div'); document.body.appendChild(target); map = new Map({ target: target @@ -20,7 +20,7 @@ describe('ol.control.ScaleLine', function() { describe('constructor', function() { it('can be constructed without arguments', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); expect(ctrl).to.be.an(ScaleLine); }); }); @@ -29,23 +29,23 @@ describe('ol.control.ScaleLine', function() { describe('className', function() { it('defaults to "ol-scale-line"', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); ctrl.setMap(map); - var element = document.querySelector('.ol-scale-line', map.getTarget()); + const element = document.querySelector('.ol-scale-line', map.getTarget()); expect(element).to.not.be(null); expect(element).to.be.a(HTMLDivElement); }); it('can be configured', function() { - var ctrl = new ScaleLine({ + const ctrl = new ScaleLine({ className: 'humpty-dumpty' }); ctrl.setMap(map); // check that the default was not chosen - var element1 = document.querySelector('.ol-scale-line', map.getTarget()); + const element1 = document.querySelector('.ol-scale-line', map.getTarget()); expect(element1).to.be(null); // check if the configured classname was chosen - var element2 = document.querySelector('.humpty-dumpty', map.getTarget()); + const element2 = document.querySelector('.humpty-dumpty', map.getTarget()); expect(element2).to.not.be(null); expect(element2).to.be.a(HTMLDivElement); }); @@ -53,11 +53,11 @@ describe('ol.control.ScaleLine', function() { describe('minWidth', function() { it('defaults to 64', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); expect(ctrl.minWidth_).to.be(64); }); it('can be configured', function() { - var ctrl = new ScaleLine({ + const ctrl = new ScaleLine({ minWidth: 4711 }); expect(ctrl.minWidth_).to.be(4711); @@ -66,14 +66,14 @@ describe('ol.control.ScaleLine', function() { describe('render', function() { it('defaults to `ol.control.ScaleLine.render`', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); expect(ctrl.render).to.be(ScaleLine.render); }); it('can be configured', function() { - var myRender = function() { + const myRender = function() { }; - var ctrl = new ScaleLine({ + const ctrl = new ScaleLine({ render: myRender }); expect(ctrl.render).to.be(myRender); @@ -84,8 +84,8 @@ describe('ol.control.ScaleLine', function() { describe('synchronisation with map view', function() { it('calls `render` as soon as the map is rendered', function(done) { - var renderSpy = sinon.spy(); - var ctrl = new ScaleLine({ + const renderSpy = sinon.spy(); + const ctrl = new ScaleLine({ render: renderSpy }); expect(renderSpy.called).to.be(false); @@ -103,8 +103,8 @@ describe('ol.control.ScaleLine', function() { }); }); it('calls `render` as often as the map is rendered', function() { - var renderSpy = sinon.spy(); - var ctrl = new ScaleLine({ + const renderSpy = sinon.spy(); + const ctrl = new ScaleLine({ render: renderSpy }); ctrl.setMap(map); @@ -120,8 +120,8 @@ describe('ol.control.ScaleLine', function() { expect(renderSpy.callCount).to.be(3); }); it('calls `render` as when the view changes', function(done) { - var renderSpy = sinon.spy(); - var ctrl = new ScaleLine({ + const renderSpy = sinon.spy(); + const ctrl = new ScaleLine({ render: renderSpy }); ctrl.setMap(map); @@ -140,7 +140,7 @@ describe('ol.control.ScaleLine', function() { describe('static method `render`', function() { it('updates the rendered text', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); expect(ctrl.element.innerText).to.be(''); ctrl.setMap(map); map.setView(new View({ @@ -154,17 +154,17 @@ describe('ol.control.ScaleLine', function() { describe('#getUnits', function() { it('returns "metric" by default', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); expect(ctrl.getUnits()).to.be('metric'); }); it('returns what is configured via `units` property', function() { - var ctrl = new ScaleLine({ + const ctrl = new ScaleLine({ units: 'nautical' }); expect(ctrl.getUnits()).to.be('nautical'); }); it('returns what is configured `setUnits` method', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); ctrl.setUnits('nautical'); expect(ctrl.getUnits()).to.be('nautical'); }); @@ -172,7 +172,7 @@ describe('ol.control.ScaleLine', function() { describe('#setUnits', function() { it('triggers rerendering', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); map.setView(new View({ center: [0, 0], zoom: 0 @@ -189,12 +189,12 @@ describe('ol.control.ScaleLine', function() { }); describe('different units result in different contents', function() { - var ctrl; - var metricHtml; - var nauticalHtml; - var degreesHtml; - var imperialHtml; - var usHtml; + let ctrl; + let metricHtml; + let nauticalHtml; + let degreesHtml; + let imperialHtml; + let usHtml; beforeEach(function(done) { ctrl = new ScaleLine(); ctrl.setMap(map); @@ -246,7 +246,7 @@ describe('ol.control.ScaleLine', function() { describe('projections affect the scaleline', function() { it('is rendered differently for different projections', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); ctrl.setMap(map); map.setView(new View({ center: fromLonLat([7, 52]), @@ -254,19 +254,19 @@ describe('ol.control.ScaleLine', function() { projection: 'EPSG:3857' })); map.renderSync(); - var innerHtml3857 = ctrl.element_.innerHTML; + const innerHtml3857 = ctrl.element_.innerHTML; map.setView(new View({ center: [7, 52], zoom: 2, projection: 'EPSG:4326' })); map.renderSync(); - var innerHtml4326 = ctrl.element_.innerHTML; + const innerHtml4326 = ctrl.element_.innerHTML; expect(innerHtml4326).to.not.be(innerHtml3857); }); it('Projection\'s metersPerUnit affect scale for non-degree units', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); ctrl.setMap(map); map.setView(new View({ center: [0, 0], @@ -303,7 +303,7 @@ describe('ol.control.ScaleLine', function() { describe('latitude may affect scale line in EPSG:4326', function() { it('is rendered differently at different latitudes for metric', function() { - var ctrl = new ScaleLine(); + const ctrl = new ScaleLine(); ctrl.setMap(map); map.setView(new View({ center: fromLonLat([7, 0]), @@ -311,15 +311,15 @@ describe('ol.control.ScaleLine', function() { projection: 'EPSG:4326' })); map.renderSync(); - var innerHtml0 = ctrl.element_.innerHTML; + const innerHtml0 = ctrl.element_.innerHTML; map.getView().setCenter([7, 52]); map.renderSync(); - var innerHtml52 = ctrl.element_.innerHTML; + const innerHtml52 = ctrl.element_.innerHTML; expect(innerHtml0).to.not.be(innerHtml52); }); it('is rendered the same at different latitudes for degrees', function() { - var ctrl = new ScaleLine({ + const ctrl = new ScaleLine({ units: 'degrees' }); ctrl.setMap(map); @@ -329,22 +329,22 @@ describe('ol.control.ScaleLine', function() { projection: 'EPSG:4326' })); map.renderSync(); - var innerHtml0 = ctrl.element_.innerHTML; + const innerHtml0 = ctrl.element_.innerHTML; map.getView().setCenter([7, 52]); map.renderSync(); - var innerHtml52 = ctrl.element_.innerHTML; + const innerHtml52 = ctrl.element_.innerHTML; expect(innerHtml0).to.be(innerHtml52); }); }); describe('zoom affects the scaleline', function() { - var currentZoom; - var ctrl; - var renderedHtmls; - var mapView; + let currentZoom; + let ctrl; + let renderedHtmls; + let mapView; - var getMetricUnit = function(zoom) { + const getMetricUnit = function(zoom) { if (zoom > 30) { return 'μm'; } else if (zoom > 20) { @@ -384,11 +384,11 @@ describe('ol.control.ScaleLine', function() { while (--currentZoom >= 0) { mapView.setZoom(currentZoom); map.renderSync(); - var currentHtml = ctrl.element_.innerHTML; + const currentHtml = ctrl.element_.innerHTML; expect(currentHtml in renderedHtmls).to.be(false); renderedHtmls[currentHtml] = true; - var unit = ctrl.innerElement_.textContent.match(/\d+ (.+)/)[1]; + const unit = ctrl.innerElement_.textContent.match(/\d+ (.+)/)[1]; expect(unit).to.eql(getMetricUnit(currentZoom)); } }); @@ -399,7 +399,7 @@ describe('ol.control.ScaleLine', function() { while (--currentZoom >= 0) { mapView.setZoom(currentZoom); map.renderSync(); - var currentHtml = ctrl.element_.innerHTML; + const currentHtml = ctrl.element_.innerHTML; expect(currentHtml in renderedHtmls).to.be(false); renderedHtmls[currentHtml] = true; } @@ -411,7 +411,7 @@ describe('ol.control.ScaleLine', function() { while (--currentZoom >= 0) { mapView.setZoom(currentZoom); map.renderSync(); - var currentHtml = ctrl.element_.innerHTML; + const currentHtml = ctrl.element_.innerHTML; expect(currentHtml in renderedHtmls).to.be(false); renderedHtmls[currentHtml] = true; } @@ -423,7 +423,7 @@ describe('ol.control.ScaleLine', function() { while (--currentZoom >= 0) { mapView.setZoom(currentZoom); map.renderSync(); - var currentHtml = ctrl.element_.innerHTML; + const currentHtml = ctrl.element_.innerHTML; expect(currentHtml in renderedHtmls).to.be(false); renderedHtmls[currentHtml] = true; } @@ -435,7 +435,7 @@ describe('ol.control.ScaleLine', function() { while (--currentZoom >= 0) { mapView.setZoom(currentZoom); map.renderSync(); - var currentHtml = ctrl.element_.innerHTML; + const currentHtml = ctrl.element_.innerHTML; expect(currentHtml in renderedHtmls).to.be(false); renderedHtmls[currentHtml] = true; } diff --git a/test/spec/ol/control/zoom.test.js b/test/spec/ol/control/zoom.test.js index 98b69fa2c5..dd359043c8 100644 --- a/test/spec/ol/control/zoom.test.js +++ b/test/spec/ol/control/zoom.test.js @@ -5,7 +5,7 @@ describe('ol.control.Zoom', function() { describe('constructor', function() { it('can be constructed without arguments', function() { - var instance = new Zoom(); + const instance = new Zoom(); expect(instance).to.be.an(Zoom); }); diff --git a/test/spec/ol/control/zoomslider.test.js b/test/spec/ol/control/zoomslider.test.js index cb0c20bc95..6af8a03cba 100644 --- a/test/spec/ol/control/zoomslider.test.js +++ b/test/spec/ol/control/zoomslider.test.js @@ -4,7 +4,7 @@ import ZoomSlider from '../../../../src/ol/control/ZoomSlider.js'; import PointerEvent from '../../../../src/ol/pointer/PointerEvent.js'; describe('ol.control.ZoomSlider', function() { - var map, target, zoomslider; + let map, target, zoomslider; beforeEach(function() { target = document.createElement('div'); @@ -27,20 +27,20 @@ describe('ol.control.ZoomSlider', function() { describe('DOM creation', function() { it('creates the expected DOM elements', function() { - var zoomSliderContainers = target.querySelectorAll('.ol-zoomslider'); + const zoomSliderContainers = target.querySelectorAll('.ol-zoomslider'); expect(zoomSliderContainers.length).to.be(1); - var zoomSliderContainer = zoomSliderContainers[0]; + const zoomSliderContainer = zoomSliderContainers[0]; expect(zoomSliderContainer instanceof HTMLDivElement).to.be(true); - var hasUnselectableCls = zoomSliderContainer.classList.contains('ol-unselectable'); + let hasUnselectableCls = zoomSliderContainer.classList.contains('ol-unselectable'); expect(hasUnselectableCls).to.be(true); - var zoomSliderThumbs = zoomSliderContainer.querySelectorAll('.ol-zoomslider-thumb'); + const zoomSliderThumbs = zoomSliderContainer.querySelectorAll('.ol-zoomslider-thumb'); expect(zoomSliderThumbs.length).to.be(1); - var zoomSliderThumb = zoomSliderThumbs[0]; + const zoomSliderThumb = zoomSliderThumbs[0]; expect(zoomSliderThumb instanceof HTMLButtonElement).to.be(true); hasUnselectableCls = zoomSliderThumb.classList.contains('ol-unselectable'); @@ -59,26 +59,26 @@ describe('ol.control.ZoomSlider', function() { describe('#direction_', function() { it('is horizontal for wide containers', function() { - var control = new ZoomSlider({}); + const control = new ZoomSlider({}); control.element.style.width = '1000px'; control.element.style.height = '10px'; control.setMap(map); control.initSlider_(); - var horizontal = 1; + const horizontal = 1; expect(control.direction_).to.be(horizontal); control.dispose(); }); it('is vertical for tall containers', function() { - var control = new ZoomSlider({}); + const control = new ZoomSlider({}); control.element.style.width = '10px'; control.element.style.height = '1000px'; control.setMap(map); - var vertical = 0; + const vertical = 0; expect(control.direction_).to.be(vertical); control.dispose(); @@ -86,7 +86,7 @@ describe('ol.control.ZoomSlider', function() { }); describe('Pointer event handling', function() { - var map; + let map; beforeEach(function() { map = new Map({ @@ -102,7 +102,7 @@ describe('ol.control.ZoomSlider', function() { }); it('[horizontal] handles a drag sequence', function() { - var control = new ZoomSlider(); + const control = new ZoomSlider(); map.addControl(control); map.getView().setZoom(0); control.element.style.width = '500px'; @@ -110,8 +110,8 @@ describe('ol.control.ZoomSlider', function() { control.element.firstChild.style.width = '100px'; control.element.firstChild.style.height = '10px'; map.renderSync(); - var dragger = control.dragger_; - var event = new PointerEvent('pointerdown', { + const dragger = control.dragger_; + const event = new PointerEvent('pointerdown', { target: control.element.firstElementChild }); event.clientX = control.widthLimit_; @@ -134,7 +134,7 @@ describe('ol.control.ZoomSlider', function() { expect(control.dragging_).to.be(false); }); it('[vertical] handles a drag sequence', function() { - var control = new ZoomSlider(); + const control = new ZoomSlider(); control.element.style.width = '10px'; control.element.style.height = '100px'; control.element.firstChild.style.width = '10px'; @@ -142,8 +142,8 @@ describe('ol.control.ZoomSlider', function() { map.addControl(control); map.getView().setZoom(8); map.renderSync(); - var dragger = control.dragger_; - var event = new PointerEvent('pointerdown', { + const dragger = control.dragger_; + const event = new PointerEvent('pointerdown', { target: control.element.firstElementChild }); event.clientX = 0; diff --git a/test/spec/ol/control/zoomtoextent.test.js b/test/spec/ol/control/zoomtoextent.test.js index f346aa03eb..6b1490603c 100644 --- a/test/spec/ol/control/zoomtoextent.test.js +++ b/test/spec/ol/control/zoomtoextent.test.js @@ -5,7 +5,7 @@ describe('ol.control.ZoomToExtent', function() { describe('constructor', function() { it('can be constructed without arguments', function() { - var instance = new ZoomToExtent(); + const instance = new ZoomToExtent(); expect(instance).to.be.an(ZoomToExtent); }); diff --git a/test/spec/ol/coordinate.test.js b/test/spec/ol/coordinate.test.js index a4b33e3985..b6d88671ad 100644 --- a/test/spec/ol/coordinate.test.js +++ b/test/spec/ol/coordinate.test.js @@ -5,7 +5,7 @@ import Circle from '../../../src/ol/geom/Circle.js'; describe('ol.coordinate', function() { describe('#add', function() { - var coordinate, delta; + let coordinate, delta; beforeEach(function() { coordinate = [50.73, 7.1]; @@ -13,13 +13,13 @@ describe('ol.coordinate', function() { }); it('returns a coordinate', function() { - var returnedCoordinate = _ol_coordinate_.add(coordinate, delta); + const returnedCoordinate = _ol_coordinate_.add(coordinate, delta); expect(returnedCoordinate).to.be.an('array'); expect(returnedCoordinate).to.have.length(2); }); it('adds the delta', function() { - var returnedCoordinate = _ol_coordinate_.add(coordinate, delta); + const returnedCoordinate = _ol_coordinate_.add(coordinate, delta); expect(returnedCoordinate[0]).to.eql(48.73); expect(returnedCoordinate[1]).to.eql(10.1); }); @@ -32,37 +32,37 @@ describe('ol.coordinate', function() { }); describe('#equals', function() { - var cologne = [50.93333, 6.95]; - var bonn1 = [50.73, 7.1]; - var bonn2 = [50.73000, 7.10000]; + const cologne = [50.93333, 6.95]; + const bonn1 = [50.73, 7.1]; + const bonn2 = [50.73000, 7.10000]; it('compares correctly', function() { - var bonnEqualsBonn = _ol_coordinate_.equals(bonn1, bonn2); - var bonnEqualsCologne = _ol_coordinate_.equals(bonn1, cologne); + const bonnEqualsBonn = _ol_coordinate_.equals(bonn1, bonn2); + const bonnEqualsCologne = _ol_coordinate_.equals(bonn1, cologne); expect(bonnEqualsBonn).to.be(true); expect(bonnEqualsCologne).to.be(false); }); }); describe('#format', function() { - var coordinate; + let coordinate; beforeEach(function() { coordinate = [6.6123, 46.7919]; }); it('rounds the values', function() { - var string = _ol_coordinate_.format(coordinate, '{x} {y}', 0); + const string = _ol_coordinate_.format(coordinate, '{x} {y}', 0); expect(string).to.eql('7 47'); }); it('handles the optional fractionDigits param', function() { - var string = _ol_coordinate_.format(coordinate, '{x} {y}', 3); + const string = _ol_coordinate_.format(coordinate, '{x} {y}', 3); expect(string).to.eql('6.612 46.792'); }); }); describe('#createStringXY', function() { - var coordinate, created, formatted; + let coordinate, created, formatted; beforeEach(function() { coordinate = [6.6123, 46.7919]; created = null; @@ -89,33 +89,33 @@ describe('ol.coordinate', function() { }); describe('#closestOnCircle', function() { - var center = [5, 10]; - var circle = new Circle(center, 10); + const center = [5, 10]; + const circle = new Circle(center, 10); it('can find the closest point on circle', function() { expect(_ol_coordinate_.closestOnCircle([-20, 10], circle)) - .to.eql([-5, 10]); + .to.eql([-5, 10]); }); it('can handle coordinate equal circle center', function() { expect(_ol_coordinate_.closestOnCircle(center, circle)) - .to.eql([15, 10]); + .to.eql([15, 10]); }); }); describe('#closestOnSegment', function() { it('can handle points where the foot of the perpendicular is closest', - function() { - var point = [2, 5]; - var segment = [[-5, 0], [10, 0]]; - expect(_ol_coordinate_.closestOnSegment(point, segment)) - .to.eql([2, 0]); - }); + function() { + const point = [2, 5]; + const segment = [[-5, 0], [10, 0]]; + expect(_ol_coordinate_.closestOnSegment(point, segment)) + .to.eql([2, 0]); + }); it('can handle points where the foot of the perpendicular is not closest', - function() { - var point = [0, -6]; - var segment = [[-5, 0], [0, -1]]; - expect(_ol_coordinate_.closestOnSegment(point, segment)) - .to.eql([0, -1]); - }); + function() { + const point = [0, -6]; + const segment = [[-5, 0], [0, -1]]; + expect(_ol_coordinate_.closestOnSegment(point, segment)) + .to.eql([0, -1]); + }); }); describe('#format', function() { @@ -123,35 +123,35 @@ describe('ol.coordinate', function() { expect(_ol_coordinate_.format()).to.be(''); }); it('formats a coordinate into a template (default precision is 0)', - function() { - var coord = [7.85, 47.983333]; - var template = 'Coordinate is ({x}|{y}).'; - var got = _ol_coordinate_.format(coord, template); - var expected = 'Coordinate is (8|48).'; - expect(got).to.be(expected); - }); + function() { + const coord = [7.85, 47.983333]; + const template = 'Coordinate is ({x}|{y}).'; + const got = _ol_coordinate_.format(coord, template); + const expected = 'Coordinate is (8|48).'; + expect(got).to.be(expected); + }); it('formats a coordinate into a template and respects precision)', - function() { - var coord = [7.85, 47.983333]; - var template = 'Coordinate is ({x}|{y}).'; - var got = _ol_coordinate_.format(coord, template, 2); - var expected = 'Coordinate is (7.85|47.98).'; - expect(got).to.be(expected); - }); + function() { + const coord = [7.85, 47.983333]; + const template = 'Coordinate is ({x}|{y}).'; + const got = _ol_coordinate_.format(coord, template, 2); + const expected = 'Coordinate is (7.85|47.98).'; + expect(got).to.be(expected); + }); }); describe('#rotate', function() { it('can rotate point in place', function() { - var coord = [7.85, 47.983333]; - var rotateRadians = Math.PI / 2; // 90 degrees + const coord = [7.85, 47.983333]; + const rotateRadians = Math.PI / 2; // 90 degrees _ol_coordinate_.rotate(coord, rotateRadians); expect(coord[0].toFixed(6)).to.eql('-47.983333'); expect(coord[1].toFixed(6)).to.eql('7.850000'); }); it('returns the rotated point', function() { - var coord = [7.85, 47.983333]; - var rotateRadians = Math.PI / 2; // 90 degrees - var rotated = _ol_coordinate_.rotate(coord, rotateRadians); + const coord = [7.85, 47.983333]; + const rotateRadians = Math.PI / 2; // 90 degrees + const rotated = _ol_coordinate_.rotate(coord, rotateRadians); expect(rotated[0].toFixed(7)).to.eql('-47.9833330'); expect(rotated[1].toFixed(7)).to.eql('7.8500000'); }); @@ -159,16 +159,16 @@ describe('ol.coordinate', function() { describe('#scale', function() { it('can scale point in place', function() { - var coord = [7.85, 47.983333]; - var scale = 1.2; + const coord = [7.85, 47.983333]; + const scale = 1.2; _ol_coordinate_.scale(coord, scale); expect(coord[0].toFixed(7)).to.eql('9.4200000'); expect(coord[1].toFixed(7)).to.eql('57.5799996'); }); it('returns the scaled point', function() { - var coord = [7.85, 47.983333]; - var scale = 1.2; - var scaledCoord = _ol_coordinate_.scale(coord, scale); + const coord = [7.85, 47.983333]; + const scale = 1.2; + const scaledCoord = _ol_coordinate_.scale(coord, scale); expect(scaledCoord[0].toFixed(7)).to.eql('9.4200000'); expect(scaledCoord[1].toFixed(7)).to.eql('57.5799996'); }); @@ -176,16 +176,16 @@ describe('ol.coordinate', function() { describe('#sub', function() { it('can subtract from point in place', function() { - var coord = [47, 11]; - var delta = [1, -1]; + const coord = [47, 11]; + const delta = [1, -1]; _ol_coordinate_.sub(coord, delta); expect(coord[0]).to.eql(46); expect(coord[1]).to.eql(12); }); it('can subtract from point in place', function() { - var coord = [47, 11]; - var delta = [1, -1]; - var subtracted = _ol_coordinate_.sub(coord, delta); + const coord = [47, 11]; + const delta = [1, -1]; + const subtracted = _ol_coordinate_.sub(coord, delta); expect(subtracted[0]).to.eql(46); expect(subtracted[1]).to.eql(12); }); @@ -193,53 +193,53 @@ describe('ol.coordinate', function() { describe('#squaredDistanceToSegment', function() { it('can handle points where the foot of the perpendicular is closest', - function() { - var point = [2, 5]; - var segment = [[-5, 0], [10, 0]]; - expect(_ol_coordinate_.squaredDistanceToSegment(point, segment)) - .to.eql(25); - }); + function() { + const point = [2, 5]; + const segment = [[-5, 0], [10, 0]]; + expect(_ol_coordinate_.squaredDistanceToSegment(point, segment)) + .to.eql(25); + }); it('can handle points where the foot of the perpendicular is not closest', - function() { - var point = [0, -6]; - var segment = [[-5, 0], [0, -1]]; - expect(_ol_coordinate_.squaredDistanceToSegment(point, segment)) - .to.eql(25); - }); + function() { + const point = [0, -6]; + const segment = [[-5, 0], [0, -1]]; + expect(_ol_coordinate_.squaredDistanceToSegment(point, segment)) + .to.eql(25); + }); }); describe('#toStringHDMS', function() { it('returns the empty string on undefined input', function() { - var got = _ol_coordinate_.toStringHDMS(); - var expected = ''; + const got = _ol_coordinate_.toStringHDMS(); + const expected = ''; expect(got).to.be(expected); }); it('formats with zero fractional digits as default', function() { - var coord = [7.85, 47.983333]; - var got = _ol_coordinate_.toStringHDMS(coord); - var expected = '47° 59′ 00″ N 7° 51′ 00″ E'; + const coord = [7.85, 47.983333]; + const got = _ol_coordinate_.toStringHDMS(coord); + const expected = '47° 59′ 00″ N 7° 51′ 00″ E'; expect(got).to.be(expected); }); it('formats with given fractional digits, if passed', function() { - var coord = [7.85, 47.983333]; - var got = _ol_coordinate_.toStringHDMS(coord, 3); - var expected = '47° 58′ 59.999″ N 7° 51′ 00.000″ E'; + const coord = [7.85, 47.983333]; + const got = _ol_coordinate_.toStringHDMS(coord, 3); + const expected = '47° 58′ 59.999″ N 7° 51′ 00.000″ E'; expect(got).to.be(expected); }); }); describe('#toStringXY', function() { it('formats with zero fractional digits as default', function() { - var coord = [7.85, 47.983333]; - var got = _ol_coordinate_.toStringXY(coord); - var expected = '8, 48'; + const coord = [7.85, 47.983333]; + const got = _ol_coordinate_.toStringXY(coord); + const expected = '8, 48'; expect(got).to.be(expected); }); it('formats with given fractional digits, if passed', function() { - var coord = [7.85, 47.983333]; - var got = _ol_coordinate_.toStringXY(coord, 2); - var expected = '7.85, 47.98'; + const coord = [7.85, 47.983333]; + const got = _ol_coordinate_.toStringXY(coord, 2); + const expected = '7.85, 47.98'; expect(got).to.be(expected); }); }); diff --git a/test/spec/ol/css.test.js b/test/spec/ol/css.test.js index c1fbe04289..5a422d4bb8 100644 --- a/test/spec/ol/css.test.js +++ b/test/spec/ol/css.test.js @@ -3,7 +3,7 @@ import {getFontFamilies} from '../../../src/ol/css.js'; describe('ol.css', function() { describe('getFontFamilies()', function() { - var cases = [{ + const cases = [{ font: '2em "Open Sans"', families: ['"Open Sans"'] }, { @@ -25,7 +25,7 @@ describe('ol.css', function() { cases.forEach(function(c, i) { it('works for ' + c.font, function() { - var families = getFontFamilies(c.font); + const families = getFontFamilies(c.font); if (c.families === null) { expect(families).to.be(null); return; diff --git a/test/spec/ol/disposable.test.js b/test/spec/ol/disposable.test.js index 7ffaf11c5c..21907b9bbd 100644 --- a/test/spec/ol/disposable.test.js +++ b/test/spec/ol/disposable.test.js @@ -6,7 +6,7 @@ describe('ol.Disposable', function() { describe('constructor', function() { it('creates an instance', function() { - var disposable = new Disposable(); + const disposable = new Disposable(); expect(disposable).to.be.a(Disposable); }); @@ -15,12 +15,12 @@ describe('ol.Disposable', function() { describe('#disposed_', function() { it('is initially false', function() { - var disposable = new Disposable(); + const disposable = new Disposable(); expect(disposable.disposed_).to.be(false); }); it('is true after a call to dispose', function() { - var disposable = new Disposable(); + const disposable = new Disposable(); disposable.dispose(); expect(disposable.disposed_).to.be(true); }); @@ -30,7 +30,7 @@ describe('ol.Disposable', function() { describe('#dispose()', function() { it('calls disposeInternal only once', function() { - var disposable = new Disposable(); + const disposable = new Disposable(); sinon.spy(disposable, 'disposeInternal'); expect(disposable.disposeInternal.called).to.be(false); disposable.dispose(); diff --git a/test/spec/ol/dom/dom.test.js b/test/spec/ol/dom/dom.test.js index bd9f7d48ae..ce164d6540 100644 --- a/test/spec/ol/dom/dom.test.js +++ b/test/spec/ol/dom/dom.test.js @@ -5,11 +5,11 @@ describe('ol.dom', function() { describe('ol.dom.createCanvasContext2D', function() { // default values from // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas - var defaultWidth = 300; - var defaultHeight = 150; + const defaultWidth = 300; + const defaultHeight = 150; it('returns a CanvasRenderingContext2D', function() { - var ctx = createCanvasContext2D(); + const ctx = createCanvasContext2D(); expect(ctx).to.be.a(CanvasRenderingContext2D); expect(ctx.canvas).to.be.a(HTMLCanvasElement); expect(ctx.canvas.width).to.be(defaultWidth); @@ -17,7 +17,7 @@ describe('ol.dom', function() { }); it('has the desired width', function() { - var ctx = createCanvasContext2D(42); + const ctx = createCanvasContext2D(42); expect(ctx).to.be.a(CanvasRenderingContext2D); expect(ctx.canvas).to.be.a(HTMLCanvasElement); expect(ctx.canvas.width).to.be(42); @@ -25,7 +25,7 @@ describe('ol.dom', function() { }); it('has the desired height', function() { - var ctx = createCanvasContext2D(undefined, 42); + const ctx = createCanvasContext2D(undefined, 42); expect(ctx).to.be.a(CanvasRenderingContext2D); expect(ctx.canvas).to.be.a(HTMLCanvasElement); expect(ctx.canvas.width).to.be(defaultWidth); @@ -33,7 +33,7 @@ describe('ol.dom', function() { }); it('has the desired height and width', function() { - var ctx = createCanvasContext2D(42, 42); + const ctx = createCanvasContext2D(42, 42); expect(ctx).to.be.a(CanvasRenderingContext2D); expect(ctx.canvas).to.be.a(HTMLCanvasElement); expect(ctx.canvas.width).to.be(42); @@ -43,7 +43,7 @@ describe('ol.dom', function() { }); describe('ol.dom.outerWidth', function() { - var element = null; + let element = null; beforeEach(function() { element = document.createElement('div'); element.style.padding = 0; @@ -61,7 +61,7 @@ describe('ol.dom', function() { describe('without padding, margin or border', function() { it('calculates correctly', function() { - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(10); }); @@ -70,13 +70,13 @@ describe('ol.dom', function() { describe('with padding', function() { it('calculates correctly (both sides)', function() { element.style.padding = '5px'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(20); }); it('calculates correctly (one side)', function() { element.style.paddingLeft = '5px'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(15); }); }); @@ -85,13 +85,13 @@ describe('ol.dom', function() { it('calculates correctly (both sides)', function() { element.style.margin = '5px'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(20); }); it('calculates correctly (one side)', function() { element.style.marginLeft = '5px'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(15); }); @@ -101,14 +101,14 @@ describe('ol.dom', function() { it('calculates correctly (both sides)', function() { element.style.border = '5px solid chocolate'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(20); }); it('calculates correctly (one side)', function() { element.style.border = '5px solid chocolate'; element.style.borderRightWidth = '0'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(15); }); @@ -119,14 +119,14 @@ describe('ol.dom', function() { it('calculates correctly (both sides)', function() { element.style.padding = '5px'; element.style.margin = '5px'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(30); }); it('calculates correctly (one side)', function() { element.style.paddingLeft = '5px'; element.style.marginLeft = '5px'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(20); }); @@ -137,7 +137,7 @@ describe('ol.dom', function() { it('calculates correctly (both sides)', function() { element.style.padding = '5px'; element.style.border = '5px solid chocolate'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(30); }); @@ -145,7 +145,7 @@ describe('ol.dom', function() { element.style.paddingLeft = '5px'; element.style.border = '5px solid chocolate'; element.style.borderRightWidth = '0'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(20); }); @@ -156,7 +156,7 @@ describe('ol.dom', function() { it('calculates correctly (both sides)', function() { element.style.margin = '5px'; element.style.border = '5px solid chocolate'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(30); }); @@ -164,7 +164,7 @@ describe('ol.dom', function() { element.style.marginLeft = '5px'; element.style.border = '5px solid chocolate'; element.style.borderRightWidth = '0'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(20); }); @@ -176,7 +176,7 @@ describe('ol.dom', function() { element.style.margin = '5px'; element.style.padding = '5px'; element.style.border = '5px solid chocolate'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(40); }); @@ -185,7 +185,7 @@ describe('ol.dom', function() { element.style.paddingLeft = '5px'; element.style.border = '5px solid chocolate'; element.style.borderRightWidth = '0'; - var calcWidth = outerWidth(element); + const calcWidth = outerWidth(element); expect(calcWidth).to.be(25); }); @@ -194,7 +194,7 @@ describe('ol.dom', function() { }); describe('ol.dom.outerHeight', function() { - var element = null; + let element = null; beforeEach(function() { element = document.createElement('div'); element.style.padding = 0; @@ -212,7 +212,7 @@ describe('ol.dom', function() { describe('without padding, margin or border', function() { it('calculates correctly', function() { - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(10); }); @@ -221,13 +221,13 @@ describe('ol.dom', function() { describe('with padding', function() { it('calculates correctly (both sides)', function() { element.style.padding = '5px'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(20); }); it('calculates correctly (one side)', function() { element.style.paddingTop = '5px'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(15); }); }); @@ -236,13 +236,13 @@ describe('ol.dom', function() { it('calculates correctly (both sides)', function() { element.style.margin = '5px'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(20); }); it('calculates correctly (one side)', function() { element.style.marginTop = '5px'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(15); }); @@ -252,14 +252,14 @@ describe('ol.dom', function() { it('calculates correctly (both sides)', function() { element.style.border = '5px solid chocolate'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(20); }); it('calculates correctly (one side)', function() { element.style.border = '5px solid chocolate'; element.style.borderBottomWidth = '0'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(15); }); @@ -270,14 +270,14 @@ describe('ol.dom', function() { it('calculates correctly (both sides)', function() { element.style.padding = '5px'; element.style.margin = '5px'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(30); }); it('calculates correctly (one side)', function() { element.style.paddingTop = '5px'; element.style.marginTop = '5px'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(20); }); @@ -288,7 +288,7 @@ describe('ol.dom', function() { it('calculates correctly (both sides)', function() { element.style.padding = '5px'; element.style.border = '5px solid chocolate'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(30); }); @@ -296,7 +296,7 @@ describe('ol.dom', function() { element.style.paddingTop = '5px'; element.style.border = '5px solid chocolate'; element.style.borderBottomWidth = '0'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(20); }); @@ -307,7 +307,7 @@ describe('ol.dom', function() { it('calculates correctly (both sides)', function() { element.style.margin = '5px'; element.style.border = '5px solid chocolate'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(30); }); @@ -315,7 +315,7 @@ describe('ol.dom', function() { element.style.marginTop = '5px'; element.style.border = '5px solid chocolate'; element.style.borderBottomWidth = '0'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(20); }); @@ -327,7 +327,7 @@ describe('ol.dom', function() { element.style.margin = '5px'; element.style.padding = '5px'; element.style.border = '5px solid chocolate'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(40); }); @@ -336,7 +336,7 @@ describe('ol.dom', function() { element.style.paddingTop = '5px'; element.style.border = '5px solid chocolate'; element.style.borderBottomWidth = '0'; - var calcHeight = outerHeight(element); + const calcHeight = outerHeight(element); expect(calcHeight).to.be(25); }); diff --git a/test/spec/ol/events.test.js b/test/spec/ol/events.test.js index c248237f8a..321ec7f4aa 100644 --- a/test/spec/ol/events.test.js +++ b/test/spec/ol/events.test.js @@ -2,7 +2,7 @@ import _ol_events_ from '../../../src/ol/events.js'; import EventTarget from '../../../src/ol/events/EventTarget.js'; describe('ol.events', function() { - var add, remove, target; + let add, remove, target; beforeEach(function() { add = sinon.spy(); @@ -15,39 +15,39 @@ describe('ol.events', function() { describe('bindListener_()', function() { it('binds a listener and returns a bound listener function', function() { - var listenerObj = { + const listenerObj = { listener: sinon.spy(), bindTo: {id: 1} }; - var boundListener = _ol_events_.bindListener_(listenerObj); + const boundListener = _ol_events_.bindListener_(listenerObj); expect(listenerObj.boundListener).to.equal(boundListener); boundListener(); expect(listenerObj.listener.thisValues[0]).to.equal(listenerObj.bindTo); }); it('binds to the target when bindTo is not provided', function() { - var listenerObj = { + const listenerObj = { listener: sinon.spy(), target: {id: 1} }; - var boundListener = _ol_events_.bindListener_(listenerObj); + const boundListener = _ol_events_.bindListener_(listenerObj); expect(listenerObj.boundListener).to.equal(boundListener); boundListener(); expect(listenerObj.listener.thisValues[0]).to.equal(listenerObj.target); }); it('binds a self-unregistering listener when callOnce is true', function() { - var bindTo = {id: 1}; - var listenerObj = { + const bindTo = {id: 1}; + const listenerObj = { type: 'foo', target: target, bindTo: bindTo, callOnce: true }; - var unlistenSpy = sinon.spy(_ol_events_, 'unlistenByKey'); // eslint-disable-line openlayers-internal/no-missing-requires + const unlistenSpy = sinon.spy(_ol_events_, 'unlistenByKey'); // eslint-disable-line openlayers-internal/no-missing-requires listenerObj.listener = function() { expect(this).to.equal(bindTo); expect(unlistenSpy.firstCall.args[0]).to.eql(listenerObj); }; - var boundListener = _ol_events_.bindListener_(listenerObj); + const boundListener = _ol_events_.bindListener_(listenerObj); expect(listenerObj.boundListener).to.equal(boundListener); boundListener(); unlistenSpy.restore(); @@ -55,7 +55,7 @@ describe('ol.events', function() { }); describe('findListener_()', function() { - var listener, listenerObj, listeners; + let listener, listenerObj, listeners; beforeEach(function() { listener = function() {}; @@ -68,8 +68,8 @@ describe('ol.events', function() { }); it('searches a listener array for a specific listener', function() { - var bindTo = {id: 1}; - var result = _ol_events_.findListener_(listeners, listener); + const bindTo = {id: 1}; + let result = _ol_events_.findListener_(listeners, listener); expect(result).to.be(listenerObj); result = _ol_events_.findListener_(listeners, listener, bindTo); expect(result).to.be(undefined); @@ -80,7 +80,7 @@ describe('ol.events', function() { expect(result).to.be(listenerObj); }); it('marks the delete index on a listener object', function() { - var result = _ol_events_.findListener_(listeners, listener, undefined, true); + const result = _ol_events_.findListener_(listeners, listener, undefined, true); expect(result).to.be(listenerObj); expect(listenerObj.deleteIndex).to.be(0); }); @@ -88,8 +88,8 @@ describe('ol.events', function() { describe('getListeners()', function() { it('returns listeners for a target and type', function() { - var foo = _ol_events_.listen(target, 'foo', function() {}); - var bar = _ol_events_.listen(target, 'bar', function() {}); + const foo = _ol_events_.listen(target, 'foo', function() {}); + const bar = _ol_events_.listen(target, 'bar', function() {}); expect (_ol_events_.getListeners(target, 'foo')).to.eql([foo]); expect (_ol_events_.getListeners(target, 'bar')).to.eql([bar]); }); @@ -104,18 +104,18 @@ describe('ol.events', function() { expect(add.callCount).to.be(1); }); it('returns a key', function() { - var key = _ol_events_.listen(target, 'foo', function() {}); + const key = _ol_events_.listen(target, 'foo', function() {}); expect(key).to.be.a(Object); }); it('does not add the same listener twice', function() { - var listener = function() {}; - var key1 = _ol_events_.listen(target, 'foo', listener); - var key2 = _ol_events_.listen(target, 'foo', listener); + const listener = function() {}; + const key1 = _ol_events_.listen(target, 'foo', listener); + const key2 = _ol_events_.listen(target, 'foo', listener); expect(key1).to.equal(key2); expect(add.callCount).to.be(1); }); it('only treats listeners as same when all args are equal', function() { - var listener = function() {}; + const listener = function() {}; _ol_events_.listen(target, 'foo', listener, {}); _ol_events_.listen(target, 'foo', listener, {}); _ol_events_.listen(target, 'foo', listener, undefined); @@ -125,8 +125,8 @@ describe('ol.events', function() { describe('listenOnce()', function() { it('creates a one-off listener', function() { - var listener = sinon.spy(); - var key = _ol_events_.listenOnce(target, 'foo', listener); + const listener = sinon.spy(); + const key = _ol_events_.listenOnce(target, 'foo', listener); expect(add.callCount).to.be(1); expect(key.callOnce).to.be(true); key.boundListener(); @@ -134,16 +134,16 @@ describe('ol.events', function() { expect(remove.callCount).to.be(1); }); it('does not add the same listener twice', function() { - var listener = function() {}; - var key1 = _ol_events_.listenOnce(target, 'foo', listener); - var key2 = _ol_events_.listenOnce(target, 'foo', listener); + const listener = function() {}; + const key1 = _ol_events_.listenOnce(target, 'foo', listener); + const key2 = _ol_events_.listenOnce(target, 'foo', listener); expect(key1).to.equal(key2); expect(add.callCount).to.be(1); expect(key1.callOnce).to.be(true); }); it('listen() can turn a one-off listener into a permanent one', function() { - var listener = sinon.spy(); - var key = _ol_events_.listenOnce(target, 'foo', listener); + const listener = sinon.spy(); + let key = _ol_events_.listenOnce(target, 'foo', listener); expect(key.callOnce).to.be(true); key = _ol_events_.listen(target, 'foo', listener); expect(add.callCount).to.be(1); @@ -155,13 +155,13 @@ describe('ol.events', function() { describe('unlisten()', function() { it('unregisters previously registered listeners', function() { - var listener = function() {}; + const listener = function() {}; _ol_events_.listen(target, 'foo', listener); _ol_events_.unlisten(target, 'foo', listener); expect(_ol_events_.getListeners(target, 'foo')).to.be(undefined); }); it('works with multiple types', function() { - var listener = function() {}; + const listener = function() {}; _ol_events_.listen(target, ['foo', 'bar'], listener); _ol_events_.unlisten(target, ['bar', 'foo'], listener); expect(_ol_events_.getListeners(target, 'foo')).to.be(undefined); @@ -171,12 +171,12 @@ describe('ol.events', function() { describe('unlistenByKey()', function() { it('unregisters previously registered listeners', function() { - var key = _ol_events_.listen(target, 'foo', function() {}); + const key = _ol_events_.listen(target, 'foo', function() {}); _ol_events_.unlistenByKey(key); expect(_ol_events_.getListeners(target, 'foo')).to.be(undefined); }); it('works with multiple types', function() { - var key = _ol_events_.listen(target, ['foo', 'bar'], function() {}); + const key = _ol_events_.listen(target, ['foo', 'bar'], function() {}); _ol_events_.unlistenByKey(key); expect(_ol_events_.getListeners(target, 'foo')).to.be(undefined); expect(_ol_events_.getListeners(target, 'bar')).to.be(undefined); @@ -185,7 +185,7 @@ describe('ol.events', function() { describe('unlistenAll()', function() { it('unregisters all listeners registered for a target', function() { - var keys = [ + const keys = [ _ol_events_.listen(target, 'foo', function() {}), _ol_events_.listen(target, 'bar', function() {}) ]; @@ -199,22 +199,22 @@ describe('ol.events', function() { describe('Compatibility with ol.events.EventTarget', function() { it('does not register duplicated listeners', function() { - var target = new EventTarget(); - var listener = function() {}; - var key1 = _ol_events_.listen(target, 'foo', listener); + const target = new EventTarget(); + const listener = function() {}; + const key1 = _ol_events_.listen(target, 'foo', listener); expect(target.getListeners('foo')).to.eql([key1.boundListener]); - var key2 = _ol_events_.listen(target, 'foo', listener); + const key2 = _ol_events_.listen(target, 'foo', listener); expect(key2.boundListener).to.equal(key1.boundListener); expect(target.getListeners('foo')).to.eql([key1.boundListener]); }); it('registers multiple listeners if this object is different', function() { - var target = new EventTarget(); - var listener = function() {}; - var key1 = _ol_events_.listen(target, 'foo', listener, {}); - var key2 = _ol_events_.listen(target, 'foo', listener, {}); + const target = new EventTarget(); + const listener = function() {}; + const key1 = _ol_events_.listen(target, 'foo', listener, {}); + const key2 = _ol_events_.listen(target, 'foo', listener, {}); expect(key1.boundListener).to.not.equal(key2.boundListener); expect(target.getListeners('foo')).to.eql( - [key1.boundListener, key2.boundListener]); + [key1.boundListener, key2.boundListener]); }); }); diff --git a/test/spec/ol/events/event.test.js b/test/spec/ol/events/event.test.js index 3c1f827534..7ac8974fe3 100644 --- a/test/spec/ol/events/event.test.js +++ b/test/spec/ol/events/event.test.js @@ -4,30 +4,30 @@ describe('ol.events.Event', function() { describe('constructor', function() { it('takes a type as argument', function() { - var event = new Event('foo'); + const event = new Event('foo'); expect(event.type).to.be('foo'); }); it('does not set the propagationStopped flag', function() { - var event = new Event('foo'); + const event = new Event('foo'); expect(event.propagationStopped).to.be(undefined); }); }); describe('#preventDefault', function() { it('sets the propagationStopped flag', function() { - var event = new Event('foo'); + const event = new Event('foo'); event.preventDefault(); expect(event.propagationStopped).to.be(true); }); it('is the same as #stopPropagation', function() { - var event = new Event('foo'); + const event = new Event('foo'); expect(event.stopPropagation).to.equal(event.preventDefault); }); }); describe('ol.events.Event.preventDefault', function() { it('calls preventDefault on the event object', function() { - var event = { + const event = { preventDefault: sinon.spy() }; Event.preventDefault(event); @@ -37,7 +37,7 @@ describe('ol.events.Event', function() { describe('ol.events.Event.stopPropagation', function() { it('calls preventDefault on the event object', function() { - var event = { + const event = { stopPropagation: sinon.spy() }; Event.stopPropagation(event); diff --git a/test/spec/ol/events/eventtarget.test.js b/test/spec/ol/events/eventtarget.test.js index 94b2e9414f..cfcd62b2bb 100644 --- a/test/spec/ol/events/eventtarget.test.js +++ b/test/spec/ol/events/eventtarget.test.js @@ -5,7 +5,7 @@ import EventTarget from '../../../../src/ol/events/EventTarget.js'; describe('ol.events.EventTarget', function() { - var called, events, eventTarget, spy1, spy2, spy3; + let called, events, eventTarget, spy1, spy2, spy3; beforeEach(function() { called = []; @@ -46,7 +46,7 @@ describe('ol.events.EventTarget', function() { describe('#getListeners', function() { it('returns listeners for a type or undefined if none', function() { expect(eventTarget.getListeners('foo')).to.be(undefined); - var listeners = [function() {}]; + const listeners = [function() {}]; eventTarget.listeners_['foo'] = listeners; expect(eventTarget.getListeners('foo')).to.equal(listeners); }); @@ -111,7 +111,7 @@ describe('ol.events.EventTarget', function() { }); it('passes a custom event object with target to listeners', function() { eventTarget.addEventListener('foo', spy1); - var event = { + const event = { type: 'foo' }; eventTarget.dispatchEvent(event); diff --git a/test/spec/ol/expect.test.js b/test/spec/ol/expect.test.js index 7f3128cc94..a54b07cf53 100644 --- a/test/spec/ol/expect.test.js +++ b/test/spec/ol/expect.test.js @@ -34,17 +34,17 @@ describe('expect.js', function() { }); it('knows that, like, 1 and 2 would, like, totally dig each other', - function() { - expect(function() { - expect(1).to.roughlyEqual(2, 1); - }).not.to.throwException(); - }); + function() { + expect(function() { + expect(1).to.roughlyEqual(2, 1); + }).not.to.throwException(); + }); }); describe('called', function() { - var telephone; + let telephone; beforeEach(function() { telephone = sinon.spy(); }); @@ -77,46 +77,46 @@ describe('expect.js', function() { describe('Test equality of XML documents - xmleql', function() { it('Test XML document with single root, different prefix', function() { - var doc1 = ''; - var doc2 = ''; + const doc1 = ''; + const doc2 = ''; expect(new DOMParser().parseFromString(doc1, 'application/xml')).to.xmleql( - new DOMParser().parseFromString(doc2, 'application/xml')); + new DOMParser().parseFromString(doc2, 'application/xml')); }); it('Test XML document with single root, different prefix, prefix true', - function() { - var doc1 = ''; - var doc2 = ''; - expect(new DOMParser().parseFromString(doc1, 'application/xml')).to.not.xmleql( - new DOMParser().parseFromString(doc2, 'application/xml'), {prefix: true}); - }); + function() { + const doc1 = ''; + const doc2 = ''; + expect(new DOMParser().parseFromString(doc1, 'application/xml')).to.not.xmleql( + new DOMParser().parseFromString(doc2, 'application/xml'), {prefix: true}); + }); it('Test XML document with different root', function() { - var doc1 = ''; - var doc2 = ''; + const doc1 = ''; + const doc2 = ''; expect(new DOMParser().parseFromString(doc1, 'application/xml')).to.not.xmleql( - new DOMParser().parseFromString(doc2, 'application/xml')); + new DOMParser().parseFromString(doc2, 'application/xml')); }); it('Test different number of attributes', function() { - var doc1 = ''; - var doc2 = ''; + const doc1 = ''; + const doc2 = ''; expect(new DOMParser().parseFromString(doc1, 'application/xml')).to.not.xmleql( - new DOMParser().parseFromString(doc2, 'application/xml')); + new DOMParser().parseFromString(doc2, 'application/xml')); }); it('Test different attribute value', function() { - var doc1 = ''; - var doc2 = ''; + const doc1 = ''; + const doc2 = ''; expect(new DOMParser().parseFromString(doc1, 'application/xml')).to.not.xmleql( - new DOMParser().parseFromString(doc2, 'application/xml')); + new DOMParser().parseFromString(doc2, 'application/xml')); }); it('Test different number of children', function() { - var doc1 = ''; - var doc2 = ''; + const doc1 = ''; + const doc2 = ''; expect(new DOMParser().parseFromString(doc1, 'application/xml')).to.not.xmleql( - new DOMParser().parseFromString(doc2, 'application/xml')); + new DOMParser().parseFromString(doc2, 'application/xml')); }); }); diff --git a/test/spec/ol/extent.test.js b/test/spec/ol/extent.test.js index 683f4886f7..1d83f0d656 100644 --- a/test/spec/ol/extent.test.js +++ b/test/spec/ol/extent.test.js @@ -7,7 +7,7 @@ describe('ol.extent', function() { describe('buffer', function() { it('buffers an extent by some value', function() { - var extent = [-10, -20, 10, 20]; + const extent = [-10, -20, 10, 20]; expect(_ol_extent_.buffer(extent, 15)).to.eql([-25, -35, 25, 35]); }); @@ -16,8 +16,8 @@ describe('ol.extent', function() { describe('clone', function() { it('creates a copy of an extent', function() { - var extent = _ol_extent_.createOrUpdate(1, 2, 3, 4); - var clone = _ol_extent_.clone(extent); + const extent = _ol_extent_.createOrUpdate(1, 2, 3, 4); + const clone = _ol_extent_.clone(extent); expect(_ol_extent_.equals(extent, clone)).to.be(true); _ol_extent_.extendCoordinate(extent, [10, 20]); @@ -29,44 +29,44 @@ describe('ol.extent', function() { describe('closestSquaredDistanceXY', function() { it('returns correct result when x left of extent', function() { - var extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); - var x = -2; - var y = 0; + const extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); + const x = -2; + const y = 0; expect(_ol_extent_.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); it('returns correct result when x right of extent', function() { - var extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); - var x = 3; - var y = 0; + const extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); + const x = 3; + const y = 0; expect(_ol_extent_.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); it('returns correct result for other x values', function() { - var extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); - var x = 0.5; - var y = 3; + const extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); + const x = 0.5; + const y = 3; expect(_ol_extent_.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); it('returns correct result when y below extent', function() { - var extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); - var x = 0; - var y = -2; + const extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); + const x = 0; + const y = -2; expect(_ol_extent_.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); it('returns correct result when y above extent', function() { - var extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); - var x = 0; - var y = 3; + const extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); + const x = 0; + const y = 3; expect(_ol_extent_.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); it('returns correct result for other y values', function() { - var extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); - var x = 3; - var y = 0.5; + const extent = _ol_extent_.createOrUpdate(0, 0, 1, 1); + const x = 3; + const y = 0.5; expect(_ol_extent_.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); @@ -75,16 +75,16 @@ describe('ol.extent', function() { describe('createOrUpdateFromCoordinate', function() { it('works when no extent passed', function() { - var coords = [0, 1]; - var expected = [0, 1, 0, 1]; - var got = _ol_extent_.createOrUpdateFromCoordinate(coords); + const coords = [0, 1]; + const expected = [0, 1, 0, 1]; + const got = _ol_extent_.createOrUpdateFromCoordinate(coords); expect(got).to.eql(expected); }); it('updates a passed extent', function() { - var extent = _ol_extent_.createOrUpdate(-4, -7, -3, -6); - var coords = [0, 1]; - var expected = [0, 1, 0, 1]; + const extent = _ol_extent_.createOrUpdate(-4, -7, -3, -6); + const coords = [0, 1]; + const expected = [0, 1, 0, 1]; _ol_extent_.createOrUpdateFromCoordinate(coords, extent); expect(extent).to.eql(expected); }); @@ -94,31 +94,31 @@ describe('ol.extent', function() { describe('createOrUpdateFromCoordinates', function() { it('works when single coordinate and no extent passed', function() { - var coords = [[0, 1]]; - var expected = [0, 1, 0, 1]; - var got = _ol_extent_.createOrUpdateFromCoordinates(coords); + const coords = [[0, 1]]; + const expected = [0, 1, 0, 1]; + const got = _ol_extent_.createOrUpdateFromCoordinates(coords); expect(got).to.eql(expected); }); it('changes the passed extent when single coordinate', function() { - var extent = _ol_extent_.createOrUpdate(-4, -7, -3, -6); - var coords = [[0, 1]]; - var expected = [0, 1, 0, 1]; + const extent = _ol_extent_.createOrUpdate(-4, -7, -3, -6); + const coords = [[0, 1]]; + const expected = [0, 1, 0, 1]; _ol_extent_.createOrUpdateFromCoordinates(coords, extent); expect(extent).to.eql(expected); }); it('works when multiple coordinates and no extent passed', function() { - var coords = [[0, 1], [2, 3]]; - var expected = [0, 1, 2, 3]; - var got = _ol_extent_.createOrUpdateFromCoordinates(coords); + const coords = [[0, 1], [2, 3]]; + const expected = [0, 1, 2, 3]; + const got = _ol_extent_.createOrUpdateFromCoordinates(coords); expect(got).to.eql(expected); }); it('changes the passed extent when multiple coordinates given', function() { - var extent = _ol_extent_.createOrUpdate(-4, -7, -3, -6); - var coords = [[0, 1], [-2, -1]]; - var expected = [-2, -1, 0, 1]; + const extent = _ol_extent_.createOrUpdate(-4, -7, -3, -6); + const coords = [[0, 1], [-2, -1]]; + const expected = [-2, -1, 0, 1]; _ol_extent_.createOrUpdateFromCoordinates(coords, extent); expect(extent).to.eql(expected); }); @@ -128,37 +128,37 @@ describe('ol.extent', function() { describe('createOrUpdateFromRings', function() { it('works when single ring and no extent passed', function() { - var ring = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; - var rings = [ring]; - var expected = [0, 0, 2, 2]; - var got = _ol_extent_.createOrUpdateFromRings(rings); + const ring = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; + const rings = [ring]; + const expected = [0, 0, 2, 2]; + const got = _ol_extent_.createOrUpdateFromRings(rings); expect(got).to.eql(expected); }); it('changes the passed extent when single ring given', function() { - var ring = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; - var rings = [ring]; - var extent = [1, 1, 4, 7]; - var expected = [0, 0, 2, 2]; + const ring = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; + const rings = [ring]; + const extent = [1, 1, 4, 7]; + const expected = [0, 0, 2, 2]; _ol_extent_.createOrUpdateFromRings(rings, extent); expect(extent).to.eql(expected); }); it('works when multiple rings and no extent passed', function() { - var ring1 = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; - var ring2 = [[1, 1], [1, 3], [3, 3], [3, 1], [1, 1]]; - var rings = [ring1, ring2]; - var expected = [0, 0, 3, 3]; - var got = _ol_extent_.createOrUpdateFromRings(rings); + const ring1 = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; + const ring2 = [[1, 1], [1, 3], [3, 3], [3, 1], [1, 1]]; + const rings = [ring1, ring2]; + const expected = [0, 0, 3, 3]; + const got = _ol_extent_.createOrUpdateFromRings(rings); expect(got).to.eql(expected); }); it('changes the passed extent when multiple rings given', function() { - var ring1 = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; - var ring2 = [[1, 1], [1, 3], [3, 3], [3, 1], [1, 1]]; - var rings = [ring1, ring2]; - var extent = [1, 1, 4, 7]; - var expected = [0, 0, 3, 3]; + const ring1 = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; + const ring2 = [[1, 1], [1, 3], [3, 3], [3, 1], [1, 1]]; + const rings = [ring1, ring2]; + const extent = [1, 1, 4, 7]; + const expected = [0, 0, 3, 3]; _ol_extent_.createOrUpdateFromRings(rings, extent); expect(extent).to.eql(expected); }); @@ -167,8 +167,8 @@ describe('ol.extent', function() { describe('forEachCorner', function() { - var callbackFalse; - var callbackTrue; + let callbackFalse; + let callbackTrue; beforeEach(function() { callbackFalse = sinon.spy(function() { return false; @@ -179,18 +179,18 @@ describe('ol.extent', function() { }); it('calls the passed callback for each corner', function() { - var extent = [1, 2, 3, 4]; + const extent = [1, 2, 3, 4]; _ol_extent_.forEachCorner(extent, callbackFalse); expect(callbackFalse.callCount).to.be(4); }); it('calls the passed callback with each corner', function() { - var extent = [1, 2, 3, 4]; + const extent = [1, 2, 3, 4]; _ol_extent_.forEachCorner(extent, callbackFalse); - var firstCallFirstArg = callbackFalse.args[0][0]; - var secondCallFirstArg = callbackFalse.args[1][0]; - var thirdCallFirstArg = callbackFalse.args[2][0]; - var fourthCallFirstArg = callbackFalse.args[3][0]; + const firstCallFirstArg = callbackFalse.args[0][0]; + const secondCallFirstArg = callbackFalse.args[1][0]; + const thirdCallFirstArg = callbackFalse.args[2][0]; + const fourthCallFirstArg = callbackFalse.args[3][0]; expect(firstCallFirstArg).to.eql([1, 2]); // bl expect(secondCallFirstArg).to.eql([3, 2]); // br expect(thirdCallFirstArg).to.eql([3, 4]); // tr @@ -198,23 +198,23 @@ describe('ol.extent', function() { }); it('calls a truthy callback only once', function() { - var extent = [1, 2, 3, 4]; + const extent = [1, 2, 3, 4]; _ol_extent_.forEachCorner(extent, callbackTrue); expect(callbackTrue.callCount).to.be(1); }); it('ensures that any corner can cancel the callback execution', function() { - var extent = [1, 2, 3, 4]; - var bottomLeftSpy = sinon.spy(function(corner) { + const extent = [1, 2, 3, 4]; + const bottomLeftSpy = sinon.spy(function(corner) { return (corner[0] === 1 && corner[1] === 2) ? true : false; }); - var bottomRightSpy = sinon.spy(function(corner) { + const bottomRightSpy = sinon.spy(function(corner) { return (corner[0] === 3 && corner[1] === 2) ? true : false; }); - var topRightSpy = sinon.spy(function(corner) { + const topRightSpy = sinon.spy(function(corner) { return (corner[0] === 3 && corner[1] === 4) ? true : false; }); - var topLeftSpy = sinon.spy(function(corner) { + const topLeftSpy = sinon.spy(function(corner) { return (corner[0] === 1 && corner[1] === 4) ? true : false; }); @@ -230,18 +230,18 @@ describe('ol.extent', function() { }); it('returns false eventually, if no invocation returned a truthy value', - function() { - var extent = [1, 2, 3, 4]; - var spy = sinon.spy(); // will return undefined for each corner - var got = _ol_extent_.forEachCorner(extent, spy); - expect(spy.callCount).to.be(4); - expect(got).to.be(false); - } + function() { + const extent = [1, 2, 3, 4]; + const spy = sinon.spy(); // will return undefined for each corner + const got = _ol_extent_.forEachCorner(extent, spy); + expect(spy.callCount).to.be(4); + expect(got).to.be(false); + } ); it('calls the callback with given scope', function() { - var extent = [1, 2, 3, 4]; - var scope = {humpty: 'dumpty'}; + const extent = [1, 2, 3, 4]; + const scope = {humpty: 'dumpty'}; _ol_extent_.forEachCorner(extent, callbackTrue, scope); expect(callbackTrue.calledOn(scope)).to.be(true); }); @@ -250,37 +250,37 @@ describe('ol.extent', function() { describe('getArea', function() { it('returns zero for empty extents', function() { - var emptyExtent = _ol_extent_.createEmpty(); - var areaEmpty = _ol_extent_.getArea(emptyExtent); + const emptyExtent = _ol_extent_.createEmpty(); + const areaEmpty = _ol_extent_.getArea(emptyExtent); expect(areaEmpty).to.be(0); - var extentDeltaXZero = [45, 67, 45, 78]; - var areaDeltaXZero = _ol_extent_.getArea(extentDeltaXZero); + const extentDeltaXZero = [45, 67, 45, 78]; + const areaDeltaXZero = _ol_extent_.getArea(extentDeltaXZero); expect(areaDeltaXZero).to.be(0); - var extentDeltaYZero = [11, 67, 45, 67]; - var areaDeltaYZero = _ol_extent_.getArea(extentDeltaYZero); + const extentDeltaYZero = [11, 67, 45, 67]; + const areaDeltaYZero = _ol_extent_.getArea(extentDeltaYZero); expect(areaDeltaYZero).to.be(0); }); it('calculates correct area for other extents', function() { - var extent = [0, 0, 10, 10]; - var area = _ol_extent_.getArea(extent); + const extent = [0, 0, 10, 10]; + const area = _ol_extent_.getArea(extent); expect(area).to.be(100); }); }); describe('getIntersection()', function() { it('returns the intersection of two extents', function() { - var world = [-180, -90, 180, 90]; - var north = [-180, 0, 180, 90]; - var farNorth = [-180, 45, 180, 90]; - var east = [0, -90, 180, 90]; - var farEast = [90, -90, 180, 90]; - var south = [-180, -90, 180, 0]; - var farSouth = [-180, -90, 180, -45]; - var west = [-180, -90, 0, 90]; - var farWest = [-180, -90, -90, 90]; - var none = _ol_extent_.createEmpty(); + const world = [-180, -90, 180, 90]; + const north = [-180, 0, 180, 90]; + const farNorth = [-180, 45, 180, 90]; + const east = [0, -90, 180, 90]; + const farEast = [90, -90, 180, 90]; + const south = [-180, -90, 180, 0]; + const farSouth = [-180, -90, 180, -45]; + const west = [-180, -90, 0, 90]; + const farWest = [-180, -90, -90, 90]; + const none = _ol_extent_.createEmpty(); expect(_ol_extent_.getIntersection(world, none)).to.eql(none); expect(_ol_extent_.getIntersection(world, north)).to.eql(north); expect(_ol_extent_.getIntersection(world, east)).to.eql(east); @@ -297,7 +297,7 @@ describe('ol.extent', function() { describe('positive', function() { it('returns true', function() { - var extent = [1, 2, 3, 4]; + const extent = [1, 2, 3, 4]; expect(_ol_extent_.containsCoordinate(extent, [1, 2])).to.be.ok(); expect(_ol_extent_.containsCoordinate(extent, [1, 3])).to.be.ok(); expect(_ol_extent_.containsCoordinate(extent, [1, 4])).to.be.ok(); @@ -312,7 +312,7 @@ describe('ol.extent', function() { describe('negative', function() { it('returns false', function() { - var extent = [1, 2, 3, 4]; + const extent = [1, 2, 3, 4]; expect(_ol_extent_.containsCoordinate(extent, [0, 1])).to.not.be(); expect(_ol_extent_.containsCoordinate(extent, [0, 2])).to.not.be(); expect(_ol_extent_.containsCoordinate(extent, [0, 3])).to.not.be(); @@ -335,78 +335,78 @@ describe('ol.extent', function() { describe('coordinateRelationship()', function() { - var extent = [-180, -90, 180, 90]; - var INTERSECTING = 1; - var ABOVE = 2; - var RIGHT = 4; - var BELOW = 8; - var LEFT = 16; + const extent = [-180, -90, 180, 90]; + const INTERSECTING = 1; + const ABOVE = 2; + const RIGHT = 4; + const BELOW = 8; + const LEFT = 16; it('returns intersecting for within', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [0, 0]); + const rel = _ol_extent_.coordinateRelationship(extent, [0, 0]); expect(rel).to.be(INTERSECTING); }); it('returns intersecting for touching top', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [0, 90]); + const rel = _ol_extent_.coordinateRelationship(extent, [0, 90]); expect(rel).to.be(INTERSECTING); }); it('returns intersecting for touching right', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [180, 0]); + const rel = _ol_extent_.coordinateRelationship(extent, [180, 0]); expect(rel).to.be(INTERSECTING); }); it('returns intersecting for touching bottom', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [0, -90]); + const rel = _ol_extent_.coordinateRelationship(extent, [0, -90]); expect(rel).to.be(INTERSECTING); }); it('returns intersecting for touching left', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [-180, 0]); + const rel = _ol_extent_.coordinateRelationship(extent, [-180, 0]); expect(rel).to.be(INTERSECTING); }); it('above for north', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [0, 100]); + const rel = _ol_extent_.coordinateRelationship(extent, [0, 100]); expect(rel).to.be(ABOVE); }); it('above and right for northeast', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [190, 100]); + const rel = _ol_extent_.coordinateRelationship(extent, [190, 100]); expect(rel & ABOVE).to.be(ABOVE); expect(rel & RIGHT).to.be(RIGHT); }); it('right for east', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [190, 0]); + const rel = _ol_extent_.coordinateRelationship(extent, [190, 0]); expect(rel).to.be(RIGHT); }); it('below and right for southeast', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [190, -100]); + const rel = _ol_extent_.coordinateRelationship(extent, [190, -100]); expect(rel & BELOW).to.be(BELOW); expect(rel & RIGHT).to.be(RIGHT); }); it('below for south', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [0, -100]); + const rel = _ol_extent_.coordinateRelationship(extent, [0, -100]); expect(rel).to.be(BELOW); }); it('below and left for southwest', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [-190, -100]); + const rel = _ol_extent_.coordinateRelationship(extent, [-190, -100]); expect(rel & BELOW).to.be(BELOW); expect(rel & LEFT).to.be(LEFT); }); it('left for west', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [-190, 0]); + const rel = _ol_extent_.coordinateRelationship(extent, [-190, 0]); expect(rel).to.be(LEFT); }); it('above and left for northwest', function() { - var rel = _ol_extent_.coordinateRelationship(extent, [-190, 100]); + const rel = _ol_extent_.coordinateRelationship(extent, [-190, 100]); expect(rel & ABOVE).to.be(ABOVE); expect(rel & LEFT).to.be(LEFT); }); @@ -415,39 +415,39 @@ describe('ol.extent', function() { describe('getCenter', function() { it('returns the expected center', function() { - var extent = [1, 2, 3, 4]; - var center = _ol_extent_.getCenter(extent); + const extent = [1, 2, 3, 4]; + const center = _ol_extent_.getCenter(extent); expect(center[0]).to.eql(2); expect(center[1]).to.eql(3); }); it('returns [NaN, NaN] for empty extents', function() { - var extent = _ol_extent_.createEmpty(); - var center = _ol_extent_.getCenter(extent); + const extent = _ol_extent_.createEmpty(); + const center = _ol_extent_.getCenter(extent); expect('' + center[0]).to.be('NaN'); expect('' + center[1]).to.be('NaN'); }); }); describe('getCorner', function() { - var extent = [1, 2, 3, 4]; + const extent = [1, 2, 3, 4]; it('gets the bottom left', function() { - var corner = 'bottom-left'; + const corner = 'bottom-left'; expect(_ol_extent_.getCorner(extent, corner)).to.eql([1, 2]); }); it('gets the bottom right', function() { - var corner = 'bottom-right'; + const corner = 'bottom-right'; expect(_ol_extent_.getCorner(extent, corner)).to.eql([3, 2]); }); it('gets the top left', function() { - var corner = 'top-left'; + const corner = 'top-left'; expect(_ol_extent_.getCorner(extent, corner)).to.eql([1, 4]); }); it('gets the top right', function() { - var corner = 'top-right'; + const corner = 'top-right'; expect(_ol_extent_.getCorner(extent, corner)).to.eql([3, 4]); }); @@ -461,9 +461,9 @@ describe('ol.extent', function() { describe('getEnlargedArea', function() { it('returns enlarged area of two extents', function() { - var extent1 = [-1, -1, 0, 0]; - var extent2 = [0, 0, 1, 1]; - var enlargedArea = _ol_extent_.getEnlargedArea(extent1, extent2); + const extent1 = [-1, -1, 0, 0]; + const extent2 = [0, 0, 1, 1]; + const enlargedArea = _ol_extent_.getEnlargedArea(extent1, extent2); expect(enlargedArea).to.be(4); }); }); @@ -471,8 +471,8 @@ describe('ol.extent', function() { describe('getForViewAndSize', function() { it('works for a unit square', function() { - var extent = _ol_extent_.getForViewAndSize( - [0, 0], 1, 0, [1, 1]); + const extent = _ol_extent_.getForViewAndSize( + [0, 0], 1, 0, [1, 1]); expect(extent[0]).to.be(-0.5); expect(extent[2]).to.be(0.5); expect(extent[1]).to.be(-0.5); @@ -480,8 +480,8 @@ describe('ol.extent', function() { }); it('works for center', function() { - var extent = _ol_extent_.getForViewAndSize( - [5, 10], 1, 0, [1, 1]); + const extent = _ol_extent_.getForViewAndSize( + [5, 10], 1, 0, [1, 1]); expect(extent[0]).to.be(4.5); expect(extent[2]).to.be(5.5); expect(extent[1]).to.be(9.5); @@ -489,8 +489,8 @@ describe('ol.extent', function() { }); it('works for rotation', function() { - var extent = _ol_extent_.getForViewAndSize( - [0, 0], 1, Math.PI / 4, [1, 1]); + const extent = _ol_extent_.getForViewAndSize( + [0, 0], 1, Math.PI / 4, [1, 1]); expect(extent[0]).to.roughlyEqual(-Math.sqrt(0.5), 1e-9); expect(extent[2]).to.roughlyEqual(Math.sqrt(0.5), 1e-9); expect(extent[1]).to.roughlyEqual(-Math.sqrt(0.5), 1e-9); @@ -498,8 +498,8 @@ describe('ol.extent', function() { }); it('works for resolution', function() { - var extent = _ol_extent_.getForViewAndSize( - [0, 0], 2, 0, [1, 1]); + const extent = _ol_extent_.getForViewAndSize( + [0, 0], 2, 0, [1, 1]); expect(extent[0]).to.be(-1); expect(extent[2]).to.be(1); expect(extent[1]).to.be(-1); @@ -507,8 +507,8 @@ describe('ol.extent', function() { }); it('works for size', function() { - var extent = _ol_extent_.getForViewAndSize( - [0, 0], 1, 0, [10, 5]); + const extent = _ol_extent_.getForViewAndSize( + [0, 0], 1, 0, [10, 5]); expect(extent[0]).to.be(-5); expect(extent[2]).to.be(5); expect(extent[1]).to.be(-2.5); @@ -519,30 +519,30 @@ describe('ol.extent', function() { describe('getSize', function() { it('returns the expected size', function() { - var extent = [0, 1, 2, 4]; - var size = _ol_extent_.getSize(extent); + const extent = [0, 1, 2, 4]; + const size = _ol_extent_.getSize(extent); expect(size).to.eql([2, 3]); }); }); describe('getIntersectionArea', function() { it('returns correct area when extents intersect', function() { - var extent1 = [0, 0, 2, 2]; - var extent2 = [1, 1, 3, 3]; - var intersectionArea = _ol_extent_.getIntersectionArea(extent1, extent2); + const extent1 = [0, 0, 2, 2]; + const extent2 = [1, 1, 3, 3]; + const intersectionArea = _ol_extent_.getIntersectionArea(extent1, extent2); expect(intersectionArea).to.be(1); }); it('returns 0 when extents do not intersect', function() { - var extent1 = [0, 0, 1, 1]; - var extent2 = [2, 2, 3, 3]; - var intersectionArea = _ol_extent_.getIntersectionArea(extent1, extent2); + const extent1 = [0, 0, 1, 1]; + const extent2 = [2, 2, 3, 3]; + const intersectionArea = _ol_extent_.getIntersectionArea(extent1, extent2); expect(intersectionArea).to.be(0); }); }); describe('getMargin', function() { it('returns the correct margin (sum of width and height)', function() { - var extent = [1, 2, 3, 4]; + const extent = [1, 2, 3, 4]; expect(_ol_extent_.getMargin(extent)).to.be(4); }); }); @@ -550,8 +550,8 @@ describe('ol.extent', function() { describe('intersects', function() { it('returns the expected value', function() { - var intersects = _ol_extent_.intersects; - var extent = [50, 50, 100, 100]; + const intersects = _ol_extent_.intersects; + const extent = [50, 50, 100, 100]; expect(intersects(extent, extent)).to.be(true); expect(intersects(extent, [20, 20, 80, 80])).to.be(true); expect(intersects(extent, [20, 50, 80, 100])).to.be(true); @@ -584,7 +584,7 @@ describe('ol.extent', function() { describe('scaleFromCenter', function() { it('scales the extent from its center', function() { - var extent = [1, 1, 3, 3]; + const extent = [1, 1, 3, 3]; _ol_extent_.scaleFromCenter(extent, 2); expect(extent[0]).to.eql(0); expect(extent[2]).to.eql(4); @@ -595,139 +595,139 @@ describe('ol.extent', function() { describe('intersectsSegment()', function() { - var extent = [-180, -90, 180, 90]; - var north = [0, 100]; - var northeast = [190, 100]; - var east = [190, 0]; - var southeast = [190, -100]; - var south = [0, -100]; - var southwest = [-190, -100]; - var west = [-190, 0]; - var northwest = [-190, 100]; - var center = [0, 0]; - var top = [0, 90]; - var right = [180, 0]; - var bottom = [-90, 0]; - var left = [-180, 0]; - var inside = [10, 10]; + const extent = [-180, -90, 180, 90]; + const north = [0, 100]; + const northeast = [190, 100]; + const east = [190, 0]; + const southeast = [190, -100]; + const south = [0, -100]; + const southwest = [-190, -100]; + const west = [-190, 0]; + const northwest = [-190, 100]; + const center = [0, 0]; + const top = [0, 90]; + const right = [180, 0]; + const bottom = [-90, 0]; + const left = [-180, 0]; + const inside = [10, 10]; it('returns true if contained', function() { - var intersects = _ol_extent_.intersectsSegment(extent, center, inside); + const intersects = _ol_extent_.intersectsSegment(extent, center, inside); expect(intersects).to.be(true); }); it('returns true if crosses top', function() { - var intersects = _ol_extent_.intersectsSegment(extent, center, north); + const intersects = _ol_extent_.intersectsSegment(extent, center, north); expect(intersects).to.be(true); }); it('returns true if crosses right', function() { - var intersects = _ol_extent_.intersectsSegment(extent, center, east); + const intersects = _ol_extent_.intersectsSegment(extent, center, east); expect(intersects).to.be(true); }); it('returns true if crosses bottom', function() { - var intersects = _ol_extent_.intersectsSegment(extent, center, south); + const intersects = _ol_extent_.intersectsSegment(extent, center, south); expect(intersects).to.be(true); }); it('returns true if crosses left', function() { - var intersects = _ol_extent_.intersectsSegment(extent, center, west); + const intersects = _ol_extent_.intersectsSegment(extent, center, west); expect(intersects).to.be(true); }); it('returns false if above', function() { - var intersects = _ol_extent_.intersectsSegment(extent, northwest, north); + const intersects = _ol_extent_.intersectsSegment(extent, northwest, north); expect(intersects).to.be(false); }); it('returns false if right', function() { - var intersects = _ol_extent_.intersectsSegment(extent, northeast, east); + const intersects = _ol_extent_.intersectsSegment(extent, northeast, east); expect(intersects).to.be(false); }); it('returns false if below', function() { - var intersects = _ol_extent_.intersectsSegment(extent, south, southwest); + const intersects = _ol_extent_.intersectsSegment(extent, south, southwest); expect(intersects).to.be(false); }); it('returns false if left', function() { - var intersects = _ol_extent_.intersectsSegment(extent, west, southwest); + const intersects = _ol_extent_.intersectsSegment(extent, west, southwest); expect(intersects).to.be(false); }); it('returns true if crosses top to bottom', function() { - var intersects = _ol_extent_.intersectsSegment(extent, north, south); + const intersects = _ol_extent_.intersectsSegment(extent, north, south); expect(intersects).to.be(true); }); it('returns true if crosses bottom to top', function() { - var intersects = _ol_extent_.intersectsSegment(extent, south, north); + const intersects = _ol_extent_.intersectsSegment(extent, south, north); expect(intersects).to.be(true); }); it('returns true if crosses left to right', function() { - var intersects = _ol_extent_.intersectsSegment(extent, west, east); + const intersects = _ol_extent_.intersectsSegment(extent, west, east); expect(intersects).to.be(true); }); it('returns true if crosses right to left', function() { - var intersects = _ol_extent_.intersectsSegment(extent, east, west); + const intersects = _ol_extent_.intersectsSegment(extent, east, west); expect(intersects).to.be(true); }); it('returns true if crosses northwest to east', function() { - var intersects = _ol_extent_.intersectsSegment(extent, northwest, east); + const intersects = _ol_extent_.intersectsSegment(extent, northwest, east); expect(intersects).to.be(true); }); it('returns true if crosses south to west', function() { - var intersects = _ol_extent_.intersectsSegment(extent, south, west); + const intersects = _ol_extent_.intersectsSegment(extent, south, west); expect(intersects).to.be(true); }); it('returns true if touches top', function() { - var intersects = _ol_extent_.intersectsSegment(extent, northwest, top); + const intersects = _ol_extent_.intersectsSegment(extent, northwest, top); expect(intersects).to.be(true); }); it('returns true if touches right', function() { - var intersects = _ol_extent_.intersectsSegment(extent, southeast, right); + const intersects = _ol_extent_.intersectsSegment(extent, southeast, right); expect(intersects).to.be(true); }); it('returns true if touches bottom', function() { - var intersects = _ol_extent_.intersectsSegment(extent, bottom, south); + const intersects = _ol_extent_.intersectsSegment(extent, bottom, south); expect(intersects).to.be(true); }); it('returns true if touches left', function() { - var intersects = _ol_extent_.intersectsSegment(extent, left, west); + const intersects = _ol_extent_.intersectsSegment(extent, left, west); expect(intersects).to.be(true); }); it('works for zero length inside', function() { - var intersects = _ol_extent_.intersectsSegment(extent, center, center); + const intersects = _ol_extent_.intersectsSegment(extent, center, center); expect(intersects).to.be(true); }); it('works for zero length outside', function() { - var intersects = _ol_extent_.intersectsSegment(extent, north, north); + const intersects = _ol_extent_.intersectsSegment(extent, north, north); expect(intersects).to.be(false); }); it('works for left/right intersection spanning top to bottom', function() { - var extent = [2, 1, 3, 4]; - var start = [0, 0]; - var end = [5, 5]; + const extent = [2, 1, 3, 4]; + const start = [0, 0]; + const end = [5, 5]; expect(_ol_extent_.intersectsSegment(extent, start, end)).to.be(true); expect(_ol_extent_.intersectsSegment(extent, end, start)).to.be(true); }); it('works for top/bottom intersection spanning left to right', function() { - var extent = [1, 2, 4, 3]; - var start = [0, 0]; - var end = [5, 5]; + const extent = [1, 2, 4, 3]; + const start = [0, 0]; + const end = [5, 5]; expect(_ol_extent_.intersectsSegment(extent, start, end)).to.be(true); expect(_ol_extent_.intersectsSegment(extent, end, start)).to.be(true); }); @@ -737,37 +737,37 @@ describe('ol.extent', function() { describe('#applyTransform()', function() { it('does transform', function() { - var transformFn = getTransform('EPSG:4326', 'EPSG:3857'); - var sourceExtent = [-15, -30, 45, 60]; - var destinationExtent = _ol_extent_.applyTransform( - sourceExtent, transformFn); + const transformFn = getTransform('EPSG:4326', 'EPSG:3857'); + const sourceExtent = [-15, -30, 45, 60]; + const destinationExtent = _ol_extent_.applyTransform( + sourceExtent, transformFn); expect(destinationExtent).not.to.be(undefined); expect(destinationExtent).not.to.be(null); // FIXME check values with third-party tool expect(destinationExtent[0]) - .to.roughlyEqual(-1669792.3618991037, 1e-9); + .to.roughlyEqual(-1669792.3618991037, 1e-9); expect(destinationExtent[2]).to.roughlyEqual(5009377.085697311, 1e-9); expect(destinationExtent[1]).to.roughlyEqual(-3503549.843504376, 1e-8); expect(destinationExtent[3]).to.roughlyEqual(8399737.889818361, 1e-8); }); it('takes arbitrary function', function() { - var transformFn = function(input, output, opt_dimension) { - var dimension = opt_dimension !== undefined ? opt_dimension : 2; + const transformFn = function(input, output, opt_dimension) { + const dimension = opt_dimension !== undefined ? opt_dimension : 2; if (output === undefined) { output = new Array(input.length); } - var n = input.length; - var i; + const n = input.length; + let i; for (i = 0; i < n; i += dimension) { output[i] = -input[i]; output[i + 1] = -input[i + 1]; } return output; }; - var sourceExtent = [-15, -30, 45, 60]; - var destinationExtent = _ol_extent_.applyTransform( - sourceExtent, transformFn); + const sourceExtent = [-15, -30, 45, 60]; + const destinationExtent = _ol_extent_.applyTransform( + sourceExtent, transformFn); expect(destinationExtent).not.to.be(undefined); expect(destinationExtent).not.to.be(null); expect(destinationExtent[0]).to.be(-45); diff --git a/test/spec/ol/feature.test.js b/test/spec/ol/feature.test.js index 36f2761450..cdac229adc 100644 --- a/test/spec/ol/feature.test.js +++ b/test/spec/ol/feature.test.js @@ -9,29 +9,29 @@ describe('ol.Feature', function() { describe('constructor', function() { it('creates a new feature', function() { - var feature = new Feature(); + const feature = new Feature(); expect(feature).to.be.a(Feature); }); it('takes properties', function() { - var feature = new Feature({ + const feature = new Feature({ foo: 'bar' }); expect(feature.get('foo')).to.be('bar'); }); it('can store the feature\'s commonly used id', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setId('foo'); expect(feature.getId()).to.be('foo'); }); it('will set the default geometry', function() { - var feature = new Feature({ + const feature = new Feature({ geometry: new Point([10, 20]), foo: 'bar' }); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.a(Point); expect(feature.get('geometry')).to.be(geometry); }); @@ -41,7 +41,7 @@ describe('ol.Feature', function() { describe('#get()', function() { it('returns values set at construction', function() { - var feature = new Feature({ + const feature = new Feature({ a: 'first', b: 'second' }); @@ -50,12 +50,12 @@ describe('ol.Feature', function() { }); it('returns undefined for unset attributes', function() { - var feature = new Feature(); + const feature = new Feature(); expect(feature.get('a')).to.be(undefined); }); it('returns values set by set', function() { - var feature = new Feature(); + const feature = new Feature(); feature.set('a', 'b'); expect(feature.get('a')).to.be('b'); }); @@ -65,16 +65,16 @@ describe('ol.Feature', function() { describe('#getProperties()', function() { it('returns an object with all attributes', function() { - var point = new Point([15, 30]); - var feature = new Feature({ + const point = new Point([15, 30]); + const feature = new Feature({ foo: 'bar', ten: 10, geometry: point }); - var attributes = feature.getProperties(); + const attributes = feature.getProperties(); - var keys = Object.keys(attributes); + const keys = Object.keys(attributes); expect(keys.sort()).to.eql(['foo', 'geometry', 'ten']); expect(attributes.foo).to.be('bar'); @@ -83,8 +83,8 @@ describe('ol.Feature', function() { }); it('is empty by default', function() { - var feature = new Feature(); - var properties = feature.getProperties(); + const feature = new Feature(); + const properties = feature.getProperties(); expect(_ol_obj_.isEmpty(properties)).to.be(true); }); @@ -93,37 +93,37 @@ describe('ol.Feature', function() { describe('#getGeometry()', function() { - var point = new Point([15, 30]); + const point = new Point([15, 30]); it('returns undefined for unset geometry', function() { - var feature = new Feature(); + const feature = new Feature(); expect(feature.getGeometry()).to.be(undefined); }); it('returns null for null geometry (constructor)', function() { - var feature = new Feature(null); + const feature = new Feature(null); expect(feature.getGeometry()).to.be(null); }); it('returns null for null geometry (setGeometry())', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setGeometry(null); expect(feature.getGeometry()).to.be(null); }); it('gets the geometry set at construction', function() { - var feature = new Feature({ + const feature = new Feature({ geometry: point }); expect(feature.getGeometry()).to.be(point); }); it('gets any geometry set by setGeometry', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setGeometry(point); expect(feature.getGeometry()).to.be(point); - var point2 = new Point([1, 2]); + const point2 = new Point([1, 2]); feature.setGeometry(point2); expect(feature.getGeometry()).to.be(point2); }); @@ -133,7 +133,7 @@ describe('ol.Feature', function() { describe('#set()', function() { it('sets values', function() { - var feature = new Feature({ + const feature = new Feature({ a: 'first', b: 'second' }); @@ -142,8 +142,8 @@ describe('ol.Feature', function() { }); it('can be used to set the geometry', function() { - var point = new Point([3, 4]); - var feature = new Feature({ + const point = new Point([3, 4]); + const feature = new Feature({ geometry: new Point([1, 2]) }); feature.set('geometry', point); @@ -153,7 +153,7 @@ describe('ol.Feature', function() { it('can be used to set attributes with arbitrary names', function() { - var feature = new Feature(); + const feature = new Feature(); feature.set('toString', 'string'); expect(feature.get('toString')).to.be('string'); @@ -171,21 +171,21 @@ describe('ol.Feature', function() { describe('#setGeometry()', function() { - var point = new Point([15, 30]); + const point = new Point([15, 30]); it('sets the default geometry', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setGeometry(point); expect(feature.get('geometry')).to.be(point); }); it('replaces previous default geometry', function() { - var feature = new Feature({ + const feature = new Feature({ geometry: point }); expect(feature.getGeometry()).to.be(point); - var point2 = new Point([1, 2]); + const point2 = new Point([1, 2]); feature.setGeometry(point2); expect(feature.getGeometry()).to.be(point2); }); @@ -194,14 +194,14 @@ describe('ol.Feature', function() { describe('#setGeometryName()', function() { - var point = new Point([15, 30]); + const point = new Point([15, 30]); it('sets property where to to look at geometry', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setGeometry(point); expect(feature.getGeometry()).to.be(point); - var point2 = new Point([1, 2]); + const point2 = new Point([1, 2]); feature.set('altGeometry', point2); expect(feature.getGeometry()).to.be(point); feature.setGeometryName('altGeometry'); @@ -214,22 +214,22 @@ describe('ol.Feature', function() { }); it('changes property listener', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setGeometry(point); - var point2 = new Point([1, 2]); + const point2 = new Point([1, 2]); feature.set('altGeometry', point2); feature.setGeometryName('altGeometry'); - var spy = sinon.spy(); + const spy = sinon.spy(); feature.on('change', spy); point2.setCoordinates([0, 2]); expect(spy.callCount).to.be(1); }); it('can use a different geometry name', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setGeometryName('foo'); - var point = new Point([10, 20]); + const point = new Point([10, 20]); feature.setGeometry(point); expect(feature.getGeometry()).to.be(point); }); @@ -239,14 +239,14 @@ describe('ol.Feature', function() { describe('#setId()', function() { it('sets the feature identifier', function() { - var feature = new Feature(); + const feature = new Feature(); expect(feature.getId()).to.be(undefined); feature.setId('foo'); expect(feature.getId()).to.be('foo'); }); it('accepts a string or number', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setId('foo'); expect(feature.getId()).to.be('foo'); feature.setId(2); @@ -254,7 +254,7 @@ describe('ol.Feature', function() { }); it('dispatches the "change" event', function(done) { - var feature = new Feature(); + const feature = new Feature(); feature.on('change', function() { expect(feature.getId()).to.be('foo'); done(); @@ -266,29 +266,29 @@ describe('ol.Feature', function() { describe('#getStyleFunction()', function() { - var styleFunction = function(resolution) { + const styleFunction = function(resolution) { return null; }; it('returns undefined after construction', function() { - var feature = new Feature(); + const feature = new Feature(); expect(feature.getStyleFunction()).to.be(undefined); }); it('returns the function passed to setStyle', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setStyle(styleFunction); expect(feature.getStyleFunction()).to.be(styleFunction); }); it('does not get confused with user "styleFunction" property', function() { - var feature = new Feature(); + const feature = new Feature(); feature.set('styleFunction', 'foo'); expect(feature.getStyleFunction()).to.be(undefined); }); it('does not get confused with "styleFunction" option', function() { - var feature = new Feature({ + const feature = new Feature({ styleFunction: 'foo' }); expect(feature.getStyleFunction()).to.be(undefined); @@ -298,28 +298,28 @@ describe('ol.Feature', function() { describe('#setStyle()', function() { - var style = new Style(); + const style = new Style(); - var styleFunction = function(feature, resolution) { + const styleFunction = function(feature, resolution) { return resolution; }; it('accepts a single style', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setStyle(style); - var func = feature.getStyleFunction(); + const func = feature.getStyleFunction(); expect(func()).to.eql([style]); }); it('accepts an array of styles', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setStyle([style]); - var func = feature.getStyleFunction(); + const func = feature.getStyleFunction(); expect(func()).to.eql([style]); }); it('accepts a style function', function() { - var feature = new Feature(); + const feature = new Feature(); function featureStyleFunction(resolution) { return styleFunction(this, resolution); } @@ -329,14 +329,14 @@ describe('ol.Feature', function() { }); it('accepts a layer style function', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setStyle(styleFunction); expect(feature.getStyleFunction()).to.not.be(styleFunction); expect(feature.getStyleFunction()(42)).to.be(42); }); it('accepts null', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setStyle(style); feature.setStyle(null); expect(feature.getStyle()).to.be(null); @@ -344,8 +344,8 @@ describe('ol.Feature', function() { }); it('dispatches a change event', function() { - var feature = new Feature(); - var spy = sinon.spy(); + const feature = new Feature(); + const spy = sinon.spy(); feature.on('change', spy); feature.setStyle(style); expect(spy.callCount).to.be(1); @@ -355,14 +355,14 @@ describe('ol.Feature', function() { describe('#getStyle()', function() { - var style = new Style(); + const style = new Style(); - var styleFunction = function(resolution) { + const styleFunction = function(resolution) { return null; }; it('returns what is passed to setStyle', function() { - var feature = new Feature(); + const feature = new Feature(); expect(feature.getStyle()).to.be(null); @@ -378,7 +378,7 @@ describe('ol.Feature', function() { }); it('does not get confused with "style" option to constructor', function() { - var feature = new Feature({ + const feature = new Feature({ style: 'foo' }); @@ -386,7 +386,7 @@ describe('ol.Feature', function() { }); it('does not get confused with user set "style" property', function() { - var feature = new Feature(); + const feature = new Feature(); feature.set('style', 'foo'); expect(feature.getStyle()).to.be(null); @@ -397,23 +397,23 @@ describe('ol.Feature', function() { describe('#clone', function() { it('correctly clones features', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setProperties({'fookey': 'fooval'}); feature.setId(1); feature.setGeometryName('geom'); - var geometry = new Point([1, 2]); + const geometry = new Point([1, 2]); feature.setGeometry(geometry); - var style = new Style({}); + const style = new Style({}); feature.setStyle(style); feature.set('barkey', 'barval'); - var clone = feature.clone(); + const clone = feature.clone(); expect(clone.get('fookey')).to.be('fooval'); expect(clone.getId()).to.be(undefined); expect(clone.getGeometryName()).to.be('geom'); - var geometryClone = clone.getGeometry(); + const geometryClone = clone.getGeometry(); expect(geometryClone).not.to.be(geometry); - var coordinates = geometryClone.getFlatCoordinates(); + const coordinates = geometryClone.getFlatCoordinates(); expect(coordinates[0]).to.be(1); expect(coordinates[1]).to.be(2); expect(clone.getStyle()).to.be(style); @@ -421,10 +421,10 @@ describe('ol.Feature', function() { }); it('correctly clones features with no geometry and no style', function() { - var feature = new Feature(); + const feature = new Feature(); feature.set('fookey', 'fooval'); - var clone = feature.clone(); + const clone = feature.clone(); expect(clone.get('fookey')).to.be('fooval'); expect(clone.getGeometry()).to.be(undefined); expect(clone.getStyle()).to.be(null); @@ -434,37 +434,37 @@ describe('ol.Feature', function() { describe('#setGeometry()', function() { it('dispatches a change event when geometry is set to null', - function() { - var feature = new Feature({ - geometry: new Point([0, 0]) - }); - var spy = sinon.spy(); - feature.on('change', spy); - feature.setGeometry(null); - expect(spy.callCount).to.be(1); + function() { + const feature = new Feature({ + geometry: new Point([0, 0]) }); + const spy = sinon.spy(); + feature.on('change', spy); + feature.setGeometry(null); + expect(spy.callCount).to.be(1); + }); }); }); describe('ol.Feature.createStyleFunction()', function() { - var style = new Style(); + const style = new Style(); it('creates a feature style function from a single style', function() { - var styleFunction = Feature.createStyleFunction(style); + const styleFunction = Feature.createStyleFunction(style); expect(styleFunction()).to.eql([style]); }); it('creates a feature style function from an array of styles', function() { - var styleFunction = Feature.createStyleFunction([style]); + const styleFunction = Feature.createStyleFunction([style]); expect(styleFunction()).to.eql([style]); }); it('passes through a function', function() { - var original = function() { + const original = function() { return [style]; }; - var styleFunction = Feature.createStyleFunction(original); + const styleFunction = Feature.createStyleFunction(original); expect(styleFunction).to.be(original); }); diff --git a/test/spec/ol/featureloader.test.js b/test/spec/ol/featureloader.test.js index 67643fb119..8938321a50 100644 --- a/test/spec/ol/featureloader.test.js +++ b/test/spec/ol/featureloader.test.js @@ -6,10 +6,10 @@ import VectorSource from '../../../src/ol/source/Vector.js'; describe('ol.featureloader', function() { describe('ol.featureloader.xhr', function() { - var loader; - var source; - var url; - var format; + let loader; + let source; + let url; + let format; beforeEach(function() { url = 'spec/ol/data/point.json'; @@ -42,9 +42,9 @@ describe('ol.featureloader', function() { }); it('sends the correct arguments to the urlFunction', function(done) { - var extent = []; - var resolution = 1; - var projection = 'EPSG:3857'; + const extent = []; + const resolution = 1; + const projection = 'EPSG:3857'; url = function(extent_, resolution_, projection_) { expect(extent_).to.eql(extent); expect(resolution_).to.eql(resolution); diff --git a/test/spec/ol/format/esrijson.test.js b/test/spec/ol/format/esrijson.test.js index e59f28ff6d..f09ad847ef 100644 --- a/test/spec/ol/format/esrijson.test.js +++ b/test/spec/ol/format/esrijson.test.js @@ -13,12 +13,12 @@ import {get as getProjection, transform} from '../../../../src/ol/proj.js'; describe('ol.format.EsriJSON', function() { - var format; + let format; beforeEach(function() { format = new EsriJSON(); }); - var pointEsriJSON = { + const pointEsriJSON = { geometry: { x: 102.0, y: 0.5 @@ -28,7 +28,7 @@ describe('ol.format.EsriJSON', function() { } }; - var multiPointEsriJSON = { + const multiPointEsriJSON = { geometry: { 'points': [[102.0, 0.0], [103.0, 1.0]] }, @@ -37,7 +37,7 @@ describe('ol.format.EsriJSON', function() { } }; - var lineStringEsriJSON = { + const lineStringEsriJSON = { geometry: { paths: [[ [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0] @@ -49,7 +49,7 @@ describe('ol.format.EsriJSON', function() { } }; - var multiLineStringEsriJSON = { + const multiLineStringEsriJSON = { geometry: { paths: [[ [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0] @@ -63,7 +63,7 @@ describe('ol.format.EsriJSON', function() { } }; - var polygonEsriJSON = { + const polygonEsriJSON = { geometry: { rings: [[ [100.0, 0.0], [100.0, 1.0], [101.0, 1.0], [101.0, 0.0] @@ -75,7 +75,7 @@ describe('ol.format.EsriJSON', function() { } }; - var multiPolygonEsriJSON = { + const multiPolygonEsriJSON = { geometry: { rings: [[ [0, 1], @@ -96,11 +96,11 @@ describe('ol.format.EsriJSON', function() { } }; - var featureCollectionEsriJSON = { + const featureCollectionEsriJSON = { features: [pointEsriJSON, lineStringEsriJSON, polygonEsriJSON] }; - var data = { + const data = { features: [{ attributes: { 'LINK_ID': 573730499, @@ -160,38 +160,38 @@ describe('ol.format.EsriJSON', function() { describe('#readFeature', function() { it('can read a single point feature', function() { - var feature = format.readFeature(pointEsriJSON); + const feature = format.readFeature(pointEsriJSON); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.an(Point); expect(geometry.getCoordinates()).to.eql([102.0, 0.5]); expect(feature.get('prop0')).to.be('value0'); }); it('can read a single multipoint feature', function() { - var feature = format.readFeature(multiPointEsriJSON); + const feature = format.readFeature(multiPointEsriJSON); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.an(MultiPoint); expect(geometry.getCoordinates()).to.eql([[102.0, 0.0], [103.0, 1.0]]); expect(feature.get('prop0')).to.be('value0'); }); it('can read a single line string feature', function() { - var feature = format.readFeature(lineStringEsriJSON); + const feature = format.readFeature(lineStringEsriJSON); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.an(LineString); expect(geometry.getCoordinates()).to.eql( - [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]]); + [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]]); expect(feature.get('prop0')).to.be('value0'); expect(feature.get('prop1')).to.be(0.0); }); it('can read a multi line string feature', function() { - var feature = format.readFeature(multiLineStringEsriJSON); + const feature = format.readFeature(multiLineStringEsriJSON); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.an(MultiLineString); expect(geometry.getCoordinates()).to.eql([ [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]], @@ -202,9 +202,9 @@ describe('ol.format.EsriJSON', function() { }); it('can read a single polygon feature', function() { - var feature = format.readFeature(polygonEsriJSON); + const feature = format.readFeature(polygonEsriJSON); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.an(Polygon); expect(geometry.getCoordinates()).to.eql([[ [100.0, 0.0], [100.0, 1.0], [101.0, 1.0], [101.0, 0.0] @@ -214,9 +214,9 @@ describe('ol.format.EsriJSON', function() { }); it('can read a multi polygon feature', function() { - var feature = format.readFeature(multiPolygonEsriJSON); + const feature = format.readFeature(multiPolygonEsriJSON); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.an(MultiPolygon); expect(geometry.getCoordinates()).to.eql([ [[[0, 1], [1, 4], [4, 3], [3, 0]], [[2, 2], [3, 2], [3, 3], [2, 3]]], @@ -225,7 +225,7 @@ describe('ol.format.EsriJSON', function() { }); it('can read a feature collection', function() { - var features = format.readFeatures(featureCollectionEsriJSON); + const features = format.readFeatures(featureCollectionEsriJSON); expect(features).to.have.length(3); expect(features[0].getGeometry()).to.be.an(Point); expect(features[1].getGeometry()).to.be.an(LineString); @@ -233,23 +233,23 @@ describe('ol.format.EsriJSON', function() { }); it('can read and transform a point', function() { - var feature = format.readFeatures(pointEsriJSON, { + const feature = format.readFeatures(pointEsriJSON, { featureProjection: 'EPSG:3857', dataProjection: 'EPSG:4326' }); expect(feature[0].getGeometry()).to.be.an(Point); expect(feature[0].getGeometry().getCoordinates()).to.eql( - transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); + transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); }); it('can read and transform a feature collection', function() { - var features = format.readFeatures(featureCollectionEsriJSON, { + const features = format.readFeatures(featureCollectionEsriJSON, { featureProjection: 'EPSG:3857', dataProjection: 'EPSG:4326' }); expect(features[0].getGeometry()).to.be.an(Point); expect(features[0].getGeometry().getCoordinates()).to.eql( - transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); + transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); expect(features[1].getGeometry().getCoordinates()).to.eql([ transform([102.0, 0.0], 'EPSG:4326', 'EPSG:3857'), transform([103.0, 1.0], 'EPSG:4326', 'EPSG:3857'), @@ -265,8 +265,8 @@ describe('ol.format.EsriJSON', function() { }); it('can create a feature with a specific geometryName', function() { - var feature = new EsriJSON({geometryName: 'the_geom'}). - readFeature(pointEsriJSON); + const feature = new EsriJSON({geometryName: 'the_geom'}). + readFeature(pointEsriJSON); expect(feature.getGeometryName()).to.be('the_geom'); expect(feature.getGeometry()).to.be.an(Point); }); @@ -276,45 +276,45 @@ describe('ol.format.EsriJSON', function() { describe('#readFeatures', function() { it('parses feature collection', function() { - var str = JSON.stringify(data); - var array = format.readFeatures(str); + const str = JSON.stringify(data); + const array = format.readFeatures(str); expect(array.length).to.be(2); - var first = array[0]; + const first = array[0]; expect(first).to.be.a(Feature); expect(first.get('LINK_ID')).to.be(573730499); - var firstGeom = first.getGeometry(); + const firstGeom = first.getGeometry(); expect(firstGeom).to.be.a(LineString); - var second = array[1]; + const second = array[1]; expect(second).to.be.a(Feature); expect(second.get('ST_NAME')).to.be('BRUNNSGATAN'); - var secondGeom = second.getGeometry(); + const secondGeom = second.getGeometry(); expect(secondGeom).to.be.a(LineString); }); it('parses ksfields.geojson', function(done) { afterLoadText('spec/ol/format/esrijson/ksfields.json', function(text) { - var result = format.readFeatures(text); + const result = format.readFeatures(text); expect(result.length).to.be(9); - var first = result[0]; + const first = result[0]; expect(first).to.be.a(Feature); expect(first.get('field_name')).to.be('EUDORA'); expect(first.getId()).to.be(6406); - var firstGeom = first.getGeometry(); + const firstGeom = first.getGeometry(); expect(firstGeom).to.be.a(Polygon); expect(_ol_extent_.equals(firstGeom.getExtent(), [ -10585772.743554419, 4712365.161160459, -10579560.16462974, 4716567.373073828 ])).to.be(true); - var last = result[8]; + const last = result[8]; expect(last).to.be.a(Feature); expect(last.get('field_name')).to.be('FEAGINS'); expect(last.getId()).to.be(6030); - var lastGeom = last.getGeometry(); + const lastGeom = last.getGeometry(); expect(lastGeom).to.be.a(Polygon); expect(_ol_extent_.equals(lastGeom.getExtent(), [ -10555714.026858449, 4576511.565880965, @@ -330,148 +330,148 @@ describe('ol.format.EsriJSON', function() { describe('#readGeometry', function() { it('parses point', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ x: 10, y: 20 }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(Point); expect(obj.getCoordinates()).to.eql([10, 20]); expect(obj.getLayout()).to.eql('XY'); }); it('parses XYZ point', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ x: 10, y: 20, z: 10 }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(Point); expect(obj.getCoordinates()).to.eql([10, 20, 10]); expect(obj.getLayout()).to.eql('XYZ'); }); it('parses XYM point', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ x: 10, y: 20, m: 10 }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(Point); expect(obj.getCoordinates()).to.eql([10, 20, 10]); expect(obj.getLayout()).to.eql('XYM'); }); it('parses XYZM point', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ x: 10, y: 20, z: 0, m: 10 }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(Point); expect(obj.getCoordinates()).to.eql([10, 20, 0, 10]); expect(obj.getLayout()).to.eql('XYZM'); }); it('parses multipoint', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ points: [[10, 20], [20, 30]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiPoint); expect(obj.getCoordinates()).to.eql([[10, 20], [20, 30]]); expect(obj.getLayout()).to.eql('XY'); }); it('parses XYZ multipoint', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ points: [[10, 20, 0], [20, 30, 0]], hasZ: true }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiPoint); expect(obj.getCoordinates()).to.eql([[10, 20, 0], [20, 30, 0]]); expect(obj.getLayout()).to.eql('XYZ'); }); it('parses XYM multipoint', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ points: [[10, 20, 0], [20, 30, 0]], hasM: true }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiPoint); expect(obj.getCoordinates()).to.eql([[10, 20, 0], [20, 30, 0]]); expect(obj.getLayout()).to.eql('XYM'); }); it('parses XYZM multipoint', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ points: [[10, 20, 0, 1], [20, 30, 0, 1]], hasZ: true, hasM: true }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiPoint); expect(obj.getCoordinates()).to.eql([[10, 20, 0, 1], [20, 30, 0, 1]]); expect(obj.getLayout()).to.eql('XYZM'); }); it('parses linestring', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ paths: [[[10, 20], [30, 40]]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(LineString); expect(obj.getCoordinates()).to.eql([[10, 20], [30, 40]]); expect(obj.getLayout()).to.eql('XY'); }); it('parses XYZ linestring', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ hasZ: true, paths: [[[10, 20, 1534], [30, 40, 1420]]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(LineString); expect(obj.getLayout()).to.eql('XYZ'); expect(obj.getCoordinates()).to.eql([[10, 20, 1534], [30, 40, 1420]]); }); it('parses XYM linestring', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ hasM: true, paths: [[[10, 20, 1534], [30, 40, 1420]]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(LineString); expect(obj.getLayout()).to.eql('XYM'); expect(obj.getCoordinates()).to.eql([[10, 20, 1534], [30, 40, 1420]]); }); it('parses XYZM linestring', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ hasZ: true, hasM: true, paths: [[[10, 20, 1534, 1], [30, 40, 1420, 2]]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(LineString); expect(obj.getLayout()).to.eql('XYZM'); expect(obj.getCoordinates()).to.eql([[10, 20, 1534, 1], @@ -479,14 +479,14 @@ describe('ol.format.EsriJSON', function() { }); it('parses multilinestring', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ paths: [[ [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0] ], [ [105.0, 3.0], [106.0, 4.0], [107.0, 3.0], [108.0, 4.0] ]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiLineString); expect(obj.getCoordinates()).to.eql([ [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]], @@ -496,7 +496,7 @@ describe('ol.format.EsriJSON', function() { }); it('parses XYZ multilinestring', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ hasZ: true, paths: [[ [102.0, 0.0, 1], [103.0, 1.0, 1], [104.0, 0.0, 1], [105.0, 1.0, 1] @@ -504,7 +504,7 @@ describe('ol.format.EsriJSON', function() { [105.0, 3.0, 1], [106.0, 4.0, 1], [107.0, 3.0, 1], [108.0, 4.0, 1] ]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiLineString); expect(obj.getCoordinates()).to.eql([ [[102.0, 0.0, 1], [103.0, 1.0, 1], [104.0, 0.0, 1], [105.0, 1.0, 1]], @@ -514,7 +514,7 @@ describe('ol.format.EsriJSON', function() { }); it('parses XYM multilinestring', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ hasM: true, paths: [[ [102.0, 0.0, 1], [103.0, 1.0, 1], [104.0, 0.0, 1], [105.0, 1.0, 1] @@ -522,7 +522,7 @@ describe('ol.format.EsriJSON', function() { [105.0, 3.0, 1], [106.0, 4.0, 1], [107.0, 3.0, 1], [108.0, 4.0, 1] ]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiLineString); expect(obj.getCoordinates()).to.eql([ [[102.0, 0.0, 1], [103.0, 1.0, 1], [104.0, 0.0, 1], [105.0, 1.0, 1]], @@ -532,7 +532,7 @@ describe('ol.format.EsriJSON', function() { }); it('parses XYZM multilinestring', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ hasM: true, hasZ: true, paths: [[ @@ -541,7 +541,7 @@ describe('ol.format.EsriJSON', function() { [105, 3, 1, 2], [106, 4, 1, 2], [107, 3, 1, 2], [108, 4, 1, 2] ]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiLineString); expect(obj.getCoordinates()).to.eql([ [[102, 0, 1, 2], [103, 1, 1, 2], [104, 0, 1, 2], [105, 1, 1, 2]], @@ -551,16 +551,16 @@ describe('ol.format.EsriJSON', function() { }); it('parses polygon', function() { - var outer = [[0, 0], [0, 10], [10, 10], [10, 0], [0, 0]]; - var inner1 = [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]]; - var inner2 = [[8, 8], [9, 8], [9, 9], [8, 9], [8, 8]]; - var str = JSON.stringify({ + const outer = [[0, 0], [0, 10], [10, 10], [10, 0], [0, 0]]; + const inner1 = [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]]; + const inner2 = [[8, 8], [9, 8], [9, 9], [8, 9], [8, 8]]; + const str = JSON.stringify({ rings: [outer, inner1, inner2] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(Polygon); expect(obj.getLayout()).to.eql('XY'); - var rings = obj.getLinearRings(); + const rings = obj.getLinearRings(); expect(rings.length).to.be(3); expect(rings[0].getCoordinates()[0].length).to.equal(2); expect(rings[0]).to.be.a(LinearRing); @@ -569,17 +569,17 @@ describe('ol.format.EsriJSON', function() { }); it('parses XYZ polygon', function() { - var outer = [[0, 0, 5], [0, 10, 5], [10, 10, 5], [10, 0, 5], [0, 0, 5]]; - var inner1 = [[1, 1, 3], [2, 1, 3], [2, 2, 3], [1, 2, 3], [1, 1, 3]]; - var inner2 = [[8, 8, 2], [9, 8, 2], [9, 9, 2], [8, 9, 2], [8, 8, 2]]; - var str = JSON.stringify({ + const outer = [[0, 0, 5], [0, 10, 5], [10, 10, 5], [10, 0, 5], [0, 0, 5]]; + const inner1 = [[1, 1, 3], [2, 1, 3], [2, 2, 3], [1, 2, 3], [1, 1, 3]]; + const inner2 = [[8, 8, 2], [9, 8, 2], [9, 9, 2], [8, 9, 2], [8, 8, 2]]; + const str = JSON.stringify({ rings: [outer, inner1, inner2], hasZ: true }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(Polygon); expect(obj.getLayout()).to.eql('XYZ'); - var rings = obj.getLinearRings(); + const rings = obj.getLinearRings(); expect(rings.length).to.be(3); expect(rings[0].getCoordinates()[0].length).to.equal(3); expect(rings[0]).to.be.a(LinearRing); @@ -588,17 +588,17 @@ describe('ol.format.EsriJSON', function() { }); it('parses XYM polygon', function() { - var outer = [[0, 0, 5], [0, 10, 5], [10, 10, 5], [10, 0, 5], [0, 0, 5]]; - var inner1 = [[1, 1, 3], [2, 1, 3], [2, 2, 3], [1, 2, 3], [1, 1, 3]]; - var inner2 = [[8, 8, 2], [9, 8, 2], [9, 9, 2], [8, 9, 2], [8, 8, 2]]; - var str = JSON.stringify({ + const outer = [[0, 0, 5], [0, 10, 5], [10, 10, 5], [10, 0, 5], [0, 0, 5]]; + const inner1 = [[1, 1, 3], [2, 1, 3], [2, 2, 3], [1, 2, 3], [1, 1, 3]]; + const inner2 = [[8, 8, 2], [9, 8, 2], [9, 9, 2], [8, 9, 2], [8, 8, 2]]; + const str = JSON.stringify({ rings: [outer, inner1, inner2], hasM: true }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(Polygon); expect(obj.getLayout()).to.eql('XYM'); - var rings = obj.getLinearRings(); + const rings = obj.getLinearRings(); expect(rings.length).to.be(3); expect(rings[0].getCoordinates()[0].length).to.equal(3); expect(rings[0]).to.be.a(LinearRing); @@ -607,27 +607,27 @@ describe('ol.format.EsriJSON', function() { }); it('parses XYZM polygon', function() { - var outer = [ + const outer = [ [0, 0, 5, 1], [0, 10, 5, 1], [10, 10, 5, 1], [10, 0, 5, 1], [0, 0, 5, 1] ]; - var inner1 = [ + const inner1 = [ [1, 1, 3, 2], [2, 1, 3, 2], [2, 2, 3, 2], [1, 2, 3, 2], [1, 1, 3, 2] ]; - var inner2 = [ + const inner2 = [ [8, 8, 2, 1], [9, 8, 2, 1], [9, 9, 2, 1], [8, 9, 2, 1], [8, 8, 2, 1] ]; - var str = JSON.stringify({ + const str = JSON.stringify({ rings: [outer, inner1, inner2], hasZ: true, hasM: true }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(Polygon); expect(obj.getLayout()).to.eql('XYZM'); - var rings = obj.getLinearRings(); + const rings = obj.getLinearRings(); expect(rings.length).to.be(3); expect(rings[0].getCoordinates()[0].length).to.equal(4); expect(rings[0]).to.be.a(LinearRing); @@ -636,14 +636,14 @@ describe('ol.format.EsriJSON', function() { }); it('parses XY multipolygon', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ rings: [ [[0, 1], [1, 4], [4, 3], [3, 0]], [[2, 2], [3, 2], [3, 3], [2, 3]], [[10, 1], [11, 5], [14, 3], [13, 0]] ] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiPolygon); expect(obj.getLayout()).to.eql('XY'); expect(obj.getCoordinates()).to.eql([ @@ -654,7 +654,7 @@ describe('ol.format.EsriJSON', function() { }); it('parses XYZ multipolygon', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ rings: [ [[0, 1, 0], [1, 4, 0], [4, 3, 0], [3, 0, 0]], [[2, 2, 0], [3, 2, 0], [3, 3, 0], [2, 3, 0]], @@ -662,7 +662,7 @@ describe('ol.format.EsriJSON', function() { ], hasZ: true }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiPolygon); expect(obj.getLayout()).to.eql('XYZ'); expect(obj.getCoordinates()).to.eql([ @@ -673,7 +673,7 @@ describe('ol.format.EsriJSON', function() { }); it('parses XYM multipolygon', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ rings: [ [[0, 1, 0], [1, 4, 0], [4, 3, 0], [3, 0, 0]], [[2, 2, 0], [3, 2, 0], [3, 3, 0], [2, 3, 0]], @@ -681,7 +681,7 @@ describe('ol.format.EsriJSON', function() { ], hasM: true }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiPolygon); expect(obj.getLayout()).to.eql('XYM'); expect(obj.getCoordinates()).to.eql([ @@ -692,7 +692,7 @@ describe('ol.format.EsriJSON', function() { }); it('parses XYZM multipolygon', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ rings: [ [[0, 1, 0, 1], [1, 4, 0, 1], [4, 3, 0, 1], [3, 0, 0, 1]], [[2, 2, 0, 1], [3, 2, 0, 1], [3, 3, 0, 1], [2, 3, 0, 1]], @@ -701,7 +701,7 @@ describe('ol.format.EsriJSON', function() { hasZ: true, hasM: true }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(MultiPolygon); expect(obj.getLayout()).to.eql('XYZM'); expect(obj.getCoordinates()).to.eql([ @@ -718,7 +718,7 @@ describe('ol.format.EsriJSON', function() { it('reads named crs from top-level object', function() { - var json = { + const json = { spatialReference: { wkid: 3857 }, @@ -739,16 +739,16 @@ describe('ol.format.EsriJSON', function() { } }] }; - var features = format.readFeatures(json); + const features = format.readFeatures(json); expect(features.length).to.be(2); - var first = features[0]; + const first = features[0]; expect(first).to.be.a(Feature); expect(first.get('foo')).to.be('bar'); expect(first.getGeometry()).to.be.a(Point); - var second = features[1]; + const second = features[1]; expect(second).to.be.a(Feature); expect(second.get('bam')).to.be('baz'); expect(second.getGeometry()).to.be.a(LineString); @@ -762,247 +762,247 @@ describe('ol.format.EsriJSON', function() { describe('#writeGeometry', function() { it('encodes point', function() { - var point = new Point([10, 20]); - var esrijson = format.writeGeometry(point); + const point = new Point([10, 20]); + const esrijson = format.writeGeometry(point); expect(point.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZ point', function() { - var point = new Point([10, 20, 0], 'XYZ'); - var esrijson = format.writeGeometry(point); + const point = new Point([10, 20, 0], 'XYZ'); + const esrijson = format.writeGeometry(point); expect(point.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYM point', function() { - var point = new Point([10, 20, 0], 'XYM'); - var esrijson = format.writeGeometry(point); + const point = new Point([10, 20, 0], 'XYM'); + const esrijson = format.writeGeometry(point); expect(point.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZM point', function() { - var point = new Point([10, 20, 5, 0], - 'XYZM'); - var esrijson = format.writeGeometry(point); + const point = new Point([10, 20, 5, 0], + 'XYZM'); + const esrijson = format.writeGeometry(point); expect(point.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes linestring', function() { - var linestring = new LineString([[10, 20], [30, 40]]); - var esrijson = format.writeGeometry(linestring); + const linestring = new LineString([[10, 20], [30, 40]]); + const esrijson = format.writeGeometry(linestring); expect(linestring.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZ linestring', function() { - var linestring = new LineString([[10, 20, 1534], [30, 40, 1420]], - 'XYZ'); - var esrijson = format.writeGeometry(linestring); + const linestring = new LineString([[10, 20, 1534], [30, 40, 1420]], + 'XYZ'); + const esrijson = format.writeGeometry(linestring); expect(linestring.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYM linestring', function() { - var linestring = new LineString([[10, 20, 1534], [30, 40, 1420]], - 'XYM'); - var esrijson = format.writeGeometry(linestring); + const linestring = new LineString([[10, 20, 1534], [30, 40, 1420]], + 'XYM'); + const esrijson = format.writeGeometry(linestring); expect(linestring.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZM linestring', function() { - var linestring = new LineString([[10, 20, 1534, 1], + const linestring = new LineString([[10, 20, 1534, 1], [30, 40, 1420, 1]], 'XYZM'); - var esrijson = format.writeGeometry(linestring); + const esrijson = format.writeGeometry(linestring); expect(linestring.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes polygon', function() { - var outer = [[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]; - var inner1 = [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]]; - var inner2 = [[8, 8], [9, 8], [9, 9], [8, 9], [8, 8]]; - var polygon = new Polygon([outer, inner1, inner2]); - var esrijson = format.writeGeometry(polygon); + const outer = [[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]; + const inner1 = [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]]; + const inner2 = [[8, 8], [9, 8], [9, 9], [8, 9], [8, 8]]; + const polygon = new Polygon([outer, inner1, inner2]); + const esrijson = format.writeGeometry(polygon); expect(polygon.getCoordinates(false)).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZ polygon', function() { - var outer = [[0, 0, 5], [0, 10, 5], [10, 10, 5], [10, 0, 5], [0, 0, 5]]; - var inner1 = [[1, 1, 3], [2, 1, 3], [2, 2, 3], [1, 2, 3], [1, 1, 3]]; - var inner2 = [[8, 8, 2], [9, 8, 2], [9, 9, 2], [8, 9, 2], [8, 8, 2]]; - var polygon = new Polygon([outer, inner1, inner2], - 'XYZ'); - var esrijson = format.writeGeometry(polygon); + const outer = [[0, 0, 5], [0, 10, 5], [10, 10, 5], [10, 0, 5], [0, 0, 5]]; + const inner1 = [[1, 1, 3], [2, 1, 3], [2, 2, 3], [1, 2, 3], [1, 1, 3]]; + const inner2 = [[8, 8, 2], [9, 8, 2], [9, 9, 2], [8, 9, 2], [8, 8, 2]]; + const polygon = new Polygon([outer, inner1, inner2], + 'XYZ'); + const esrijson = format.writeGeometry(polygon); expect(polygon.getCoordinates(false)).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYM polygon', function() { - var outer = [[0, 0, 5], [0, 10, 5], [10, 10, 5], [10, 0, 5], [0, 0, 5]]; - var inner1 = [[1, 1, 3], [2, 1, 3], [2, 2, 3], [1, 2, 3], [1, 1, 3]]; - var inner2 = [[8, 8, 2], [9, 8, 2], [9, 9, 2], [8, 9, 2], [8, 8, 2]]; - var polygon = new Polygon([outer, inner1, inner2], - 'XYM'); - var esrijson = format.writeGeometry(polygon); + const outer = [[0, 0, 5], [0, 10, 5], [10, 10, 5], [10, 0, 5], [0, 0, 5]]; + const inner1 = [[1, 1, 3], [2, 1, 3], [2, 2, 3], [1, 2, 3], [1, 1, 3]]; + const inner2 = [[8, 8, 2], [9, 8, 2], [9, 9, 2], [8, 9, 2], [8, 8, 2]]; + const polygon = new Polygon([outer, inner1, inner2], + 'XYM'); + const esrijson = format.writeGeometry(polygon); expect(polygon.getCoordinates(false)).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZM polygon', function() { - var outer = [ + const outer = [ [0, 0, 5, 1], [0, 10, 5, 2], [10, 10, 5, 1], [10, 0, 5, 1], [0, 0, 5, 1] ]; - var inner1 = [ + const inner1 = [ [1, 1, 3, 1], [2, 1, 3, 2], [2, 2, 3, 1], [1, 2, 3, 1], [1, 1, 3, 1] ]; - var inner2 = [ + const inner2 = [ [8, 8, 2, 1], [9, 8, 2, 2], [9, 9, 2, 1], [8, 9, 2, 1], [8, 8, 2, 1] ]; - var polygon = new Polygon([outer, inner1, inner2], - 'XYZM'); - var esrijson = format.writeGeometry(polygon); + const polygon = new Polygon([outer, inner1, inner2], + 'XYZM'); + const esrijson = format.writeGeometry(polygon); expect(polygon.getCoordinates(false)).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes multipoint', function() { - var multipoint = new MultiPoint([[102.0, 0.0], [103.0, 1.0]]); - var esrijson = format.writeGeometry(multipoint); + const multipoint = new MultiPoint([[102.0, 0.0], [103.0, 1.0]]); + const esrijson = format.writeGeometry(multipoint); expect(multipoint.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZ multipoint', function() { - var multipoint = new MultiPoint([[102.0, 0.0, 3], + const multipoint = new MultiPoint([[102.0, 0.0, 3], [103.0, 1.0, 4]], 'XYZ'); - var esrijson = format.writeGeometry(multipoint); + const esrijson = format.writeGeometry(multipoint); expect(multipoint.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYM multipoint', function() { - var multipoint = new MultiPoint([[102.0, 0.0, 3], + const multipoint = new MultiPoint([[102.0, 0.0, 3], [103.0, 1.0, 4]], 'XYM'); - var esrijson = format.writeGeometry(multipoint); + const esrijson = format.writeGeometry(multipoint); expect(multipoint.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZM multipoint', function() { - var multipoint = new MultiPoint([[102.0, 0.0, 3, 1], + const multipoint = new MultiPoint([[102.0, 0.0, 3, 1], [103.0, 1.0, 4, 1]], 'XYZM'); - var esrijson = format.writeGeometry(multipoint); + const esrijson = format.writeGeometry(multipoint); expect(multipoint.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes multilinestring', function() { - var multilinestring = new MultiLineString([ + const multilinestring = new MultiLineString([ [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]], [[105.0, 3.0], [106.0, 4.0], [107.0, 3.0], [108.0, 4.0]] ]); - var esrijson = format.writeGeometry(multilinestring); + const esrijson = format.writeGeometry(multilinestring); expect(multilinestring.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZ multilinestring', function() { - var multilinestring = new MultiLineString([ + const multilinestring = new MultiLineString([ [[102.0, 0.0, 1], [103.0, 1.0, 2], [104.0, 0.0, 3], [105.0, 1.0, 4]], [[105.0, 3.0, 1], [106.0, 4.0, 2], [107.0, 3.0, 3], [108.0, 4.0, 4]] ], 'XYZ'); - var esrijson = format.writeGeometry(multilinestring); + const esrijson = format.writeGeometry(multilinestring); expect(multilinestring.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYM multilinestring', function() { - var multilinestring = new MultiLineString([ + const multilinestring = new MultiLineString([ [[102.0, 0.0, 1], [103.0, 1.0, 2], [104.0, 0.0, 3], [105.0, 1.0, 4]], [[105.0, 3.0, 1], [106.0, 4.0, 2], [107.0, 3.0, 3], [108.0, 4.0, 4]] ], 'XYM'); - var esrijson = format.writeGeometry(multilinestring); + const esrijson = format.writeGeometry(multilinestring); expect(multilinestring.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZM multilinestring', function() { - var multilinestring = new MultiLineString([ + const multilinestring = new MultiLineString([ [[102.0, 0.0, 1, 0], [103.0, 1.0, 2, 2], [104.0, 0.0, 3, 1], [105.0, 1.0, 4, 2]], [[105.0, 3.0, 1, 0], [106.0, 4.0, 2, 1], [107.0, 3.0, 3, 1], [108.0, 4.0, 4, 2]] ], 'XYZM'); - var esrijson = format.writeGeometry(multilinestring); + const esrijson = format.writeGeometry(multilinestring); expect(multilinestring.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes multipolygon', function() { - var multipolygon = new MultiPolygon([ + const multipolygon = new MultiPolygon([ [[[0, 1], [1, 4], [4, 3], [3, 0]], [[2, 2], [3, 2], [3, 3], [2, 3]]], [[[10, 1], [11, 5], [14, 3], [13, 0]]] ]); - var esrijson = format.writeGeometry(multipolygon); + const esrijson = format.writeGeometry(multipolygon); expect(multipolygon.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZ multipolygon', function() { - var multipolygon = new MultiPolygon([ + const multipolygon = new MultiPolygon([ [[[0, 1, 0], [1, 4, 0], [4, 3, 0], [3, 0, 0]], [[2, 2, 0], [3, 2, 0], [3, 3, 0], [2, 3, 0]]], [[[10, 1, 0], [11, 5, 0], [14, 3, 0], [13, 0, 0]]] ], 'XYZ'); - var esrijson = format.writeGeometry(multipolygon); + const esrijson = format.writeGeometry(multipolygon); expect(multipolygon.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYM multipolygon', function() { - var multipolygon = new MultiPolygon([ + const multipolygon = new MultiPolygon([ [[[0, 1, 0], [1, 4, 0], [4, 3, 0], [3, 0, 0]], [[2, 2, 0], [3, 2, 0], [3, 3, 0], [2, 3, 0]]], [[[10, 1, 0], [11, 5, 0], [14, 3, 0], [13, 0, 0]]] ], 'XYM'); - var esrijson = format.writeGeometry(multipolygon); + const esrijson = format.writeGeometry(multipolygon); expect(multipolygon.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('encodes XYZM multipolygon', function() { - var multipolygon = new MultiPolygon([ + const multipolygon = new MultiPolygon([ [[[0, 1, 0, 1], [1, 4, 0, 1], [4, 3, 0, 3], [3, 0, 0, 3]], [[2, 2, 0, 3], [3, 2, 0, 4], [3, 3, 0, 1], [2, 3, 0, 1]]], [[[10, 1, 0, 1], [11, 5, 0, 2], [14, 3, 0, 3], [13, 0, 0, 3]]] ], 'XYZM'); - var esrijson = format.writeGeometry(multipolygon); + const esrijson = format.writeGeometry(multipolygon); expect(multipolygon.getCoordinates()).to.eql( - format.readGeometry(esrijson).getCoordinates()); + format.readGeometry(esrijson).getCoordinates()); }); it('transforms and encodes a point', function() { - var point = new Point([2, 3]); - var esrijson = format.writeGeometry(point, { + const point = new Point([2, 3]); + const esrijson = format.writeGeometry(point, { dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' }); - var newPoint = format.readGeometry(esrijson, { + const newPoint = format.readGeometry(esrijson, { dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' }); expect(point.getCoordinates()[0]).to.roughlyEqual( - newPoint.getCoordinates()[0], 1e-8); + newPoint.getCoordinates()[0], 1e-8); expect( - Math.abs(point.getCoordinates()[1] - newPoint.getCoordinates()[1])) - .to.be.lessThan(0.0000001); + Math.abs(point.getCoordinates()[1] - newPoint.getCoordinates()[1])) + .to.be.lessThan(0.0000001); }); }); @@ -1010,17 +1010,17 @@ describe('ol.format.EsriJSON', function() { describe('#writeFeatures', function() { it('encodes feature collection', function() { - var str = JSON.stringify(data); - var array = format.readFeatures(str); - var esrijson = format.writeFeaturesObject(array); - var result = format.readFeatures(esrijson); + const str = JSON.stringify(data); + const array = format.readFeatures(str); + const esrijson = format.writeFeaturesObject(array); + const result = format.readFeatures(esrijson); expect(array.length).to.equal(result.length); - var got, exp, gotProp, expProp; - for (var i = 0, ii = array.length; i < ii; ++i) { + let got, exp, gotProp, expProp; + for (let i = 0, ii = array.length; i < ii; ++i) { got = array[i]; exp = result[i]; expect(got.getGeometry().getCoordinates()).to.eql( - exp.getGeometry().getCoordinates()); + exp.getGeometry().getCoordinates()); gotProp = got.getProperties(); delete gotProp.geometry; expProp = exp.getProperties(); @@ -1030,45 +1030,45 @@ describe('ol.format.EsriJSON', function() { }); it('transforms and encodes feature collection', function() { - var str = JSON.stringify(data); - var array = format.readFeatures(str); - var esrijson = format.writeFeatures(array, { + const str = JSON.stringify(data); + const array = format.readFeatures(str); + const esrijson = format.writeFeatures(array, { featureProjection: 'EPSG:3857', dataProjection: 'EPSG:4326' }); - var result = format.readFeatures(esrijson); - var got, exp; - for (var i = 0, ii = array.length; i < ii; ++i) { + const result = format.readFeatures(esrijson); + let got, exp; + for (let i = 0, ii = array.length; i < ii; ++i) { got = array[i]; exp = result[i]; expect(got.getGeometry().transform('EPSG:3857', 'EPSG:4326') - .getCoordinates()).to.eql(exp.getGeometry().getCoordinates()); + .getCoordinates()).to.eql(exp.getGeometry().getCoordinates()); } }); it('writes out a feature with a different geometryName correctly', - function() { - var feature = new Feature({'foo': 'bar'}); - feature.setGeometryName('mygeom'); - feature.setGeometry(new Point([5, 10])); - var esrijson = format.writeFeaturesObject([feature]); - expect(esrijson.features[0].attributes.mygeom).to.eql(undefined); - }); + function() { + const feature = new Feature({'foo': 'bar'}); + feature.setGeometryName('mygeom'); + feature.setGeometry(new Point([5, 10])); + const esrijson = format.writeFeaturesObject([feature]); + expect(esrijson.features[0].attributes.mygeom).to.eql(undefined); + }); it('writes out a feature without properties correctly', function() { - var feature = new Feature(new Point([5, 10])); - var esrijson = format.writeFeatureObject(feature); + const feature = new Feature(new Point([5, 10])); + const esrijson = format.writeFeatureObject(feature); expect(esrijson.attributes).to.eql({}); }); it('adds the projection inside the geometry correctly', function() { - var str = JSON.stringify(data); - var array = format.readFeatures(str); - var esrijson = format.writeFeaturesObject(array, { + const str = JSON.stringify(data); + const array = format.readFeatures(str); + const esrijson = format.writeFeaturesObject(array, { featureProjection: 'EPSG:4326' }); esrijson.features.forEach(function(feature) { - var spatialReference = feature.geometry.spatialReference; + const spatialReference = feature.geometry.spatialReference; expect(Number(spatialReference.wkid)).to.equal(4326); }); }); diff --git a/test/spec/ol/format/geojson.test.js b/test/spec/ol/format/geojson.test.js index 0ccaabe3fa..07b48e7546 100644 --- a/test/spec/ol/format/geojson.test.js +++ b/test/spec/ol/format/geojson.test.js @@ -13,12 +13,12 @@ import {fromLonLat, get as getProjection, toLonLat, transform} from '../../../.. describe('ol.format.GeoJSON', function() { - var format; + let format; beforeEach(function() { format = new GeoJSON(); }); - var pointGeoJSON = { + const pointGeoJSON = { 'type': 'Feature', 'geometry': { 'type': 'Point', @@ -29,7 +29,7 @@ describe('ol.format.GeoJSON', function() { } }; - var nullGeometryGeoJSON = { + const nullGeometryGeoJSON = { 'type': 'Feature', 'geometry': null, 'properties': { @@ -37,7 +37,7 @@ describe('ol.format.GeoJSON', function() { } }; - var zeroIdGeoJSON = { + const zeroIdGeoJSON = { 'type': 'Feature', 'id': 0, 'geometry': null, @@ -46,7 +46,7 @@ describe('ol.format.GeoJSON', function() { } }; - var lineStringGeoJSON = { + const lineStringGeoJSON = { 'type': 'Feature', 'geometry': { 'type': 'LineString', @@ -60,7 +60,7 @@ describe('ol.format.GeoJSON', function() { } }; - var polygonGeoJSON = { + const polygonGeoJSON = { 'type': 'Feature', 'geometry': { 'type': 'Polygon', @@ -74,12 +74,12 @@ describe('ol.format.GeoJSON', function() { } }; - var featureCollectionGeoJSON = { + const featureCollectionGeoJSON = { 'type': 'FeatureCollection', 'features': [pointGeoJSON, lineStringGeoJSON, polygonGeoJSON] }; - var data = { + const data = { 'type': 'FeatureCollection', 'features': [{ 'type': 'Feature', @@ -144,37 +144,37 @@ describe('ol.format.GeoJSON', function() { describe('#readFeature', function() { it('can read a single point feature', function() { - var feature = format.readFeature(pointGeoJSON); + const feature = format.readFeature(pointGeoJSON); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.an(Point); expect(geometry.getCoordinates()).to.eql([102.0, 0.5]); expect(feature.get('prop0')).to.be('value0'); }); it('can read a single point geometry as a feature', function() { - var feature = format.readFeature(pointGeoJSON.geometry); + const feature = format.readFeature(pointGeoJSON.geometry); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.an(Point); expect(geometry.getCoordinates()).to.eql([102.0, 0.5]); }); it('can read a single line string feature', function() { - var feature = format.readFeature(lineStringGeoJSON); + const feature = format.readFeature(lineStringGeoJSON); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.an(LineString); expect(geometry.getCoordinates()).to.eql( - [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]]); + [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]]); expect(feature.get('prop0')).to.be('value0'); expect(feature.get('prop1')).to.be(0.0); }); it('can read a single polygon feature', function() { - var feature = format.readFeature(polygonGeoJSON); + const feature = format.readFeature(polygonGeoJSON); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.be.an(Polygon); expect(geometry.getCoordinates()).to.eql([[ [100.0, 0.0], [100.0, 1.0], [101.0, 1.0], [101.0, 0.0] @@ -184,21 +184,21 @@ describe('ol.format.GeoJSON', function() { }); it('can read a feature with null geometry', function() { - var feature = format.readFeature(nullGeometryGeoJSON); + const feature = format.readFeature(nullGeometryGeoJSON); expect(feature).to.be.an(Feature); - var geometry = feature.getGeometry(); + const geometry = feature.getGeometry(); expect(geometry).to.eql(null); expect(feature.get('prop0')).to.be('value0'); }); it('can read a feature with id equal to 0', function() { - var feature = format.readFeature(zeroIdGeoJSON); + const feature = format.readFeature(zeroIdGeoJSON); expect(feature).to.be.an(Feature); expect(feature.getId()).to.be(0); }); it('can read a feature collection', function() { - var features = format.readFeatures(featureCollectionGeoJSON); + const features = format.readFeatures(featureCollectionGeoJSON); expect(features).to.have.length(3); expect(features[0].getGeometry()).to.be.an(Point); expect(features[1].getGeometry()).to.be.an(LineString); @@ -206,39 +206,39 @@ describe('ol.format.GeoJSON', function() { }); it('can read and transform a point', function() { - var feature = format.readFeatures(pointGeoJSON, { + const feature = format.readFeatures(pointGeoJSON, { featureProjection: 'EPSG:3857' }); expect(feature[0].getGeometry()).to.be.an(Point); expect(feature[0].getGeometry().getCoordinates()).to.eql( - transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); + transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); }); it('uses featureProjection passed to the constructor', function() { - var format = new GeoJSON({featureProjection: 'EPSG:3857'}); - var feature = format.readFeatures(pointGeoJSON); + const format = new GeoJSON({featureProjection: 'EPSG:3857'}); + const feature = format.readFeatures(pointGeoJSON); expect(feature[0].getGeometry()).to.be.an(Point); expect(feature[0].getGeometry().getCoordinates()).to.eql( - transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); + transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); }); it('gives precedence to options passed to the read method', function() { - var format = new GeoJSON({featureProjection: 'EPSG:1234'}); - var feature = format.readFeatures(pointGeoJSON, { + const format = new GeoJSON({featureProjection: 'EPSG:1234'}); + const feature = format.readFeatures(pointGeoJSON, { featureProjection: 'EPSG:3857' }); expect(feature[0].getGeometry()).to.be.an(Point); expect(feature[0].getGeometry().getCoordinates()).to.eql( - transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); + transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); }); it('can read and transform a feature collection', function() { - var features = format.readFeatures(featureCollectionGeoJSON, { + const features = format.readFeatures(featureCollectionGeoJSON, { featureProjection: 'EPSG:3857' }); expect(features[0].getGeometry()).to.be.an(Point); expect(features[0].getGeometry().getCoordinates()).to.eql( - transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); + transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857')); expect(features[1].getGeometry().getCoordinates()).to.eql([ transform([102.0, 0.0], 'EPSG:4326', 'EPSG:3857'), transform([103.0, 1.0], 'EPSG:4326', 'EPSG:3857'), @@ -254,8 +254,8 @@ describe('ol.format.GeoJSON', function() { }); it('can create a feature with a specific geometryName', function() { - var feature = new GeoJSON({geometryName: 'the_geom'}). - readFeature(pointGeoJSON); + const feature = new GeoJSON({geometryName: 'the_geom'}). + readFeature(pointGeoJSON); expect(feature.getGeometryName()).to.be('the_geom'); expect(feature.getGeometry()).to.be.an(Point); }); @@ -265,56 +265,56 @@ describe('ol.format.GeoJSON', function() { describe('#readFeatures', function() { it('parses feature collection', function() { - var str = JSON.stringify(data); - var array = format.readFeatures(str); + const str = JSON.stringify(data); + const array = format.readFeatures(str); expect(array.length).to.be(2); - var first = array[0]; + const first = array[0]; expect(first).to.be.a(Feature); expect(first.get('LINK_ID')).to.be(573730499); - var firstGeom = first.getGeometry(); + const firstGeom = first.getGeometry(); expect(firstGeom).to.be.a(LineString); - var second = array[1]; + const second = array[1]; expect(second).to.be.a(Feature); expect(second.get('ST_NAME')).to.be('BRUNNSGATAN'); - var secondGeom = second.getGeometry(); + const secondGeom = second.getGeometry(); expect(secondGeom).to.be.a(LineString); }); it('can parse a polygon geometry as an array of one feature', function() { - var features = format.readFeatures(polygonGeoJSON); + const features = format.readFeatures(polygonGeoJSON); expect(features).to.be.an(Array); expect(features).to.have.length(1); - var geometry = features[0].getGeometry(); + const geometry = features[0].getGeometry(); expect(geometry).to.be.an(Polygon); }); it('parses countries.geojson', function(done) { afterLoadText('spec/ol/format/geojson/countries.geojson', function(text) { - var result = format.readFeatures(text); + const result = format.readFeatures(text); expect(result.length).to.be(179); - var first = result[0]; + const first = result[0]; expect(first).to.be.a(Feature); expect(first.get('name')).to.be('Afghanistan'); expect(first.getId()).to.be('AFG'); - var firstGeom = first.getGeometry(); + const firstGeom = first.getGeometry(); expect(firstGeom).to.be.a(Polygon); expect(_ol_extent_.equals(firstGeom.getExtent(), - [60.52843, 29.318572, 75.158028, 38.486282])) - .to.be(true); + [60.52843, 29.318572, 75.158028, 38.486282])) + .to.be(true); - var last = result[178]; + const last = result[178]; expect(last).to.be.a(Feature); expect(last.get('name')).to.be('Zimbabwe'); expect(last.getId()).to.be('ZWE'); - var lastGeom = last.getGeometry(); + const lastGeom = last.getGeometry(); expect(lastGeom).to.be.a(Polygon); expect(_ol_extent_.equals(lastGeom.getExtent(), - [25.264226, -22.271612, 32.849861, -15.507787])) - .to.be(true); + [25.264226, -22.271612, 32.849861, -15.507787])) + .to.be(true); done(); }); @@ -322,8 +322,8 @@ describe('ol.format.GeoJSON', function() { it('generates an array of features for Feature', function() { - var format = new GeoJSON(); - var json = { + const format = new GeoJSON(); + const json = { type: 'Feature', properties: { bam: 'baz' @@ -333,11 +333,11 @@ describe('ol.format.GeoJSON', function() { coordinates: [[1, 2], [3, 4]] } }; - var features = format.readFeatures(json); + const features = format.readFeatures(json); expect(features.length).to.be(1); - var first = features[0]; + const first = features[0]; expect(first).to.be.a(Feature); expect(first.get('bam')).to.be('baz'); expect(first.getGeometry()).to.be.a(LineString); @@ -350,54 +350,54 @@ describe('ol.format.GeoJSON', function() { describe('#readGeometry', function() { it('parses point', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ type: 'Point', coordinates: [10, 20] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(Point); expect(obj.getCoordinates()).to.eql([10, 20]); expect(obj.getLayout()).to.eql('XY'); }); it('parses linestring', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ type: 'LineString', coordinates: [[10, 20], [30, 40]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(LineString); expect(obj.getCoordinates()).to.eql([[10, 20], [30, 40]]); expect(obj.getLayout()).to.eql('XY'); }); it('parses XYZ linestring', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ type: 'LineString', coordinates: [[10, 20, 1534], [30, 40, 1420]] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(LineString); expect(obj.getLayout()).to.eql('XYZ'); expect(obj.getCoordinates()).to.eql([[10, 20, 1534], [30, 40, 1420]]); }); it('parses polygon', function() { - var outer = [[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]; - var inner1 = [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]]; - var inner2 = [[8, 8], [9, 8], [9, 9], [8, 9], [8, 8]]; - var str = JSON.stringify({ + const outer = [[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]; + const inner1 = [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]]; + const inner2 = [[8, 8], [9, 8], [9, 9], [8, 9], [8, 8]]; + const str = JSON.stringify({ type: 'Polygon', coordinates: [outer, inner1, inner2] }); - var obj = format.readGeometry(str); + const obj = format.readGeometry(str); expect(obj).to.be.a(Polygon); expect(obj.getLayout()).to.eql('XY'); - var rings = obj.getLinearRings(); + const rings = obj.getLinearRings(); expect(rings.length).to.be(3); expect(rings[0]).to.be.a(LinearRing); expect(rings[1]).to.be.a(LinearRing); @@ -405,7 +405,7 @@ describe('ol.format.GeoJSON', function() { }); it('parses geometry collection', function() { - var str = JSON.stringify({ + const str = JSON.stringify({ type: 'GeometryCollection', geometries: [ {type: 'Point', coordinates: [10, 20]}, @@ -413,9 +413,9 @@ describe('ol.format.GeoJSON', function() { ] }); - var geometryCollection = format.readGeometry(str); + const geometryCollection = format.readGeometry(str); expect(geometryCollection).to.be.an(GeometryCollection); - var array = geometryCollection.getGeometries(); + const array = geometryCollection.getGeometries(); expect(array.length).to.be(2); expect(array[0]).to.be.a(Point); expect(array[0].getLayout()).to.eql('XY'); @@ -429,7 +429,7 @@ describe('ol.format.GeoJSON', function() { it('reads named crs from top-level object', function() { - var json = { + const json = { type: 'FeatureCollection', crs: { type: 'name', @@ -457,16 +457,16 @@ describe('ol.format.GeoJSON', function() { } }] }; - var features = format.readFeatures(json); + const features = format.readFeatures(json); expect(features.length).to.be(2); - var first = features[0]; + const first = features[0]; expect(first).to.be.a(Feature); expect(first.get('foo')).to.be('bar'); expect(first.getGeometry()).to.be.a(Point); - var second = features[1]; + const second = features[1]; expect(second).to.be.a(Feature); expect(second.get('bam')).to.be('baz'); expect(second.getGeometry()).to.be.a(LineString); @@ -477,7 +477,7 @@ describe('ol.format.GeoJSON', function() { it('accepts null crs', function() { - var json = { + const json = { type: 'FeatureCollection', crs: null, features: [{ @@ -500,16 +500,16 @@ describe('ol.format.GeoJSON', function() { } }] }; - var features = format.readFeatures(json); + const features = format.readFeatures(json); expect(features.length).to.be(2); - var first = features[0]; + const first = features[0]; expect(first).to.be.a(Feature); expect(first.get('foo')).to.be('bar'); expect(first.getGeometry()).to.be.a(Point); - var second = features[1]; + const second = features[1]; expect(second).to.be.a(Feature); expect(second.get('bam')).to.be('baz'); expect(second.getGeometry()).to.be.a(LineString); @@ -523,17 +523,17 @@ describe('ol.format.GeoJSON', function() { describe('#writeFeatures', function() { it('encodes feature collection', function() { - var str = JSON.stringify(data); - var array = format.readFeatures(str); - var geojson = format.writeFeaturesObject(array); - var result = format.readFeatures(geojson); + const str = JSON.stringify(data); + const array = format.readFeatures(str); + const geojson = format.writeFeaturesObject(array); + const result = format.readFeatures(geojson); expect(array.length).to.equal(result.length); - var got, exp, gotProp, expProp; - for (var i = 0, ii = array.length; i < ii; ++i) { + let got, exp, gotProp, expProp; + for (let i = 0, ii = array.length; i < ii; ++i) { got = array[i]; exp = result[i]; expect(got.getGeometry().getCoordinates()).to.eql( - exp.getGeometry().getCoordinates()); + exp.getGeometry().getCoordinates()); gotProp = got.getProperties(); delete gotProp.geometry; expProp = exp.getProperties(); @@ -543,46 +543,46 @@ describe('ol.format.GeoJSON', function() { }); it('transforms and encodes feature collection', function() { - var str = JSON.stringify(data); - var array = format.readFeatures(str); - var geojson = format.writeFeatures(array, { + const str = JSON.stringify(data); + const array = format.readFeatures(str); + const geojson = format.writeFeatures(array, { featureProjection: 'EPSG:3857' }); - var result = format.readFeatures(geojson); - var got, exp; - for (var i = 0, ii = array.length; i < ii; ++i) { + const result = format.readFeatures(geojson); + let got, exp; + for (let i = 0, ii = array.length; i < ii; ++i) { got = array[i]; exp = result[i]; expect(got.getGeometry().transform('EPSG:3857', 'EPSG:4326') - .getCoordinates()).to.eql(exp.getGeometry().getCoordinates()); + .getCoordinates()).to.eql(exp.getGeometry().getCoordinates()); } }); it('writes out a feature with a different geometryName correctly', - function() { - var feature = new Feature({'foo': 'bar'}); - feature.setGeometryName('mygeom'); - feature.setGeometry(new Point([5, 10])); - var geojson = format.writeFeaturesObject([feature]); - expect(geojson.features[0].properties.mygeom).to.eql(undefined); - }); + function() { + const feature = new Feature({'foo': 'bar'}); + feature.setGeometryName('mygeom'); + feature.setGeometry(new Point([5, 10])); + const geojson = format.writeFeaturesObject([feature]); + expect(geojson.features[0].properties.mygeom).to.eql(undefined); + }); it('writes out a feature without properties correctly', function() { - var feature = new Feature(new Point([5, 10])); - var geojson = format.writeFeatureObject(feature); + const feature = new Feature(new Point([5, 10])); + const geojson = format.writeFeatureObject(feature); expect(geojson.properties).to.eql(null); }); it('writes out a feature without geometry correctly', function() { - var feature = new Feature(); - var geojson = format.writeFeatureObject(feature); + const feature = new Feature(); + const geojson = format.writeFeatureObject(feature); expect(geojson.geometry).to.eql(null); }); it('writes out a feature with id equal to 0 correctly', function() { - var feature = new Feature(); + const feature = new Feature(); feature.setId(0); - var geojson = format.writeFeatureObject(feature); + const geojson = format.writeFeatureObject(feature); expect(geojson.id).to.eql(0); }); }); @@ -590,77 +590,77 @@ describe('ol.format.GeoJSON', function() { describe('#writeGeometry', function() { it('encodes point', function() { - var point = new Point([10, 20]); - var geojson = format.writeGeometry(point); + const point = new Point([10, 20]); + const geojson = format.writeGeometry(point); expect(point.getCoordinates()).to.eql( - format.readGeometry(geojson).getCoordinates()); + format.readGeometry(geojson).getCoordinates()); }); it('accepts featureProjection', function() { - var point = new Point(fromLonLat([10, 20])); - var geojson = format.writeGeometry(point, {featureProjection: 'EPSG:3857'}); - var obj = JSON.parse(geojson); + const point = new Point(fromLonLat([10, 20])); + const geojson = format.writeGeometry(point, {featureProjection: 'EPSG:3857'}); + const obj = JSON.parse(geojson); expect(obj.coordinates).to.eql(toLonLat(point.getCoordinates())); }); it('respects featureProjection passed to constructor', function() { - var format = new GeoJSON({featureProjection: 'EPSG:3857'}); - var point = new Point(fromLonLat([10, 20])); - var geojson = format.writeGeometry(point); - var obj = JSON.parse(geojson); + const format = new GeoJSON({featureProjection: 'EPSG:3857'}); + const point = new Point(fromLonLat([10, 20])); + const geojson = format.writeGeometry(point); + const obj = JSON.parse(geojson); expect(obj.coordinates).to.eql(toLonLat(point.getCoordinates())); }); it('encodes linestring', function() { - var linestring = new LineString([[10, 20], [30, 40]]); - var geojson = format.writeGeometry(linestring); + const linestring = new LineString([[10, 20], [30, 40]]); + const geojson = format.writeGeometry(linestring); expect(linestring.getCoordinates()).to.eql( - format.readGeometry(geojson).getCoordinates()); + format.readGeometry(geojson).getCoordinates()); }); it('encodes polygon', function() { - var outer = [[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]; - var inner1 = [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]]; - var inner2 = [[8, 8], [9, 8], [9, 9], [8, 9], [8, 8]]; - var polygon = new Polygon([outer, inner1, inner2]); - var geojson = format.writeGeometry(polygon); + const outer = [[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]; + const inner1 = [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]]; + const inner2 = [[8, 8], [9, 8], [9, 9], [8, 9], [8, 8]]; + const polygon = new Polygon([outer, inner1, inner2]); + const geojson = format.writeGeometry(polygon); expect(polygon.getCoordinates()).to.eql( - format.readGeometry(geojson).getCoordinates()); + format.readGeometry(geojson).getCoordinates()); }); it('maintains coordinate order by default', function() { - var cw = [[-180, -90], [-180, 90], [180, 90], [180, -90], [-180, -90]]; - var ccw = [[-180, -90], [180, -90], [180, 90], [-180, 90], [-180, -90]]; + const cw = [[-180, -90], [-180, 90], [180, 90], [180, -90], [-180, -90]]; + const ccw = [[-180, -90], [180, -90], [180, 90], [-180, 90], [-180, -90]]; - var right = new Polygon([ccw, cw]); - var rightMulti = new MultiPolygon([[ccw, cw]]); - var left = new Polygon([cw, ccw]); - var leftMulti = new MultiPolygon([[cw, ccw]]); + const right = new Polygon([ccw, cw]); + const rightMulti = new MultiPolygon([[ccw, cw]]); + const left = new Polygon([cw, ccw]); + const leftMulti = new MultiPolygon([[cw, ccw]]); - var rightObj = { + const rightObj = { type: 'Polygon', coordinates: [ccw, cw] }; - var rightMultiObj = { + const rightMultiObj = { type: 'MultiPolygon', coordinates: [[ccw, cw]] }; - var leftObj = { + const leftObj = { type: 'Polygon', coordinates: [cw, ccw] }; - var leftMultiObj = { + const leftMultiObj = { type: 'MultiPolygon', coordinates: [[cw, ccw]] }; expect(JSON.parse(format.writeGeometry(right))).to.eql(rightObj); expect( - JSON.parse(format.writeGeometry(rightMulti))).to.eql(rightMultiObj); + JSON.parse(format.writeGeometry(rightMulti))).to.eql(rightMultiObj); expect(JSON.parse(format.writeGeometry(left))).to.eql(leftObj); expect(JSON.parse(format.writeGeometry(leftMulti))).to.eql(leftMultiObj); @@ -668,24 +668,24 @@ describe('ol.format.GeoJSON', function() { it('allows serializing following the right-hand rule', function() { - var cw = [[-180, -90], [-180, 90], [180, 90], [180, -90], [-180, -90]]; - var ccw = [[-180, -90], [180, -90], [180, 90], [-180, 90], [-180, -90]]; - var right = new Polygon([ccw, cw]); - var rightMulti = new MultiPolygon([[ccw, cw]]); - var left = new Polygon([cw, ccw]); - var leftMulti = new MultiPolygon([[cw, ccw]]); + const cw = [[-180, -90], [-180, 90], [180, 90], [180, -90], [-180, -90]]; + const ccw = [[-180, -90], [180, -90], [180, 90], [-180, 90], [-180, -90]]; + const right = new Polygon([ccw, cw]); + const rightMulti = new MultiPolygon([[ccw, cw]]); + const left = new Polygon([cw, ccw]); + const leftMulti = new MultiPolygon([[cw, ccw]]); - var rightObj = { + const rightObj = { type: 'Polygon', coordinates: [ccw, cw] }; - var rightMultiObj = { + const rightMultiObj = { type: 'MultiPolygon', coordinates: [[ccw, cw]] }; - var json = format.writeGeometry(right, {rightHanded: true}); + let json = format.writeGeometry(right, {rightHanded: true}); expect(JSON.parse(json)).to.eql(rightObj); json = format.writeGeometry(rightMulti, {rightHanded: true}); expect(JSON.parse(json)).to.eql(rightMultiObj); @@ -699,24 +699,24 @@ describe('ol.format.GeoJSON', function() { it('allows serializing following the left-hand rule', function() { - var cw = [[-180, -90], [-180, 90], [180, 90], [180, -90], [-180, -90]]; - var ccw = [[-180, -90], [180, -90], [180, 90], [-180, 90], [-180, -90]]; - var right = new Polygon([ccw, cw]); - var rightMulti = new MultiPolygon([[ccw, cw]]); - var left = new Polygon([cw, ccw]); - var leftMulti = new MultiPolygon([[cw, ccw]]); + const cw = [[-180, -90], [-180, 90], [180, 90], [180, -90], [-180, -90]]; + const ccw = [[-180, -90], [180, -90], [180, 90], [-180, 90], [-180, -90]]; + const right = new Polygon([ccw, cw]); + const rightMulti = new MultiPolygon([[ccw, cw]]); + const left = new Polygon([cw, ccw]); + const leftMulti = new MultiPolygon([[cw, ccw]]); - var leftObj = { + const leftObj = { type: 'Polygon', coordinates: [cw, ccw] }; - var leftMultiObj = { + const leftMultiObj = { type: 'MultiPolygon', coordinates: [[cw, ccw]] }; - var json = format.writeGeometry(right, {rightHanded: false}); + let json = format.writeGeometry(right, {rightHanded: false}); expect(JSON.parse(json)).to.eql(leftObj); json = format.writeGeometry(rightMulti, {rightHanded: false}); expect(JSON.parse(json)).to.eql(leftMultiObj); @@ -729,26 +729,26 @@ describe('ol.format.GeoJSON', function() { }); it('encodes geometry collection', function() { - var collection = new GeometryCollection([ + const collection = new GeometryCollection([ new Point([10, 20]), new LineString([[30, 40], [50, 60]]) ]); - var geojson = format.writeGeometry(collection); - var got = format.readGeometry(geojson); + const geojson = format.writeGeometry(collection); + const got = format.readGeometry(geojson); expect(got).to.be.an(GeometryCollection); - var gotGeometries = got.getGeometries(); - var geometries = collection.getGeometries(); + const gotGeometries = got.getGeometries(); + const geometries = collection.getGeometries(); expect(geometries.length).to.equal(gotGeometries.length); - for (var i = 0, ii = geometries.length; i < ii; ++i) { + for (let i = 0, ii = geometries.length; i < ii; ++i) { expect(geometries[i].getCoordinates()). - to.eql(gotGeometries[i].getCoordinates()); + to.eql(gotGeometries[i].getCoordinates()); } }); it('encodes a circle as an empty geometry collection', function() { - var circle = new Circle([0, 0], 1); - var geojson = format.writeGeometryObject(circle); + const circle = new Circle([0, 0], 1); + const geojson = format.writeGeometryObject(circle); expect(geojson).to.eql({ 'type': 'GeometryCollection', 'geometries': [] @@ -756,74 +756,74 @@ describe('ol.format.GeoJSON', function() { }); it('transforms and encodes a point', function() { - var point = new Point([2, 3]); - var geojson = format.writeGeometry(point, { + const point = new Point([2, 3]); + const geojson = format.writeGeometry(point, { featureProjection: 'EPSG:3857' }); - var newPoint = format.readGeometry(geojson, { + const newPoint = format.readGeometry(geojson, { featureProjection: 'EPSG:3857' }); expect(point.getCoordinates()[0]).to.roughlyEqual( - newPoint.getCoordinates()[0], 1e-8); + newPoint.getCoordinates()[0], 1e-8); expect(point.getCoordinates()[1]).to.roughlyEqual( - newPoint.getCoordinates()[1], 1e-8); + newPoint.getCoordinates()[1], 1e-8); }); it('transforms and encodes geometry collection', function() { - var collection = new GeometryCollection([ + const collection = new GeometryCollection([ new Point([2, 3]), new LineString([[3, 2], [2, 1]]) ]); - var geojson = format.writeGeometry(collection, { + const geojson = format.writeGeometry(collection, { featureProjection: 'EPSG:3857' }); - var got = format.readGeometry(geojson, { + const got = format.readGeometry(geojson, { featureProjection: 'EPSG:3857' }); - var gotGeometries = got.getGeometries(); - var geometries = collection.getGeometries(); + const gotGeometries = got.getGeometries(); + const geometries = collection.getGeometries(); expect(geometries[0].getCoordinates()[0]).to.roughlyEqual( - gotGeometries[0].getCoordinates()[0], 1e-8); + gotGeometries[0].getCoordinates()[0], 1e-8); expect(geometries[0].getCoordinates()[1]).to.roughlyEqual( - gotGeometries[0].getCoordinates()[1], 1e-8); + gotGeometries[0].getCoordinates()[1], 1e-8); expect(geometries[1].getCoordinates()[0][0]).to.roughlyEqual( - gotGeometries[1].getCoordinates()[0][0], 1e-8); + gotGeometries[1].getCoordinates()[0][0], 1e-8); expect(geometries[1].getCoordinates()[0][1]).to.roughlyEqual( - gotGeometries[1].getCoordinates()[0][1], 1e-8); + gotGeometries[1].getCoordinates()[0][1], 1e-8); }); it('truncates transformed point with decimals option', function() { - var point = new Point([2, 3]).transform('EPSG:4326', 'EPSG:3857'); - var geojson = format.writeGeometry(point, { + const point = new Point([2, 3]).transform('EPSG:4326', 'EPSG:3857'); + const geojson = format.writeGeometry(point, { featureProjection: 'EPSG:3857', decimals: 2 }); expect(format.readGeometry(geojson).getCoordinates()).to.eql( - [2, 3]); + [2, 3]); }); it('truncates a linestring with decimals option', function() { - var linestring = new LineString([[42.123456789, 38.987654321], + const linestring = new LineString([[42.123456789, 38.987654321], [43, 39]]); - var geojson = format.writeGeometry(linestring, { + const geojson = format.writeGeometry(linestring, { decimals: 6 }); expect(format.readGeometry(geojson).getCoordinates()).to.eql( - [[42.123457, 38.987654], [43, 39]]); + [[42.123457, 38.987654], [43, 39]]); expect(linestring.getCoordinates()).to.eql( - [[42.123456789, 38.987654321], [43, 39]]); + [[42.123456789, 38.987654321], [43, 39]]); }); it('rounds a linestring with decimals option = 0', function() { - var linestring = new LineString([[42.123456789, 38.987654321], + const linestring = new LineString([[42.123456789, 38.987654321], [43, 39]]); - var geojson = format.writeGeometry(linestring, { + const geojson = format.writeGeometry(linestring, { decimals: 0 }); expect(format.readGeometry(geojson).getCoordinates()).to.eql( - [[42, 39], [43, 39]]); + [[42, 39], [43, 39]]); expect(linestring.getCoordinates()).to.eql( - [[42.123456789, 38.987654321], [43, 39]]); + [[42.123456789, 38.987654321], [43, 39]]); }); }); diff --git a/test/spec/ol/format/gml.test.js b/test/spec/ol/format/gml.test.js index 2d4f4cf730..c64156ab15 100644 --- a/test/spec/ol/format/gml.test.js +++ b/test/spec/ol/format/gml.test.js @@ -11,25 +11,25 @@ import Polygon from '../../../../src/ol/geom/Polygon.js'; import {transform} from '../../../../src/ol/proj.js'; import _ol_xml_ from '../../../../src/ol/xml.js'; -var readGeometry = function(format, text, opt_options) { - var doc = _ol_xml_.parse(text); +const readGeometry = function(format, text, opt_options) { + const doc = _ol_xml_.parse(text); // we need an intermediate node for testing purposes - var node = document.createElement('PRE'); + const node = document.createElement('PRE'); node.appendChild(doc.documentElement); return format.readGeometryFromNode(node, opt_options); }; describe('ol.format.GML2', function() { - var format; + let format; beforeEach(function() { format = new GML2({srsName: 'CRS:84'}); }); describe('#readFeatures', function() { - var features; + let features; before(function(done) { - var url = 'spec/ol/format/gml/osm-wfs-10.xml'; + const url = 'spec/ol/format/gml/osm-wfs-10.xml'; afterLoadText(url, function(xml) { try { features = new GML2().readFeatures(xml); @@ -51,41 +51,41 @@ describe('ol.format.GML2', function() { describe('gml 2.1.2', function() { it('can read a point geometry', function() { - var text = '' + ' -90,-180' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(Point); expect(g.getCoordinates()).to.eql([-180, -90, 0]); }); it('can read a 3D point geometry', function() { - var text = '' + ' -90,-180,42' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(Point); expect(g.getCoordinates()).to.eql([-180, -90, 42]); }); it('can read a box element', function() { - var text = '' + ' -0.768746,47.003018 ' + ' 3.002191,47.925567' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.eql([47.003018, -0.768746, 47.925567, 3.002191]); }); it('can read a multipolygon with gml:coordinates', function() { - var text = + const text = '' + ' ' + @@ -117,7 +117,7 @@ describe('ol.format.GML2', function() { ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiPolygon); expect(g.getCoordinates()).to.eql([ [ @@ -143,14 +143,14 @@ describe('ol.format.GML2', function() { }); describe('#writeFeatureElement', function() { - var node; - var featureNS = 'http://www.openlayers.org/'; + let node; + const featureNS = 'http://www.openlayers.org/'; beforeEach(function() { node = _ol_xml_.createElementNS(featureNS, 'layer'); }); it('can serialize a LineString', function() { - var expected = + const expected = '' + ' ' + ' ' + ' '; - var feature = new Feature({ + const feature = new Feature({ geometry: new LineString([[1.1, 2], [3, 4.2]]) }); feature.setId(1); - var objectStack = [{ + const objectStack = [{ featureNS: featureNS, srsName: 'EPSG:4326' }]; @@ -177,7 +177,7 @@ describe('ol.format.GML2', function() { }); it('can serialize a Polygon', function() { - var expected = + const expected = '' + ' ' + ' ' + ' '; - var feature = new Feature({ + const feature = new Feature({ geometry: new Polygon([[[1.1, 2], [3, 4.2], [5.2, 6]]]) }); feature.setId(1); - var objectStack = [{ + const objectStack = [{ featureNS: featureNS, srsName: 'EPSG:4326' }]; @@ -208,7 +208,7 @@ describe('ol.format.GML2', function() { }); it('can serialize a Point', function() { - var expected = + const expected = '' + ' ' + ' ' + ' '; - var feature = new Feature({ + const feature = new Feature({ geometry: new Point([1.1, 2]) }); feature.setId(1); - var objectStack = [{ + const objectStack = [{ featureNS: featureNS, srsName: 'EPSG:4326' }]; @@ -235,7 +235,7 @@ describe('ol.format.GML2', function() { }); it('can serialize a Multi Point', function() { - var expected = + const expected = '' + ' ' + ' ' + ' '; - var feature = new Feature({ + const feature = new Feature({ geometry: new MultiPoint([[1.1, 2]]) }); feature.setId(1); - var objectStack = [{ + const objectStack = [{ featureNS: featureNS, srsName: 'EPSG:4326' }]; @@ -266,7 +266,7 @@ describe('ol.format.GML2', function() { }); it('can serialize a Multi Line String', function() { - var expected = + const expected = '' + ' ' + ' ' + ' '; - var feature = new Feature({ + const feature = new Feature({ geometry: new MultiLineString([[[1.1, 2], [3, 4.2]]]) }); feature.setId(1); - var objectStack = [{ + const objectStack = [{ featureNS: featureNS, srsName: 'EPSG:4326' }]; @@ -297,7 +297,7 @@ describe('ol.format.GML2', function() { }); it('can serialize a Multi Polygon', function() { - var expected = + const expected = '' + ' ' + ' ' + ' '; - var feature = new Feature({ + const feature = new Feature({ geometry: new MultiPolygon([[[[1.1, 2], [3, 4.2], [5.2, 6]]]]) }); feature.setId(1); - var objectStack = [{ + const objectStack = [{ featureNS: featureNS, srsName: 'EPSG:4326' }]; @@ -335,7 +335,7 @@ describe('ol.format.GML2', function() { describe('ol.format.GML3', function() { - var format, formatWGS84, formatNoSrs; + let format, formatWGS84, formatNoSrs; beforeEach(function() { format = new _ol_format_GML_({srsName: 'CRS:84'}); formatWGS84 = new _ol_format_GML_({ @@ -349,25 +349,25 @@ describe('ol.format.GML3', function() { describe('point', function() { it('can read and write a point geometry', function() { - var text = + const text = '' + ' 1 2' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(Point); expect(g.getCoordinates()).to.eql([1, 2, 0]); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); it('can read a point geometry with scientific notation', function() { - var text = + let text = '' + ' 1E7 2' + ''; - var g = readGeometry(format, text); + let g = readGeometry(format, text); expect(g).to.be.an(Point); expect(g.getCoordinates()).to.eql([10000000, 2, 0]); text = @@ -381,53 +381,53 @@ describe('ol.format.GML3', function() { }); it('can read, transform and write a point geometry', function() { - var config = { + const config = { featureProjection: 'EPSG:3857' }; - var text = + const text = '' + ' 1 2' + ''; - var g = readGeometry(format, text, config); + const g = readGeometry(format, text, config); expect(g).to.be.an(Point); - var coordinates = g.getCoordinates(); + const coordinates = g.getCoordinates(); expect(coordinates.splice(0, 2)).to.eql( - transform([1, 2], 'CRS:84', 'EPSG:3857')); + transform([1, 2], 'CRS:84', 'EPSG:3857')); config.dataProjection = 'CRS:84'; - var serialized = format.writeGeometryNode(g, config); - var pos = serialized.firstElementChild.firstElementChild.textContent; - var coordinate = pos.split(' '); + const serialized = format.writeGeometryNode(g, config); + const pos = serialized.firstElementChild.firstElementChild.textContent; + const coordinate = pos.split(' '); expect(coordinate[0]).to.roughlyEqual(1, 1e-9); expect(coordinate[1]).to.roughlyEqual(2, 1e-9); }); it('can detect SRS, read and transform a point geometry', function() { - var config = { + const config = { featureProjection: 'EPSG:3857' }; - var text = + const text = '' + ' 1 2' + ''; - var g = readGeometry(formatNoSrs, text, config); + const g = readGeometry(formatNoSrs, text, config); expect(g).to.be.an(Point); - var coordinates = g.getCoordinates(); + const coordinates = g.getCoordinates(); expect(coordinates.splice(0, 2)).to.eql( - transform([1, 2], 'CRS:84', 'EPSG:3857')); + transform([1, 2], 'CRS:84', 'EPSG:3857')); }); it('can read and write a point geometry in EPSG:4326', function() { - var text = + const text = '' + ' 2 1' + ''; - var g = readGeometry(formatWGS84, text); + const g = readGeometry(formatWGS84, text); expect(g).to.be.an(Point); expect(g.getCoordinates()).to.eql([1, 2, 0]); - var serialized = formatWGS84.writeGeometryNode(g); + const serialized = formatWGS84.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); @@ -436,38 +436,38 @@ describe('ol.format.GML3', function() { describe('linestring', function() { it('can read and write a linestring geometry', function() { - var text = + const text = '' + ' 1 2 3 4' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(LineString); expect(g.getCoordinates()).to.eql([[1, 2, 0], [3, 4, 0]]); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); it('can read, transform and write a linestring geometry', function() { - var config = { + const config = { dataProjection: 'CRS:84', featureProjection: 'EPSG:3857' }; - var text = + const text = '' + ' 1 2 3 4' + ''; - var g = readGeometry(format, text, config); + const g = readGeometry(format, text, config); expect(g).to.be.an(LineString); - var coordinates = g.getCoordinates(); + const coordinates = g.getCoordinates(); expect(coordinates[0].slice(0, 2)).to.eql( - transform([1, 2], 'CRS:84', 'EPSG:3857')); + transform([1, 2], 'CRS:84', 'EPSG:3857')); expect(coordinates[1].slice(0, 2)).to.eql( - transform([3, 4], 'CRS:84', 'EPSG:3857')); - var serialized = format.writeGeometryNode(g, config); - var poss = serialized.firstElementChild.firstElementChild.textContent; - var coordinate = poss.split(' '); + transform([3, 4], 'CRS:84', 'EPSG:3857')); + const serialized = format.writeGeometryNode(g, config); + const poss = serialized.firstElementChild.firstElementChild.textContent; + const coordinate = poss.split(' '); expect(coordinate[0]).to.roughlyEqual(1, 1e-9); expect(coordinate[1]).to.roughlyEqual(2, 1e-9); expect(coordinate[2]).to.roughlyEqual(3, 1e-9); @@ -475,15 +475,15 @@ describe('ol.format.GML3', function() { }); it('can read and write a linestring geometry in EPSG:4326', function() { - var text = + const text = '' + ' 2 1 4 3' + ''; - var g = readGeometry(formatWGS84, text); + const g = readGeometry(formatWGS84, text); expect(g).to.be.an(LineString); expect(g.getCoordinates()).to.eql([[1, 2, 0], [3, 4, 0]]); - var serialized = formatWGS84.writeGeometryNode(g); + const serialized = formatWGS84.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); @@ -494,35 +494,35 @@ describe('ol.format.GML3', function() { it('can read and write a linestring geometry with ' + 'correct axis order', function() { - var text = + const text = '' + ' -90 -180 90 180' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(LineString); expect(g.getCoordinates()).to.eql([[-180, -90, 0], [180, 90, 0]]); - var serialized = formatWGS84.writeGeometryNode(g); + const serialized = formatWGS84.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); it('can read and write a point geometry with correct axis order', - function() { - var text = + function() { + const text = '' + ' -90 -180' + ''; - var g = readGeometry(format, text); - expect(g).to.be.an(Point); - expect(g.getCoordinates()).to.eql([-180, -90, 0]); - var serialized = formatWGS84.writeGeometryNode(g); - expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); - }); + const g = readGeometry(format, text); + expect(g).to.be.an(Point); + expect(g.getCoordinates()).to.eql([-180, -90, 0]); + const serialized = formatWGS84.writeGeometryNode(g); + expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); + }); it('can read and write a surface geometry with right axis order', - function() { - var text = + function() { + const text = '' + ' ' + @@ -542,27 +542,27 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); - expect(g.getCoordinates()[0][0][0][0]).to.equal(-77.0081); - expect(g.getCoordinates()[0][0][0][1]).to.equal(38.9661); - format = new _ol_format_GML_({ - srsName: 'urn:x-ogc:def:crs:EPSG:4326', - surface: false}); - var serialized = format.writeGeometryNode(g); - expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); - }); + const g = readGeometry(format, text); + expect(g.getCoordinates()[0][0][0][0]).to.equal(-77.0081); + expect(g.getCoordinates()[0][0][0][1]).to.equal(38.9661); + format = new _ol_format_GML_({ + srsName: 'urn:x-ogc:def:crs:EPSG:4326', + surface: false}); + const serialized = format.writeGeometryNode(g); + expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); + }); }); describe('linestring 3D', function() { it('can read a linestring 3D geometry', function() { - var text = + const text = '' + ' 1 2 3 4 5 6' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(LineString); expect(g.getCoordinates()).to.eql([[1, 2, 3], [4, 5, 6]]); }); @@ -572,16 +572,16 @@ describe('ol.format.GML3', function() { describe('linearring', function() { it('can read and write a linearring geometry', function() { - var text = + const text = '' + ' 1 2 3 4 5 6 1 2' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(LinearRing); expect(g.getCoordinates()).to.eql( - [[1, 2, 0], [3, 4, 0], [5, 6, 0], [1, 2, 0]]); - var serialized = format.writeGeometryNode(g); + [[1, 2, 0], [3, 4, 0], [5, 6, 0], [1, 2, 0]]); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); @@ -590,7 +590,7 @@ describe('ol.format.GML3', function() { describe('polygon', function() { it('can read and write a polygon geometry', function() { - var text = + const text = '' + ' ' + @@ -609,12 +609,12 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(Polygon); expect(g.getCoordinates()).to.eql([[[1, 2, 0], [3, 2, 0], [3, 4, 0], [1, 2, 0]], [[2, 3, 0], [2, 5, 0], [4, 5, 0], [2, 3, 0]], [[3, 4, 0], [3, 6, 0], [5, 6, 0], [3, 4, 0]]]); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); @@ -623,7 +623,7 @@ describe('ol.format.GML3', function() { describe('surface', function() { it('can read and write a surface geometry', function() { - var text = + const text = '' + ' ' + @@ -652,13 +652,13 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(Polygon); expect(g.getCoordinates()).to.eql([[[1, 2, 0], [3, 2, 0], [3, 4, 0], [1, 2, 0]], [[2, 3, 0], [2, 5, 0], [4, 5, 0], [2, 3, 0]], [[3, 4, 0], [3, 6, 0], [5, 6, 0], [3, 4, 0]]]); format = new _ol_format_GML_({srsName: 'CRS:84', surface: true}); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); @@ -667,7 +667,7 @@ describe('ol.format.GML3', function() { describe('curve', function() { it('can read and write a curve geometry', function() { - var text = + const text = '' + ' ' + @@ -676,11 +676,11 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(LineString); expect(g.getCoordinates()).to.eql([[1, 2, 0], [3, 4, 0]]); format = new _ol_format_GML_({srsName: 'CRS:84', curve: true}); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); @@ -689,13 +689,13 @@ describe('ol.format.GML3', function() { describe('envelope', function() { it('can read an envelope geometry', function() { - var text = + const text = '' + ' 1 2' + ' 3 4' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.eql([1, 2, 3, 4]); }); @@ -704,7 +704,7 @@ describe('ol.format.GML3', function() { describe('multipoint', function() { it('can read and write a singular multipoint geometry', function() { - var text = + const text = '' + ' ' + @@ -723,15 +723,15 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiPoint); expect(g.getCoordinates()).to.eql([[1, 2, 0], [2, 3, 0], [3, 4, 0]]); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); it('can read a plural multipoint geometry', function() { - var text = + const text = '' + ' ' + @@ -746,7 +746,7 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiPoint); expect(g.getCoordinates()).to.eql([[1, 2, 0], [2, 3, 0], [3, 4, 0]]); }); @@ -756,7 +756,7 @@ describe('ol.format.GML3', function() { describe('multilinestring', function() { it('can read and write a singular multilinestring geometry', function() { - var text = + const text = '' + ' ' + @@ -770,17 +770,17 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiLineString); expect(g.getCoordinates()).to.eql( - [[[1, 2, 0], [2, 3, 0]], [[3, 4, 0], [4, 5, 0]]]); + [[[1, 2, 0], [2, 3, 0]], [[3, 4, 0], [4, 5, 0]]]); format = new _ol_format_GML_({srsName: 'CRS:84', multiCurve: false}); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); it('can read a plural multilinestring geometry', function() { - var text = + const text = '' + ' ' + @@ -792,10 +792,10 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiLineString); expect(g.getCoordinates()).to.eql( - [[[1, 2, 0], [2, 3, 0]], [[3, 4, 0], [4, 5, 0]]]); + [[[1, 2, 0], [2, 3, 0]], [[3, 4, 0], [4, 5, 0]]]); }); }); @@ -803,7 +803,7 @@ describe('ol.format.GML3', function() { describe('multipolygon', function() { it('can read and write a singular multipolygon geometry', function() { - var text = + const text = '' + ' ' + @@ -843,7 +843,7 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiPolygon); expect(g.getCoordinates()).to.eql([ [[[1, 2, 0], [3, 2, 0], [3, 4, 0], @@ -851,12 +851,12 @@ describe('ol.format.GML3', function() { [[3, 4, 0], [3, 6, 0], [5, 6, 0], [3, 4, 0]]], [[[1, 2, 0], [3, 2, 0], [3, 4, 0], [1, 2, 0]]]]); format = new _ol_format_GML_({srsName: 'CRS:84', multiSurface: false}); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); it('can read a plural multipolygon geometry', function() { - var text = + const text = '' + ' ' + @@ -886,7 +886,7 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiPolygon); expect(g.getCoordinates()).to.eql([ [[[1, 2, 0], [3, 2, 0], [3, 4, 0], @@ -900,8 +900,8 @@ describe('ol.format.GML3', function() { describe('multicurve', function() { it('can read and write a singular multicurve-linestring geometry', - function() { - var text = + function() { + const text = '' + ' ' + @@ -915,16 +915,16 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); - expect(g).to.be.an(MultiLineString); - expect(g.getCoordinates()).to.eql( - [[[1, 2, 0], [2, 3, 0]], [[3, 4, 0], [4, 5, 0]]]); - var serialized = format.writeGeometryNode(g); - expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); - }); + const g = readGeometry(format, text); + expect(g).to.be.an(MultiLineString); + expect(g.getCoordinates()).to.eql( + [[[1, 2, 0], [2, 3, 0]], [[3, 4, 0], [4, 5, 0]]]); + const serialized = format.writeGeometryNode(g); + expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); + }); it('can read and write a singular multicurve-curve geometry', function() { - var text = + const text = '' + ' ' + @@ -946,12 +946,12 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiLineString); expect(g.getCoordinates()).to.eql( - [[[1, 2, 0], [2, 3, 0]], [[3, 4, 0], [4, 5, 0]]]); + [[[1, 2, 0], [2, 3, 0]], [[3, 4, 0], [4, 5, 0]]]); format = new _ol_format_GML_({srsName: 'CRS:84', curve: true}); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); @@ -960,7 +960,7 @@ describe('ol.format.GML3', function() { describe('multisurface', function() { it('can read and write a singular multisurface geometry', function() { - var text = + const text = '' + ' ' + @@ -1000,19 +1000,19 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiPolygon); expect(g.getCoordinates()).to.eql([ [[[1, 2, 0], [3, 2, 0], [3, 4, 0], [1, 2, 0]], [[2, 3, 0], [2, 5, 0], [4, 5, 0], [2, 3, 0]], [[3, 4, 0], [3, 6, 0], [5, 6, 0], [3, 4, 0]]], [[[1, 2, 0], [3, 2, 0], [3, 4, 0], [1, 2, 0]]]]); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); it('can read a plural multisurface geometry', function() { - var text = + const text = '' + ' ' + @@ -1044,7 +1044,7 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiPolygon); expect(g.getCoordinates()).to.eql([ [[[1, 2, 0], [3, 2, 0], [3, 4, 0], @@ -1054,7 +1054,7 @@ describe('ol.format.GML3', function() { }); it('can read and write a multisurface-surface geometry', function() { - var text = + const text = '' + ' ' + @@ -1102,7 +1102,7 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var g = readGeometry(format, text); + const g = readGeometry(format, text); expect(g).to.be.an(MultiPolygon); expect(g.getCoordinates()).to.eql([ [[[1, 2, 0], [3, 2, 0], [3, 4, 0], @@ -1110,7 +1110,7 @@ describe('ol.format.GML3', function() { [[3, 4, 0], [3, 6, 0], [5, 6, 0], [3, 4, 0]]], [[[1, 2, 0], [3, 2, 0], [3, 4, 0], [1, 2, 0]]]]); format = new _ol_format_GML_({srsName: 'CRS:84', surface: true}); - var serialized = format.writeGeometryNode(g); + const serialized = format.writeGeometryNode(g); expect(serialized.firstElementChild).to.xmleql(_ol_xml_.parse(text)); }); @@ -1120,7 +1120,7 @@ describe('ol.format.GML3', function() { describe('when parsing empty attribute', function() { it('generates undefined value', function() { - var text = + const text = '' + ' ' + @@ -1137,21 +1137,21 @@ describe('ol.format.GML3', function() { ' ' + ' ' + ''; - var config = { + const config = { 'featureNS': 'http://www.openplans.org/topp', 'featureType': 'gnis_pop' }; - var features = new _ol_format_GML_(config).readFeatures(text); - var feature = features[0]; + const features = new _ol_format_GML_(config).readFeatures(text); + const feature = features[0]; expect(feature.get('empty')).to.be(undefined); }); }); describe('when parsing CDATA attribute', function() { - var features; + let features; before(function(done) { try { - var text = + const text = '' + ' ' + @@ -1168,7 +1168,7 @@ describe('ol.format.GML3', function() { ' b]]>' + ' ' + ''; - var config = { + const config = { 'featureNS': 'http://www.openplans.org/topp', 'featureType': 'gnis_pop' }; @@ -1189,7 +1189,7 @@ describe('ol.format.GML3', function() { }); describe('when parsing TOPP states WFS with autoconfigure', function() { - var features, gmlFormat; + let features, gmlFormat; before(function(done) { afterLoadText('spec/ol/format/gml/topp-states-wfs.xml', function(xml) { try { @@ -1211,7 +1211,7 @@ describe('ol.format.GML3', function() { }); it('can reuse the parser for a different featureNS', function() { - var text = + const text = '' + ' ' + @@ -1230,7 +1230,7 @@ describe('ol.format.GML3', function() { }); it('can read an empty collection', function() { - var text = + const text = '' + ''; features = gmlFormat.readFeatures(text); @@ -1241,16 +1241,16 @@ describe('ol.format.GML3', function() { describe('when parsing TOPP states GML', function() { - var features, text, gmlFormat; + let features, text, gmlFormat; before(function(done) { afterLoadText('spec/ol/format/gml/topp-states-gml.xml', function(xml) { try { - var schemaLoc = 'http://www.openplans.org/topp ' + + const schemaLoc = 'http://www.openplans.org/topp ' + 'http://demo.opengeo.org/geoserver/wfs?service=WFS&version=' + '1.1.0&request=DescribeFeatureType&typeName=topp:states ' + 'http://www.opengis.net/gml ' + 'http://schemas.opengis.net/gml/3.2.1/gml.xsd'; - var config = { + const config = { 'featureNS': 'http://www.openplans.org/topp', 'featureType': 'states', 'multiSurface': true, @@ -1276,7 +1276,7 @@ describe('ol.format.GML3', function() { }); it('writes back features as GML', function() { - var serialized = gmlFormat.writeFeaturesNode(features); + const serialized = gmlFormat.writeFeaturesNode(features); expect(serialized).to.xmleql(_ol_xml_.parse(text), {ignoreElementOrder: true}); }); @@ -1284,11 +1284,11 @@ describe('ol.format.GML3', function() { describe('when parsing TOPP states GML from WFS', function() { - var features, feature; + let features, feature; before(function(done) { afterLoadText('spec/ol/format/gml/topp-states-wfs.xml', function(xml) { try { - var config = { + const config = { 'featureNS': 'http://www.openplans.org/topp', 'featureType': 'states' }; @@ -1315,11 +1315,11 @@ describe('ol.format.GML3', function() { describe('when parsing more than one geometry', function() { - var features; + let features; before(function(done) { afterLoadText('spec/ol/format/gml/more-geoms.xml', function(xml) { try { - var config = { + const config = { 'featureNS': 'http://opengeo.org/#medford', 'featureType': 'zoning' }; @@ -1332,7 +1332,7 @@ describe('ol.format.GML3', function() { }); it('creates 2 geometries', function() { - var feature = features[0]; + const feature = features[0]; expect(feature.get('center')).to.be.a(Point); expect(feature.get('the_geom')).to.be.a(MultiPolygon); }); @@ -1341,11 +1341,11 @@ describe('ol.format.GML3', function() { describe('when parsing an attribute name equal to featureType', function() { - var features; + let features; before(function(done) { afterLoadText('spec/ol/format/gml/repeated-name.xml', function(xml) { try { - var config = { + const config = { 'featureNS': 'http://opengeo.org/#medford', 'featureType': 'zoning' }; @@ -1358,7 +1358,7 @@ describe('ol.format.GML3', function() { }); it('creates the correct attribute value', function() { - var feature = features[0]; + const feature = features[0]; expect(feature.get('zoning')).to.equal('I-L'); }); @@ -1366,7 +1366,7 @@ describe('ol.format.GML3', function() { describe('when parsing only a boundedBy element and no geometry', function() { - var features; + let features; before(function(done) { afterLoadText('spec/ol/format/gml/only-boundedby.xml', function(xml) { try { @@ -1379,7 +1379,7 @@ describe('ol.format.GML3', function() { }); it('creates a feature without a geometry', function() { - var feature = features[0]; + const feature = features[0]; expect(feature.getGeometry()).to.be(undefined); }); @@ -1387,7 +1387,7 @@ describe('ol.format.GML3', function() { describe('when parsing from OGR', function() { - var features; + let features; before(function(done) { afterLoadText('spec/ol/format/gml/ogr.xml', function(xml) { try { @@ -1407,7 +1407,7 @@ describe('ol.format.GML3', function() { describe('when parsing multiple feature types', function() { - var features; + let features; before(function(done) { afterLoadText('spec/ol/format/gml/multiple-typenames.xml', function(xml) { try { @@ -1430,7 +1430,7 @@ describe('ol.format.GML3', function() { describe('when parsing multiple feature types', function() { - var features; + let features; before(function(done) { afterLoadText('spec/ol/format/gml/multiple-typenames.xml', function(xml) { try { @@ -1450,9 +1450,9 @@ describe('ol.format.GML3', function() { describe('when parsing multiple feature types / namespaces', function() { - var features; + let features; before(function(done) { - var url = 'spec/ol/format/gml/multiple-typenames-ns.xml'; + const url = 'spec/ol/format/gml/multiple-typenames-ns.xml'; afterLoadText(url, function(xml) { try { features = new _ol_format_GML_({ @@ -1477,9 +1477,9 @@ describe('ol.format.GML3', function() { describe('when parsing multiple feature types / namespaces', function() { - var features; + let features; before(function(done) { - var url = 'spec/ol/format/gml/multiple-typenames-ns.xml'; + const url = 'spec/ol/format/gml/multiple-typenames-ns.xml'; afterLoadText(url, function(xml) { try { features = new _ol_format_GML_().readFeatures(xml); @@ -1498,21 +1498,21 @@ describe('ol.format.GML3', function() { describe('when parsing srsDimension from WFS (Geoserver)', function() { - var features, feature; + let features, feature; before(function(done) { afterLoadText('spec/ol/format/gml/geoserver3DFeatures.xml', - function(xml) { - try { - var config = { - 'featureNS': 'http://www.opengeospatial.net/cite', - 'featureType': 'geoserver_layer' - }; - features = new _ol_format_GML_(config).readFeatures(xml); - } catch (e) { - done(e); - } - done(); - }); + function(xml) { + try { + const config = { + 'featureNS': 'http://www.opengeospatial.net/cite', + 'featureType': 'geoserver_layer' + }; + features = new _ol_format_GML_(config).readFeatures(xml); + } catch (e) { + done(e); + } + done(); + }); }); it('creates 3 features', function() { @@ -1539,30 +1539,30 @@ describe('ol.format.GML3', function() { it('creates 3D Features with the expected geometries', function() { - var expectedGeometry1 = [ + const expectedGeometry1 = [ 4.46386854, 51.91122415, 46.04679351, 4.46382399, 51.91120839, 46.04679382 ]; - var expectedGeometry2 = [ + const expectedGeometry2 = [ 4.46385491, 51.91119276, 46.06074531, 4.4638264, 51.91118582, 46.06074609, 4.46380612, 51.91121772, 46.06074168, 4.46383463, 51.91122465, 46.06074089, 4.46385491, 51.91119276, 46.06074531 ]; - var expectedGeometry3 = [ + const expectedGeometry3 = [ 4.46383715, 51.91125849, 46.04679348 ]; feature = features[0]; expect(feature.getGeometry().getFlatCoordinates()) - .to.eql(expectedGeometry1); + .to.eql(expectedGeometry1); feature = features[1]; expect(feature.getGeometry().getFlatCoordinates()) - .to.eql(expectedGeometry2); + .to.eql(expectedGeometry2); feature = features[2]; expect(feature.getGeometry().getFlatCoordinates()) - .to.eql(expectedGeometry3); + .to.eql(expectedGeometry3); }); }); diff --git a/test/spec/ol/format/gpx.test.js b/test/spec/ol/format/gpx.test.js index 27914b2048..6664c36867 100644 --- a/test/spec/ol/format/gpx.test.js +++ b/test/spec/ol/format/gpx.test.js @@ -9,19 +9,19 @@ import _ol_xml_ from '../../../../src/ol/xml.js'; describe('ol.format.GPX', function() { - var format; + let format; beforeEach(function() { format = new GPX(); }); describe('#readProjection', function() { it('returns the default projection from document', function() { - var projection = format.readProjectionFromDocument(); + const projection = format.readProjectionFromDocument(); expect(projection).to.eql(getProjection('EPSG:4326')); }); it('returns the default projection from node', function() { - var projection = format.readProjectionFromNode(); + const projection = format.readProjectionFromNode(); expect(projection).to.eql(getProjection('EPSG:4326')); }); }); @@ -29,22 +29,22 @@ describe('ol.format.GPX', function() { describe('rte', function() { it('can read an empty rte', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(LineString); expect(g.getCoordinates()).to.eql([]); expect(g.getLayout()).to.be('XY'); }); it('can read and write various rte attributes', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(LineString); expect(g.getCoordinates()).to.eql([[2, 1], [4, 3]]); expect(g.getLayout()).to.be('XY'); - var serialized = format.writeFeaturesNode(fs); + const serialized = format.writeFeaturesNode(fs); expect(serialized).to.xmleql(_ol_xml_.parse(text)); }); it('can transform, read and write a rte', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text, { + const fs = format.readFeatures(text, { featureProjection: 'EPSG:3857' }); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(LineString); - var p1 = transform([2, 1], 'EPSG:4326', 'EPSG:3857'); - var p2 = transform([6, 5], 'EPSG:4326', 'EPSG:3857'); + const p1 = transform([2, 1], 'EPSG:4326', 'EPSG:3857'); + const p2 = transform([6, 5], 'EPSG:4326', 'EPSG:3857'); expect(g.getCoordinates()).to.eql([p1, p2]); expect(g.getLayout()).to.be('XY'); - var serialized = format.writeFeaturesNode(fs, { + const serialized = format.writeFeaturesNode(fs, { featureProjection: 'EPSG:3857' }); expect(serialized).to.xmleql(_ol_xml_.parse(text)); }); it('does not write rte attributes in rtepts', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text); - var serialized = format.writeFeaturesNode(fs); + const fs = format.readFeatures(text); + const serialized = format.writeFeaturesNode(fs); expect(serialized).to.xmleql(_ol_xml_.parse(text)); }); @@ -153,22 +153,22 @@ describe('ol.format.GPX', function() { describe('trk', function() { it('can read an empty trk', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(MultiLineString); expect(g.getCoordinates()).to.eql([]); expect(g.getLayout()).to.be('XY'); }); it('can read and write various trk attributes', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(Point); expect(g.getCoordinates()).to.eql([2, 1]); expect(g.getLayout()).to.be('XY'); - var serialized = format.writeFeaturesNode(fs); + const serialized = format.writeFeaturesNode(fs); expect(serialized).to.xmleql(_ol_xml_.parse(text)); }); it('can transform, read and write a wpt', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text, { + const fs = format.readFeatures(text, { featureProjection: 'EPSG:3857' }); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(Point); - var expectedPoint = transform([2, 1], 'EPSG:4326', 'EPSG:3857'); + const expectedPoint = transform([2, 1], 'EPSG:4326', 'EPSG:3857'); expect(g.getCoordinates()).to.eql(expectedPoint); expect(g.getLayout()).to.be('XY'); - var serialized = format.writeFeaturesNode(fs, { + const serialized = format.writeFeaturesNode(fs, { featureProjection: 'EPSG:3857' }); expect(serialized).to.xmleql(_ol_xml_.parse(text)); }); it('can read and write a wpt with ele', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(3); }); it('can read features with a version 1.1 namespace', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(3); }); it('can read features with no namespace', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(3); }); @@ -593,15 +593,15 @@ describe('ol.format.GPX', function() { beforeEach(function() { format = new GPX({ readExtensions: function(feature, extensionsNode) { - var nodes = extensionsNode.getElementsByTagName('id'); - var id = nodes.item(0).textContent; + const nodes = extensionsNode.getElementsByTagName('id'); + const id = nodes.item(0).textContent; feature.setId(id); } }); }); it('can process extensions from wpt', function() { - var text = + const text = '' + ' ' + ' ' + @@ -609,14 +609,14 @@ describe('ol.format.GPX', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var feature = fs[0]; + const feature = fs[0]; expect(feature.getId()).to.be('feature-id'); }); it('can process extensions from rte', function() { - var text = + const text = '' + ' ' + ' ' + @@ -625,14 +625,14 @@ describe('ol.format.GPX', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var feature = fs[0]; + const feature = fs[0]; expect(feature.getId()).to.be('feature-id'); }); it('can process extensions from trk, not trkpt', function() { - var text = + const text = '' + ' ' + ' ' + @@ -647,9 +647,9 @@ describe('ol.format.GPX', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var feature = fs[0]; + const feature = fs[0]; expect(feature.getId()).to.be('feature-id'); }); @@ -661,12 +661,12 @@ describe('ol.format.GPX', function() { }); it('does not fail', function() { - var polygon = new Polygon( - [[[0, 0], [2, 2], [4, 0], [0, 0]]]); - var feature = new Feature(polygon); - var features = [feature]; - var gpx = format.writeFeaturesNode(features); - var expected = + const polygon = new Polygon( + [[[0, 0], [2, 2], [4, 0], [0, 0]]]); + const feature = new Feature(polygon); + const features = [feature]; + const gpx = format.writeFeaturesNode(features); + const expected = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); expect(style).to.be(dfltStyle); }); @@ -79,12 +79,12 @@ describe('ol.format.KML', function() { describe('#readProjection', function() { it('returns the default projection from document', function() { - var projection = format.readProjectionFromDocument(); + const projection = format.readProjectionFromDocument(); expect(projection).to.eql(getProjection('EPSG:4326')); }); it('returns the default projection from node', function() { - var projection = format.readProjectionFromNode(); + const projection = format.readProjectionFromNode(); expect(projection).to.eql(getProjection('EPSG:4326')); }); }); @@ -94,33 +94,33 @@ describe('ol.format.KML', function() { describe('id', function() { it('can read a Feature\'s id', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.getId()).to.be('foo'); }); it('treats a missing id as undefined', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.getId()).to.be(undefined); }); it('can write a Feature', function() { - var features = [new Feature()]; - var node = format.writeFeaturesNode(features); - var text = + const features = [new Feature()]; + const node = format.writeFeaturesNode(features); + const text = '' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be(null); }); it('can write feature with null geometries', function() { - var features = [new Feature(null)]; - var node = format.writeFeaturesNode(features); - var text = + const features = [new Feature(null)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(Point); expect(g.getCoordinates()).to.eql([1, 2, 3]); expect(g.get('extrude')).to.be(false); @@ -246,7 +246,7 @@ describe('ol.format.KML', function() { }); it('can transform and read Point geometries', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text, { + const fs = format.readFeatures(text, { featureProjection: 'EPSG:3857' }); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(Point); - var expectedPoint = transform([1, 2], 'EPSG:4326', 'EPSG:3857'); + const expectedPoint = transform([1, 2], 'EPSG:4326', 'EPSG:3857'); expectedPoint.push(3); expect(g.getCoordinates()).to.eql(expectedPoint); }); it('can read a single Point geometry', function() { - var text = + const text = '' + ' ' + ''; - var f = format.readFeature(text); + const f = format.readFeature(text); expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(Point); expect(g.getCoordinates()).to.eql([1, 2, 3]); }); it('can transform and read a single Point geometry', function() { - var text = + const text = '' + ' ' + ''; - var f = format.readFeature(text, { + const f = format.readFeature(text, { featureProjection: 'EPSG:3857' }); expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(Point); - var expectedPoint = transform([1, 2], 'EPSG:4326', 'EPSG:3857'); + const expectedPoint = transform([1, 2], 'EPSG:4326', 'EPSG:3857'); expectedPoint.push(3); expect(g.getCoordinates()).to.eql(expectedPoint); }); it('can write XY Point geometries', function() { - var layout = 'XY'; - var point = new Point([1, 2], layout); - var features = [new Feature(point)]; - var node = format.writeFeaturesNode(features); - var text = + const layout = 'XY'; + const point = new Point([1, 2], layout); + const features = [new Feature(point)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -442,11 +442,11 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(LineString); expect(g.getCoordinates()).to.eql([[1, 2, 3], [4, 5, 6]]); expect(g.get('extrude')).to.be(false); @@ -455,11 +455,11 @@ describe('ol.format.KML', function() { }); it('can write XY LineString geometries', function() { - var layout = 'XY'; - var lineString = new LineString([[1, 2], [3, 4]], layout); - var features = [new Feature(lineString)]; - var node = format.writeFeaturesNode(features); - var text = + const layout = 'XY'; + const lineString = new LineString([[1, 2], [3, 4]], layout); + const features = [new Feature(lineString)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -546,22 +546,22 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(Polygon); expect(g.getCoordinates()).to.eql([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]); }); it('can write XY LinearRing geometries', function() { - var layout = 'XY'; - var linearRing = new LinearRing( - [[1, 2], [3, 4], [1, 2]], layout); - var features = [new Feature(linearRing)]; - var node = format.writeFeaturesNode(features); - var text = + const layout = 'XY'; + const linearRing = new LinearRing( + [[1, 2], [3, 4], [1, 2]], layout); + const features = [new Feature(linearRing)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -654,25 +654,25 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(Polygon); expect(g.getCoordinates()).to.eql( - [[[0, 0, 1], [0, 5, 1], [5, 5, 2], [5, 0, 3]]]); + [[[0, 0, 1], [0, 5, 1], [5, 5, 2], [5, 0, 3]]]); expect(g.get('extrude')).to.be(false); expect(g.get('altitudeMode')).to.be('absolute'); }); it('can write XY Polygon geometries', function() { - var layout = 'XY'; - var polygon = new Polygon( - [[[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]], layout); - var features = [new Feature(polygon)]; - var node = format.writeFeaturesNode(features); - var text = + const layout = 'XY'; + const polygon = new Polygon( + [[[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]], layout); + const features = [new Feature(polygon)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -794,11 +794,11 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(Polygon); expect(g.getCoordinates()).to.eql([ [[0, 0, 1], [0, 5, 1], [5, 5, 2], [5, 0, 3]], @@ -808,15 +808,15 @@ describe('ol.format.KML', function() { }); it('can write complex Polygon geometries', function() { - var layout = 'XYZ'; - var polygon = new Polygon([ + const layout = 'XYZ'; + const polygon = new Polygon([ [[0, 0, 1], [0, 5, 1], [5, 5, 2], [5, 0, 3]], [[1, 1, 0], [1, 2, 0], [2, 2, 0], [2, 1, 0]], [[3, 3, 0], [3, 4, 0], [4, 4, 0], [4, 3, 0]] ], layout); - var features = [new Feature(polygon)]; - var node = format.writeFeaturesNode(features); - var text = + const features = [new Feature(polygon)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -869,15 +869,15 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(MultiPolygon); expect(g.getCoordinates()).to.eql( - [[[[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]]], - [[[3, 0, 0], [3, 1, 0], [4, 1, 0], [4, 0, 0]]]]); + [[[[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]]], + [[[3, 0, 0], [3, 1, 0], [4, 1, 0], [4, 0, 0]]]]); expect(g.get('extrude')).to.be.an('array'); expect(g.get('extrude')).to.have.length(2); expect(g.get('extrude')[0]).to.be(false); @@ -889,13 +889,13 @@ describe('ol.format.KML', function() { }); it('can write MultiPolygon geometries', function() { - var layout = 'XYZ'; - var multiPolygon = new MultiPolygon( - [[[[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]]], - [[[3, 0, 0], [3, 1, 0], [4, 1, 0], [4, 0, 0]]]], layout); - var features = [new Feature(multiPolygon)]; - var node = format.writeFeaturesNode(features); - var text = + const layout = 'XYZ'; + const multiPolygon = new MultiPolygon( + [[[[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]]], + [[[3, 0, 0], [3, 1, 0], [4, 1, 0], [4, 0, 0]]]], layout); + const features = [new Feature(multiPolygon)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -941,11 +941,11 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(MultiPoint); expect(g.getCoordinates()).to.eql([[1, 2, 3], [4, 5, 6]]); expect(g.get('extrude')).to.be.an('array'); @@ -959,12 +959,12 @@ describe('ol.format.KML', function() { }); it('can write MultiPoint geometries', function() { - var layout = 'XYZ'; - var multiPoint = new MultiPoint( - [[1, 2, 3], [4, 5, 6]], layout); - var features = [new Feature(multiPoint)]; - var node = format.writeFeaturesNode(features); - var text = + const layout = 'XYZ'; + const multiPoint = new MultiPoint( + [[1, 2, 3], [4, 5, 6]], layout); + const features = [new Feature(multiPoint)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -1001,14 +1001,14 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(MultiLineString); expect(g.getCoordinates()).to.eql( - [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]); + [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]); expect(g.get('extrude')).to.be.an('array'); expect(g.get('extrude')).to.have.length(2); expect(g.get('extrude')[0]).to.be(false); @@ -1024,12 +1024,12 @@ describe('ol.format.KML', function() { }); it('can write MultiLineString geometries', function() { - var layout = 'XYZ'; - var multiLineString = new MultiLineString( - [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], layout); - var features = [new Feature(multiLineString)]; - var node = format.writeFeaturesNode(features); - var text = + const layout = 'XYZ'; + const multiLineString = new MultiLineString( + [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], layout); + const features = [new Feature(multiLineString)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -1073,11 +1073,11 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(MultiPolygon); expect(g.getCoordinates()).to.eql([ [[[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]]], @@ -1094,14 +1094,14 @@ describe('ol.format.KML', function() { }); it('can write MultiPolygon geometries', function() { - var layout = 'XYZ'; - var multiPolygon = new MultiPolygon([ + const layout = 'XYZ'; + const multiPolygon = new MultiPolygon([ [[[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]]], [[[3, 0, 0], [3, 1, 0], [4, 1, 0], [4, 0, 0]]] ], layout); - var features = [new Feature(multiPolygon)]; - var node = format.writeFeaturesNode(features); - var text = + const features = [new Feature(multiPolygon)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(GeometryCollection); expect(g.getGeometries()).to.be.empty(); }); it('can read heterogeneous GeometryCollection geometries', function() { - var text = + const text = '' + ' ' + ' ' + @@ -1170,13 +1170,13 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(GeometryCollection); - var gs = g.getGeometries(); + const gs = g.getGeometries(); expect(gs).to.have.length(4); expect(gs[0]).to.be.an(Point); expect(gs[1]).to.be.an(LineString); @@ -1185,7 +1185,7 @@ describe('ol.format.KML', function() { }); it('can read nested GeometryCollection geometries', function() { - var text = + const text = '' + ' ' + ' ' + @@ -1194,26 +1194,26 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(GeometryCollection); - var gs = g.getGeometries(); + const gs = g.getGeometries(); expect(gs).to.have.length(1); expect(gs[0]).to.be.an(GeometryCollection); }); it('can write GeometryCollection geometries', function() { - var collection = new GeometryCollection([ + const collection = new GeometryCollection([ new Point([1, 2]), new LineString([[1, 2], [3, 4]]), new Polygon([[[1, 2], [3, 4], [3, 2], [1, 2]]]) ]); - var features = [new Feature(collection)]; - var node = format.writeFeaturesNode(features); - var text = + const features = [new Feature(collection)]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -1255,16 +1255,16 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(LineString); }); it('can read gx:MultiTrack', function() { - var text = + const text = '' + ' ' + @@ -1282,19 +1282,19 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var g = f.getGeometry(); + const g = f.getGeometry(); expect(g).to.be.an(MultiLineString); - var gs = g.getLineStrings(); + const gs = g.getLineStrings(); expect(gs).to.have.length(2); expect(gs[0]).to.be.an(LineString); }); it('can read dateTime', function() { - var text = + const text = '' + ' ' + @@ -1312,16 +1312,16 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); - var f = fs[0]; - var g = f.getGeometry(); - var flatCoordinates = g.flatCoordinates; + const fs = format.readFeatures(text); + const f = fs[0]; + const g = f.getGeometry(); + const flatCoordinates = g.flatCoordinates; expect(flatCoordinates[3]).to.be.eql(Date.UTC(2014, 0, 1, 0, 0, 0)); expect(flatCoordinates[7]).to.be.eql(Date.UTC(2014, 1, 1, 0, 0, 0)); expect(flatCoordinates[11]).to.be.eql(Date.UTC(2014, 1, 6, 0, 0, 0)); expect(flatCoordinates[15]).to.be.eql(Date.UTC(2014, 1, 6, 19, 39, 3)); expect(flatCoordinates[19]).to.be.eql( - Date.UTC(2014, 1, 6, 16, 39, 10) + Date.UTC(2014, 1, 6, 16, 39, 10) ); }); @@ -1330,23 +1330,23 @@ describe('ol.format.KML', function() { describe('attributes', function() { it('can read boolean attributes', function() { - var text = + const text = '' + ' ' + ' 1' + ' 0' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.get('open')).to.be(true); expect(f.get('visibility')).to.be(false); }); it('can read string attributes', function() { - var text = + const text = '' + ' ' + '
My address
' + @@ -1355,9 +1355,9 @@ describe('ol.format.KML', function() { ' My phone number' + '
' + '
'; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.get('address')).to.be('My address'); expect(f.get('description')).to.be('My description'); @@ -1366,56 +1366,56 @@ describe('ol.format.KML', function() { }); it('strips leading and trailing whitespace in strings', function() { - var text = + const text = '' + ' ' + ' \n\nMy description\n\n' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.get('description')).to.be('My description'); }); it('can read CDATA sections in strings', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.get('name')).to.be('My name in CDATA'); }); it('strips leading and trailing whitespace around CDATA', function() { - var text = + const text = '' + ' ' + ' \n\n\n\n' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.get('name')).to.be('My name in CDATA'); }); it('can write Feature\'s string attributes', function() { - var feature = new Feature(); + const feature = new Feature(); feature.set('address', 'My address'); feature.set('description', 'My description'); feature.set('name', 'My name'); feature.set('phoneNumber', 'My phone number'); - var features = [feature]; - var node = format.writeFeaturesNode(features); - var text = + const features = [feature]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -1474,11 +1474,11 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var extent = f.get('extent'); + const extent = f.get('extent'); expect(extent).to.be.an(Array); expect(extent).to.have.length(4); expect(extent[0]).to.be(1.384133); @@ -1491,7 +1491,7 @@ describe('ol.format.KML', function() { }); it('can read Lod', function() { - var text = + const text = '' + ' ' + ' ' + @@ -1506,9 +1506,9 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.get('minLodPixels')).to.be(128); expect(f.get('maxLodPixels')).to.be(2048); @@ -1521,12 +1521,12 @@ describe('ol.format.KML', function() { describe('extended data', function() { it('can write ExtendedData with no values', function() { - var feature = new Feature(); + const feature = new Feature(); feature.set('foo', null); feature.set('bar', undefined); - var features = [feature]; - var node = format.writeFeaturesNode(features); - var text = + const features = [feature]; + const node = format.writeFeaturesNode(features); + const text = '' + ' ' + @@ -1608,16 +1608,16 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.getProperties()).to.only.have.keys(['foo', 'geometry']); expect(f.get('foo')).to.be('bar'); }); it('can read ExtendedData with no values', function() { - var text = + const text = '' + ' ' + ' ' + @@ -1628,9 +1628,9 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.getProperties()).to.only.have.keys(['foo', 'bar', 'geometry']); expect(f.get('foo')).to.be('200'); @@ -1638,7 +1638,7 @@ describe('ol.format.KML', function() { }); it('can read ExtendedData with displayName instead of name', function() { - var text = + const text = '' + ' ' + ' ' + @@ -1649,15 +1649,15 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.get('foo')).to.be('bar'); }); it('can read SchemaData', function() { - var text = + const text = '' + ' ' + ' ' + @@ -1668,16 +1668,16 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.get('capital')).to.be('London'); expect(f.get('population')).to.be('60000000'); }); it('can read ExtendedData with displayName when name undefined', function() { - var text = + const text = '' + ' ' + ' ' + @@ -1692,9 +1692,9 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); expect(f.get('capital')).to.be('London'); expect(f.get('country')).to.be('United-Kingdom'); @@ -1704,21 +1704,21 @@ describe('ol.format.KML', function() { describe('styles', function() { it('applies the default style if no style is defined', function() { - var text = + const text = '' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); expect(style.getFill()).to.be(KML.DEFAULT_FILL_STYLE_); expect(style.getFill().getColor()).to.eql([255, 255, 255, 1]); @@ -1730,7 +1730,7 @@ describe('ol.format.KML', function() { }); it('can read a feature\'s IconStyle', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); expect(style.getFill()).to.be(KML.DEFAULT_FILL_STYLE_); expect(style.getStroke()).to.be(KML.DEFAULT_STROKE_STYLE_); - var imageStyle = style.getImage(); + const imageStyle = style.getImage(); expect(imageStyle).to.be.an(Icon); expect(new URL(imageStyle.getSrc()).href).to.eql(new URL('http://foo.png').href); expect(imageStyle.getAnchor()).to.be(null); @@ -1768,7 +1768,7 @@ describe('ol.format.KML', function() { }); it('can read a IconStyle\'s hotspot', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(5); fs.forEach(function(f) { expect(f).to.be.an(Feature); expect(f.getId()).to.be.within(1, 5); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); expect(style.getFill()).to.be(KML.DEFAULT_FILL_STYLE_); expect(style.getStroke()).to.be(KML.DEFAULT_STROKE_STYLE_); - var imageStyle = style.getImage(); + const imageStyle = style.getImage(); expect(imageStyle).to.be.an(Icon); expect(new URL(imageStyle.getSrc()).href).to.eql(new URL('http://foo.png').href); expect(imageStyle.anchor_).to.be.an(Array); @@ -1873,7 +1873,7 @@ describe('ol.format.KML', function() { }); it('can read a complex feature\'s IconStyle', function() { - var text = + const text = '' + ' ' + @@ -1893,20 +1893,20 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); expect(style.getFill()).to.be(KML.DEFAULT_FILL_STYLE_); expect(style.getStroke()).to.be(KML.DEFAULT_STROKE_STYLE_); - var imageStyle = style.getImage(); + const imageStyle = style.getImage(); imageStyle.iconImage_.size_ = [144, 192]; expect(imageStyle.getSize()).to.eql([48, 48]); expect(imageStyle.getAnchor()).to.eql([24, 36]); @@ -1918,7 +1918,7 @@ describe('ol.format.KML', function() { }); it('can read a feature\'s LabelStyle', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); expect(style.getFill()).to.be(KML.DEFAULT_FILL_STYLE_); expect(style.getImage()).to.be(KML.DEFAULT_IMAGE_STYLE_); expect(style.getStroke()).to.be(KML.DEFAULT_STROKE_STYLE_); - var textStyle = style.getText(); + const textStyle = style.getText(); expect(textStyle).to.be.an(Text); expect(textStyle.getScale()).to.be(0.25); - var textFillStyle = textStyle.getFill(); + const textFillStyle = textStyle.getFill(); expect(textFillStyle).to.be.an(Fill); expect(textFillStyle.getColor()).to.eql([0x78, 0x56, 0x34, 0x12 / 255]); expect(style.getZIndex()).to.be(undefined); }); it('can read a feature\'s LineStyle', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); expect(style.getFill()).to.be(KML.DEFAULT_FILL_STYLE_); expect(style.getImage()).to.be(KML.DEFAULT_IMAGE_STYLE_); - var strokeStyle = style.getStroke(); + const strokeStyle = style.getStroke(); expect(strokeStyle).to.be.an(Stroke); expect(strokeStyle.getColor()).to.eql([0x78, 0x56, 0x34, 0x12 / 255]); expect(strokeStyle.getWidth()).to.be(9); @@ -1986,7 +1986,7 @@ describe('ol.format.KML', function() { }); it('can read a feature\'s PolyStyle', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); - var fillStyle = style.getFill(); + const fillStyle = style.getFill(); expect(fillStyle).to.be.an(Fill); expect(fillStyle.getColor()).to.eql([0x78, 0x56, 0x34, 0x12 / 255]); expect(style.getImage()).to.be(KML.DEFAULT_IMAGE_STYLE_); @@ -2017,7 +2017,7 @@ describe('ol.format.KML', function() { }); it('can read a feature\'s LineStyle and PolyStyle', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); - var fillStyle = style.getFill(); + const fillStyle = style.getFill(); expect(fillStyle).to.be.an(Fill); expect(fillStyle.getColor()).to.eql([0x78, 0x56, 0x34, 0x12 / 255]); expect(style.getImage()).to.be(KML.DEFAULT_IMAGE_STYLE_); - var strokeStyle = style.getStroke(); + const strokeStyle = style.getStroke(); expect(strokeStyle).to.be.an(Stroke); expect(strokeStyle.getColor()).to.eql([0x78, 0x56, 0x34, 0x12 / 255]); expect(strokeStyle.getWidth()).to.be(9); @@ -2057,7 +2057,7 @@ describe('ol.format.KML', function() { }); it('disables the fill when fill is \'0\'', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); expect(style.getFill()).to.be(null); expect(style.getImage()).to.be(KML.DEFAULT_IMAGE_STYLE_); - var strokeStyle = style.getStroke(); + const strokeStyle = style.getStroke(); expect(strokeStyle).to.be.an(Stroke); expect(strokeStyle.getColor()).to.eql([0x78, 0x56, 0x34, 0x12 / 255]); expect(strokeStyle.getWidth()).to.be(9); @@ -2094,7 +2094,7 @@ describe('ol.format.KML', function() { }); it('disables the stroke when outline is \'0\'', function() { - var text = + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var style = styleArray[0]; + const style = styleArray[0]; expect(style).to.be.an(Style); - var fillStyle = style.getFill(); + const fillStyle = style.getFill(); expect(fillStyle).to.be.an(Fill); expect(fillStyle.getColor()).to.eql([0x78, 0x56, 0x34, 0x12 / 255]); expect(style.getImage()).to.be(KML.DEFAULT_IMAGE_STYLE_); @@ -2130,8 +2130,8 @@ describe('ol.format.KML', function() { }); it('disables both fill and stroke when fill and outline are \'0\'', - function() { - var text = + function() { + const text = '' + ' ' + ' ' + ' ' + ''; - var fs = format.readFeatures(text); - expect(fs).to.have.length(1); - var f = fs[0]; - expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); - expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); - expect(styleArray).to.be.an(Array); - expect(styleArray).to.have.length(1); - var style = styleArray[0]; - expect(style).to.be.an(Style); - expect(style.getFill()).to.be(null); - expect(style.getImage()).to.be(KML.DEFAULT_IMAGE_STYLE_); - expect(style.getStroke()).to.be(null); - expect(style.getText()).to.be(KML.DEFAULT_TEXT_STYLE_); - expect(style.getZIndex()).to.be(undefined); - }); + const fs = format.readFeatures(text); + expect(fs).to.have.length(1); + const f = fs[0]; + expect(f).to.be.an(Feature); + const styleFunction = f.getStyleFunction(); + expect(styleFunction).not.to.be(undefined); + const styleArray = styleFunction.call(f, 0); + expect(styleArray).to.be.an(Array); + expect(styleArray).to.have.length(1); + const style = styleArray[0]; + expect(style).to.be.an(Style); + expect(style.getFill()).to.be(null); + expect(style.getImage()).to.be(KML.DEFAULT_IMAGE_STYLE_); + expect(style.getStroke()).to.be(null); + expect(style.getText()).to.be(KML.DEFAULT_TEXT_STYLE_); + expect(style.getZIndex()).to.be(undefined); + }); it('can create text style for named point placemarks', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(2); - var style = styleArray[1]; + const style = styleArray[1]; expect(style).to.be.an(Style); expect(style.getText().getText()).to.eql(f.getProperties()['name']); }); it('can create text style for named point placemarks', function() { - var text = + const text = '' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(2); - var style = styleArray[1]; + const style = styleArray[1]; expect(style).to.be.an(Style); expect(style.getText().getText()).to.eql(f.getProperties()['name']); }); it('can write an feature\'s icon style', function() { - var style = new Style({ + const style = new Style({ image: new Icon({ anchor: [0.25, 36], anchorOrigin: 'top-left', @@ -2279,12 +2279,12 @@ describe('ol.format.KML', function() { src: 'http://foo.png' }) }); - var imageStyle = style.getImage(); + const imageStyle = style.getImage(); imageStyle.iconImage_.size_ = [192, 144]; // sprite de 12 images(4*3) - var feature = new Feature(); + const feature = new Feature(); feature.setStyle([style]); - var node = format.writeFeaturesNode([feature]); - var text = + const node = format.writeFeaturesNode([feature]); + const text = '' + ' ' + @@ -2503,23 +2503,23 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var s = styleArray[0]; + const s = styleArray[0]; expect(s).to.be.an(Style); expect(s.getFill()).not.to.be(null); expect(s.getFill().getColor()).to.eql([0, 0, 0, 0]); }); it('ignores highlight styles', function() { - var text = + const text = '' + ' ' + ' ' + @@ -2536,23 +2536,23 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var s = styleArray[0]; + const s = styleArray[0]; expect(s).to.be.an(Style); expect(s).to.be(KML.DEFAULT_STYLE_); }); it('uses normal styles instead of highlight styles', function() { - var text = + const text = '' + ' ' + ' ' + @@ -2577,23 +2577,23 @@ describe('ol.format.KML', function() { ' ' + ' ' + ''; - var fs = format.readFeatures(text); + const fs = format.readFeatures(text); expect(fs).to.have.length(1); - var f = fs[0]; + const f = fs[0]; expect(f).to.be.an(Feature); - var styleFunction = f.getStyleFunction(); + const styleFunction = f.getStyleFunction(); expect(styleFunction).not.to.be(undefined); - var styleArray = styleFunction.call(f, 0); + const styleArray = styleFunction.call(f, 0); expect(styleArray).to.be.an(Array); expect(styleArray).to.have.length(1); - var s = styleArray[0]; + const s = styleArray[0]; expect(s).to.be.an(Style); expect(s.getFill()).not.to.be(null); expect(s.getFill().getColor()).to.eql([0, 0, 0, 0]); }); it('can read normal styleUrls', function() { - var text = + const text = '' + ' ' + '