Merge pull request #7697 from tschaub/lint

Use const and let
This commit is contained in:
Tim Schaub
2018-01-12 08:08:38 -07:00
committed by GitHub
684 changed files with 18121 additions and 18184 deletions

View File

@@ -5,7 +5,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -24,13 +24,13 @@ var map = new Map({
}); });
document.getElementById('zoom-out').onclick = function() { document.getElementById('zoom-out').onclick = function() {
var view = map.getView(); const view = map.getView();
var zoom = view.getZoom(); const zoom = view.getZoom();
view.setZoom(zoom - 1); view.setZoom(zoom - 1);
}; };
document.getElementById('zoom-in').onclick = function() { document.getElementById('zoom-in').onclick = function() {
var view = map.getView(); const view = map.getView();
var zoom = view.getZoom(); const zoom = view.getZoom();
view.setZoom(zoom + 1); view.setZoom(zoom + 1);
}; };

View File

@@ -5,18 +5,18 @@ import TileLayer from '../src/ol/layer/Tile.js';
import {fromLonLat} from '../src/ol/proj.js'; import {fromLonLat} from '../src/ol/proj.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var london = fromLonLat([-0.12755, 51.507222]); const london = fromLonLat([-0.12755, 51.507222]);
var moscow = fromLonLat([37.6178, 55.7517]); const moscow = fromLonLat([37.6178, 55.7517]);
var istanbul = fromLonLat([28.9744, 41.0128]); const istanbul = fromLonLat([28.9744, 41.0128]);
var rome = fromLonLat([12.5, 41.9]); const rome = fromLonLat([12.5, 41.9]);
var bern = fromLonLat([7.4458, 46.95]); const bern = fromLonLat([7.4458, 46.95]);
var view = new View({ const view = new View({
center: istanbul, center: istanbul,
zoom: 6 zoom: 6
}); });
var map = new Map({ const map = new Map({
target: 'map', target: 'map',
layers: [ layers: [
new TileLayer({ new TileLayer({
@@ -32,7 +32,9 @@ var map = new Map({
// A bounce easing method (from https://github.com/DmitryBaranovskiy/raphael). // A bounce easing method (from https://github.com/DmitryBaranovskiy/raphael).
function bounce(t) { 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)) { if (t < (1 / p)) {
l = s * t * t; l = s * t * t;
} else { } else {
@@ -75,7 +77,7 @@ onClick('rotate-right', function() {
onClick('rotate-around-rome', function() { onClick('rotate-around-rome', function() {
// Rotation animation takes the shortest arc, so animate in two parts // Rotation animation takes the shortest arc, so animate in two parts
var rotation = view.getRotation(); const rotation = view.getRotation();
view.animate({ view.animate({
rotation: rotation + Math.PI, rotation: rotation + Math.PI,
anchor: rome, anchor: rome,
@@ -112,7 +114,7 @@ onClick('bounce-to-istanbul', function() {
onClick('spin-to-rome', function() { onClick('spin-to-rome', function() {
// Rotation animation takes the shortest arc, so animate in two parts // Rotation animation takes the shortest arc, so animate in two parts
var center = view.getCenter(); const center = view.getCenter();
view.animate({ view.animate({
center: [ center: [
center[0] + (rome[0] - center[0]) / 2, center[0] + (rome[0] - center[0]) / 2,
@@ -128,10 +130,10 @@ onClick('spin-to-rome', function() {
}); });
function flyTo(location, done) { function flyTo(location, done) {
var duration = 2000; const duration = 2000;
var zoom = view.getZoom(); const zoom = view.getZoom();
var parts = 2; let parts = 2;
var called = false; let called = false;
function callback(complete) { function callback(complete) {
--parts; --parts;
if (called) { if (called) {
@@ -160,13 +162,13 @@ onClick('fly-to-bern', function() {
}); });
function tour() { function tour() {
var locations = [london, bern, rome, moscow, istanbul]; const locations = [london, bern, rome, moscow, istanbul];
var index = -1; let index = -1;
function next(more) { function next(more) {
if (more) { if (more) {
++index; ++index;
if (index < locations.length) { if (index < locations.length) {
var delay = index === 0 ? 0 : 750; const delay = index === 0 ? 0 : 750;
setTimeout(function() { setTimeout(function() {
flyTo(locations[index], next); flyTo(locations[index], next);
}, delay); }, delay);

View File

@@ -5,10 +5,10 @@ import ImageLayer from '../src/ol/layer/Image.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import ImageArcGISRest from '../src/ol/source/ImageArcGISRest.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'; 'Specialty/ESRI_StateCityHighway_USA/MapServer';
var layers = [ const layers = [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
}), }),
@@ -20,7 +20,7 @@ var layers = [
}) })
}) })
]; ];
var map = new Map({ const map = new Map({
layers: layers, layers: layers,
target: 'map', target: 'map',
view: new View({ view: new View({

View File

@@ -4,10 +4,10 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import TileArcGISRest from '../src/ol/source/TileArcGISRest.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'; 'Specialty/ESRI_StateCityHighway_USA/MapServer';
var layers = [ const layers = [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
}), }),
@@ -18,7 +18,7 @@ var layers = [
}) })
}) })
]; ];
var map = new Map({ const map = new Map({
layers: layers, layers: layers,
target: 'map', target: 'map',
view: new View({ view: new View({

View File

@@ -5,10 +5,10 @@ import Attribution from '../src/ol/control/Attribution.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var attribution = new Attribution({ const attribution = new Attribution({
collapsible: false collapsible: false
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -23,7 +23,7 @@ var map = new Map({
}); });
function checkSize() { function checkSize() {
var small = map.getSize()[0] < 600; const small = map.getSize()[0] < 600;
attribution.setCollapsible(small); attribution.setCollapsible(small);
attribution.setCollapsed(small); attribution.setCollapsed(small);
} }

View File

@@ -4,7 +4,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import BingMaps from '../src/ol/source/BingMaps.js'; import BingMaps from '../src/ol/source/BingMaps.js';
var styles = [ const styles = [
'Road', 'Road',
'RoadOnDemand', 'RoadOnDemand',
'Aerial', 'Aerial',
@@ -12,8 +12,8 @@ var styles = [
'collinsBart', 'collinsBart',
'ordnanceSurvey' 'ordnanceSurvey'
]; ];
var layers = []; const layers = [];
var i, ii; let i, ii;
for (i = 0, ii = styles.length; i < ii; ++i) { for (i = 0, ii = styles.length; i < ii; ++i) {
layers.push(new TileLayer({ layers.push(new TileLayer({
visible: false, 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, layers: layers,
// Improve user experience by loading tiles while dragging/zooming. Will make // Improve user experience by loading tiles while dragging/zooming. Will make
// zooming choppy on mobile or slow devices. // 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() { function onChange() {
var style = select.value; const style = select.value;
for (var i = 0, ii = layers.length; i < ii; ++i) { for (let i = 0, ii = layers.length; i < ii; ++i) {
layers[i].setVisible(styles[i] === style); layers[i].setVisible(styles[i] === style);
} }
} }

View File

@@ -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 // 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 // features form the corners of an equilateral triangle and their styles overlap
var redLayer = new VectorLayer({ const redLayer = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
features: [new Feature(new Point([0, 0]))] 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({ source: new VectorSource({
// 433.013 is roughly 250 * Math.sqrt(3) // 433.013 is roughly 250 * Math.sqrt(3)
features: [new Feature(new Point([250, 433.013]))] 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({ source: new VectorSource({
features: [new Feature(new Point([500, 0]))] 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 // Create the map, the view is centered on the triangle. Zooming and panning is
// restricted to a sane area // restricted to a sane area
var map = new Map({ const map = new Map({
layers: [ layers: [
redLayer, redLayer,
greenLayer, greenLayer,
@@ -86,10 +86,10 @@ var map = new Map({
}); });
// Get the form elements and bind the listeners // Get the form elements and bind the listeners
var select = document.getElementById('blend-mode'); const select = document.getElementById('blend-mode');
var affectRed = document.getElementById('affect-red'); const affectRed = document.getElementById('affect-red');
var affectGreen = document.getElementById('affect-green'); const affectGreen = document.getElementById('affect-green');
var affectBlue = document.getElementById('affect-blue'); const affectBlue = document.getElementById('affect-blue');
/** /**
@@ -98,7 +98,7 @@ var affectBlue = document.getElementById('affect-blue');
* *
* @param {ol.render.Event} evt The render event. * @param {ol.render.Event} evt The render event.
*/ */
var setBlendModeFromSelect = function(evt) { const setBlendModeFromSelect = function(evt) {
evt.context.globalCompositeOperation = select.value; evt.context.globalCompositeOperation = select.value;
}; };
@@ -109,7 +109,7 @@ var setBlendModeFromSelect = function(evt) {
* *
* @param {ol.render.Event} evt The render event. * @param {ol.render.Event} evt The render event.
*/ */
var resetBlendModeFromSelect = function(evt) { const resetBlendModeFromSelect = function(evt) {
evt.context.globalCompositeOperation = 'source-over'; 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. * @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('precompose', setBlendModeFromSelect);
layer.on('postcompose', resetBlendModeFromSelect); layer.on('postcompose', resetBlendModeFromSelect);
}; };
@@ -130,7 +130,7 @@ var bindLayerListeners = function(layer) {
* *
* @param {ol.layer.Vector} layer The layer to unbind the handlers from. * @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('precompose', setBlendModeFromSelect);
layer.un('postcompose', resetBlendModeFromSelect); layer.un('postcompose', resetBlendModeFromSelect);
}; };
@@ -141,8 +141,8 @@ var unbindLayerListeners = function(layer) {
* *
* @this {HTMLInputElement} * @this {HTMLInputElement}
*/ */
var affectLayerClicked = function() { const affectLayerClicked = function() {
var layer; let layer;
if (this.id == 'affect-red') { if (this.id == 'affect-red') {
layer = redLayer; layer = redLayer;
} else if (this.id == 'affect-green') { } else if (this.id == 'affect-green') {

View File

@@ -10,13 +10,13 @@ import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var vectorSource = new VectorSource({ const vectorSource = new VectorSource({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new GeoJSON()
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -33,13 +33,13 @@ var map = new Map({
}); });
// a normal select interaction to handle click // a normal select interaction to handle click
var select = new Select(); const select = new Select();
map.addInteraction(select); map.addInteraction(select);
var selectedFeatures = select.getFeatures(); const selectedFeatures = select.getFeatures();
// a DragBox interaction used to select features by drawing boxes // a DragBox interaction used to select features by drawing boxes
var dragBox = new DragBox({ const dragBox = new DragBox({
condition: _ol_events_condition_.platformModifierKeyOnly condition: _ol_events_condition_.platformModifierKeyOnly
}); });
@@ -48,7 +48,7 @@ map.addInteraction(dragBox);
dragBox.on('boxend', function() { dragBox.on('boxend', function() {
// features that intersect the box are added to the collection of // features that intersect the box are added to the collection of
// selected features // selected features
var extent = dragBox.getGeometry().getExtent(); const extent = dragBox.getGeometry().getExtent();
vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) { vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {
selectedFeatures.push(feature); selectedFeatures.push(feature);
}); });
@@ -59,10 +59,10 @@ dragBox.on('boxstart', function() {
selectedFeatures.clear(); selectedFeatures.clear();
}); });
var infoBox = document.getElementById('info'); const infoBox = document.getElementById('info');
selectedFeatures.on(['add', 'remove'], function() { selectedFeatures.on(['add', 'remove'], function() {
var names = selectedFeatures.getArray().map(function(feature) { const names = selectedFeatures.getArray().map(function(feature) {
return feature.get('name'); return feature.get('name');
}); });
if (names.length > 0) { if (names.length > 0) {

View File

@@ -3,7 +3,7 @@ import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()

View File

@@ -10,22 +10,22 @@ import Fill from '../src/ol/style/Fill.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
var context = canvas.getContext('2d'); const context = canvas.getContext('2d');
// Gradient and pattern are in canvas pixel space, so we adjust for the // Gradient and pattern are in canvas pixel space, so we adjust for the
// renderer's pixel ratio // renderer's pixel ratio
var pixelRatio = _ol_has_.DEVICE_PIXEL_RATIO; const pixelRatio = _ol_has_.DEVICE_PIXEL_RATIO;
// Generate a rainbow gradient // Generate a rainbow gradient
function gradient(feature, resolution) { 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. // 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 // 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 // we just divide the geometry's extent width by resolution and multiply with
// pixelRatio to match the renderer's pixel coordinate system. // pixelRatio to match the renderer's pixel coordinate system.
var grad = context.createLinearGradient(0, 0, const grad = context.createLinearGradient(0, 0,
_ol_extent_.getWidth(extent) / resolution * pixelRatio, 0); _ol_extent_.getWidth(extent) / resolution * pixelRatio, 0);
grad.addColorStop(0, 'red'); grad.addColorStop(0, 'red');
grad.addColorStop(1 / 6, 'orange'); grad.addColorStop(1 / 6, 'orange');
grad.addColorStop(2 / 6, 'yellow'); grad.addColorStop(2 / 6, 'yellow');
@@ -37,7 +37,7 @@ function gradient(feature, resolution) {
} }
// Generate a canvasPattern with two circles on white background // Generate a canvasPattern with two circles on white background
var pattern = (function() { const pattern = (function() {
canvas.width = 11 * pixelRatio; canvas.width = 11 * pixelRatio;
canvas.height = 11 * pixelRatio; canvas.height = 11 * pixelRatio;
// white background // white background
@@ -57,8 +57,8 @@ var pattern = (function() {
}()); }());
// Generate style for gradient or pattern fill // Generate style for gradient or pattern fill
var fill = new Fill(); const fill = new Fill();
var style = new Style({ const style = new Style({
fill: fill, fill: fill,
stroke: new Stroke({ stroke: new Stroke({
color: '#333', color: '#333',
@@ -74,14 +74,14 @@ var style = new Style({
* @param {number} resolution Resolution. * @param {number} resolution Resolution.
* @return {ol.style.Style} The style to use for the feature. * @return {ol.style.Style} The style to use for the feature.
*/ */
var getStackedStyle = function(feature, resolution) { const getStackedStyle = function(feature, resolution) {
var id = feature.getId(); const id = feature.getId();
fill.setColor(id > 'J' ? gradient(feature, resolution) : pattern); fill.setColor(id > 'J' ? gradient(feature, resolution) : pattern);
return style; return style;
}; };
// Create a vector layer that makes use of the style function above… // Create a vector layer that makes use of the style function above…
var vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new GeoJSON()
@@ -90,7 +90,7 @@ var vectorLayer = new VectorLayer({
}); });
// … finally create a map with that layer. // … finally create a map with that layer.
var map = new Map({ const map = new Map({
layers: [ layers: [
vectorLayer vectorLayer
], ],

View File

@@ -7,8 +7,8 @@ import OSM from '../src/ol/source/OSM.js';
import TileDebug from '../src/ol/source/TileDebug.js'; import TileDebug from '../src/ol/source/TileDebug.js';
var osmSource = new OSM(); const osmSource = new OSM();
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: osmSource source: osmSource

View File

@@ -4,7 +4,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import CartoDB from '../src/ol/source/CartoDB.js'; import CartoDB from '../src/ol/source/CartoDB.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var mapConfig = { const mapConfig = {
'layers': [{ 'layers': [{
'type': 'cartodb', 'type': 'cartodb',
'options': { 'options': {
@@ -15,12 +15,12 @@ var mapConfig = {
}] }]
}; };
var cartoDBSource = new CartoDB({ const cartoDBSource = new CartoDB({
account: 'documentation', account: 'documentation',
config: mapConfig config: mapConfig
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()

View File

@@ -11,11 +11,11 @@ import Fill from '../src/ol/style/Fill.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var source = new VectorSource({ const source = new VectorSource({
url: 'data/geojson/switzerland.geojson', url: 'data/geojson/switzerland.geojson',
format: new GeoJSON() format: new GeoJSON()
}); });
var style = new Style({ const style = new Style({
fill: new Fill({ fill: new Fill({
color: 'rgba(255, 255, 255, 0.6)' 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, source: source,
style: style style: style
}); });
var view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -58,40 +58,40 @@ var map = new Map({
view: view view: view
}); });
var zoomtoswitzerlandbest = document.getElementById('zoomtoswitzerlandbest'); const zoomtoswitzerlandbest = document.getElementById('zoomtoswitzerlandbest');
zoomtoswitzerlandbest.addEventListener('click', function() { zoomtoswitzerlandbest.addEventListener('click', function() {
var feature = source.getFeatures()[0]; const feature = source.getFeatures()[0];
var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); const polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
view.fit(polygon, {padding: [170, 50, 30, 150], constrainResolution: false}); view.fit(polygon, {padding: [170, 50, 30, 150], constrainResolution: false});
}, false); }, false);
var zoomtoswitzerlandconstrained = const zoomtoswitzerlandconstrained =
document.getElementById('zoomtoswitzerlandconstrained'); document.getElementById('zoomtoswitzerlandconstrained');
zoomtoswitzerlandconstrained.addEventListener('click', function() { zoomtoswitzerlandconstrained.addEventListener('click', function() {
var feature = source.getFeatures()[0]; const feature = source.getFeatures()[0];
var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); const polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
view.fit(polygon, {padding: [170, 50, 30, 150]}); view.fit(polygon, {padding: [170, 50, 30, 150]});
}, false); }, false);
var zoomtoswitzerlandnearest = const zoomtoswitzerlandnearest =
document.getElementById('zoomtoswitzerlandnearest'); document.getElementById('zoomtoswitzerlandnearest');
zoomtoswitzerlandnearest.addEventListener('click', function() { zoomtoswitzerlandnearest.addEventListener('click', function() {
var feature = source.getFeatures()[0]; const feature = source.getFeatures()[0];
var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); const polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
view.fit(polygon, {padding: [170, 50, 30, 150], nearest: true}); view.fit(polygon, {padding: [170, 50, 30, 150], nearest: true});
}, false); }, false);
var zoomtolausanne = document.getElementById('zoomtolausanne'); const zoomtolausanne = document.getElementById('zoomtolausanne');
zoomtolausanne.addEventListener('click', function() { zoomtolausanne.addEventListener('click', function() {
var feature = source.getFeatures()[1]; const feature = source.getFeatures()[1];
var point = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry()); const point = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
view.fit(point, {padding: [170, 50, 30, 150], minResolution: 50}); view.fit(point, {padding: [170, 50, 30, 150], minResolution: 50});
}, false); }, false);
var centerlausanne = document.getElementById('centerlausanne'); const centerlausanne = document.getElementById('centerlausanne');
centerlausanne.addEventListener('click', function() { centerlausanne.addEventListener('click', function() {
var feature = source.getFeatures()[1]; const feature = source.getFeatures()[1];
var point = /** @type {ol.geom.Point} */ (feature.getGeometry()); const point = /** @type {ol.geom.Point} */ (feature.getGeometry());
var size = /** @type {ol.Size} */ (map.getSize()); const size = /** @type {ol.Size} */ (map.getSize());
view.centerOn(point.getCoordinates(), size, [570, 500]); view.centerOn(point.getCoordinates(), size, [570, 500]);
}, false); }, false);

View File

@@ -14,31 +14,31 @@ import Style from '../src/ol/style/Style.js';
import Text from '../src/ol/style/Text.js'; import Text from '../src/ol/style/Text.js';
var distance = document.getElementById('distance'); const distance = document.getElementById('distance');
var count = 20000; const count = 20000;
var features = new Array(count); const features = new Array(count);
var e = 4500000; const e = 4500000;
for (var i = 0; i < count; ++i) { for (let i = 0; i < count; ++i) {
var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; const coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
features[i] = new Feature(new Point(coordinates)); features[i] = new Feature(new Point(coordinates));
} }
var source = new VectorSource({ const source = new VectorSource({
features: features features: features
}); });
var clusterSource = new Cluster({ const clusterSource = new Cluster({
distance: parseInt(distance.value, 10), distance: parseInt(distance.value, 10),
source: source source: source
}); });
var styleCache = {}; const styleCache = {};
var clusters = new VectorLayer({ const clusters = new VectorLayer({
source: clusterSource, source: clusterSource,
style: function(feature) { style: function(feature) {
var size = feature.get('features').length; const size = feature.get('features').length;
var style = styleCache[size]; let style = styleCache[size];
if (!style) { if (!style) {
style = new Style({ style = new Style({
image: new CircleStyle({ image: new CircleStyle({
@@ -63,11 +63,11 @@ var clusters = new VectorLayer({
} }
}); });
var raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM()
}); });
var map = new Map({ const map = new Map({
layers: [raster, clusters], layers: [raster, clusters],
target: 'map', target: 'map',
view: new View({ view: new View({

View File

@@ -10,14 +10,14 @@ import Stamen from '../src/ol/source/Stamen.js';
* Color manipulation functions below are adapted from * Color manipulation functions below are adapted from
* https://github.com/d3/d3-color. * https://github.com/d3/d3-color.
*/ */
var Xn = 0.950470; const Xn = 0.950470;
var Yn = 1; const Yn = 1;
var Zn = 1.088830; const Zn = 1.088830;
var t0 = 4 / 29; const t0 = 4 / 29;
var t1 = 6 / 29; const t1 = 6 / 29;
var t2 = 3 * t1 * t1; const t2 = 3 * t1 * t1;
var t3 = t1 * t1 * t1; const t3 = t1 * t1 * t1;
var twoPi = 2 * Math.PI; const twoPi = 2 * Math.PI;
/** /**
@@ -26,23 +26,23 @@ var twoPi = 2 * Math.PI;
* @return {Array.<number>} A pixel in HCL space. * @return {Array.<number>} A pixel in HCL space.
*/ */
function rgb2hcl(pixel) { function rgb2hcl(pixel) {
var red = rgb2xyz(pixel[0]); const red = rgb2xyz(pixel[0]);
var green = rgb2xyz(pixel[1]); const green = rgb2xyz(pixel[1]);
var blue = rgb2xyz(pixel[2]); const blue = rgb2xyz(pixel[2]);
var x = xyz2lab( const x = xyz2lab(
(0.4124564 * red + 0.3575761 * green + 0.1804375 * blue) / Xn); (0.4124564 * red + 0.3575761 * green + 0.1804375 * blue) / Xn);
var y = xyz2lab( const y = xyz2lab(
(0.2126729 * red + 0.7151522 * green + 0.0721750 * blue) / Yn); (0.2126729 * red + 0.7151522 * green + 0.0721750 * blue) / Yn);
var z = xyz2lab( const z = xyz2lab(
(0.0193339 * red + 0.1191920 * green + 0.9503041 * blue) / Zn); (0.0193339 * red + 0.1191920 * green + 0.9503041 * blue) / Zn);
var l = 116 * y - 16; const l = 116 * y - 16;
var a = 500 * (x - y); const a = 500 * (x - y);
var b = 200 * (y - z); const b = 200 * (y - z);
var c = Math.sqrt(a * a + b * b); const c = Math.sqrt(a * a + b * b);
var h = Math.atan2(b, a); let h = Math.atan2(b, a);
if (h < 0) { if (h < 0) {
h += twoPi; h += twoPi;
} }
@@ -61,16 +61,16 @@ function rgb2hcl(pixel) {
* @return {Array.<number>} A pixel in RGB space. * @return {Array.<number>} A pixel in RGB space.
*/ */
function hcl2rgb(pixel) { function hcl2rgb(pixel) {
var h = pixel[0]; const h = pixel[0];
var c = pixel[1]; const c = pixel[1];
var l = pixel[2]; const l = pixel[2];
var a = Math.cos(h) * c; const a = Math.cos(h) * c;
var b = Math.sin(h) * c; const b = Math.sin(h) * c;
var y = (l + 16) / 116; let y = (l + 16) / 116;
var x = isNaN(a) ? y : y + a / 500; let x = isNaN(a) ? y : y + a / 500;
var z = isNaN(b) ? y : y - b / 200; let z = isNaN(b) ? y : y - b / 200;
y = Yn * lab2xyz(y); y = Yn * lab2xyz(y);
x = Xn * lab2xyz(x); x = Xn * lab2xyz(x);
@@ -100,15 +100,15 @@ function xyz2rgb(x) {
12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
} }
var raster = new RasterSource({ const raster = new RasterSource({
sources: [new Stamen({ sources: [new Stamen({
layer: 'watercolor', layer: 'watercolor',
transition: 0 transition: 0
})], })],
operation: function(pixels, data) { 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) { if (h < 0) {
h += twoPi; h += twoPi;
} else if (h > twoPi) { } else if (h > twoPi) {
@@ -139,16 +139,16 @@ var raster = new RasterSource({
} }
}); });
var controls = {}; const controls = {};
raster.on('beforeoperations', function(event) { raster.on('beforeoperations', function(event) {
var data = event.data; const data = event.data;
for (var id in controls) { for (const id in controls) {
data[id] = Number(controls[id].value); data[id] = Number(controls[id].value);
} }
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new ImageLayer({ new ImageLayer({
source: raster source: raster
@@ -162,10 +162,10 @@ var map = new Map({
}) })
}); });
var controlIds = ['hue', 'chroma', 'lightness']; const controlIds = ['hue', 'chroma', 'lightness'];
controlIds.forEach(function(id) { controlIds.forEach(function(id) {
var control = document.getElementById(id); const control = document.getElementById(id);
var output = document.getElementById(id + 'Out'); const output = document.getElementById(id + 'Out');
control.addEventListener('input', function() { control.addEventListener('input', function() {
output.innerText = control.value; output.innerText = control.value;
raster.changed(); raster.changed();

View File

@@ -11,7 +11,7 @@ import OSM from '../src/ol/source/OSM.js';
* Define a namespace for the application. * Define a namespace for the application.
*/ */
window.app = {}; window.app = {};
var app = window.app; const app = window.app;
// //
@@ -26,20 +26,20 @@ var app = window.app;
*/ */
app.RotateNorthControl = function(opt_options) { 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'; button.innerHTML = 'N';
var this_ = this; const this_ = this;
var handleRotateNorth = function() { const handleRotateNorth = function() {
this_.getMap().getView().setRotation(0); this_.getMap().getView().setRotation(0);
}; };
button.addEventListener('click', handleRotateNorth, false); button.addEventListener('click', handleRotateNorth, false);
button.addEventListener('touchstart', 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.className = 'rotate-north ol-unselectable ol-control';
element.appendChild(button); element.appendChild(button);
@@ -57,7 +57,7 @@ inherits(app.RotateNorthControl, Control);
// //
var map = new Map({ const map = new Map({
controls: defaultControls({ controls: defaultControls({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false

View File

@@ -20,7 +20,7 @@ import Style from '../src/ol/style/Style.js';
/** /**
* Define a namespace for the application. * 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. * @return {boolean} `true` to start the drag sequence.
*/ */
app.Drag.prototype.handleDownEvent = function(evt) { app.Drag.prototype.handleDownEvent = function(evt) {
var map = evt.map; const map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel, const feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) { function(feature) {
return feature; return feature;
}); });
if (feature) { if (feature) {
this.coordinate_ = evt.coordinate; this.coordinate_ = evt.coordinate;
@@ -89,10 +89,10 @@ app.Drag.prototype.handleDownEvent = function(evt) {
* @param {ol.MapBrowserEvent} evt Map browser event. * @param {ol.MapBrowserEvent} evt Map browser event.
*/ */
app.Drag.prototype.handleDragEvent = function(evt) { app.Drag.prototype.handleDragEvent = function(evt) {
var deltaX = evt.coordinate[0] - this.coordinate_[0]; const deltaX = evt.coordinate[0] - this.coordinate_[0];
var deltaY = evt.coordinate[1] - this.coordinate_[1]; const deltaY = evt.coordinate[1] - this.coordinate_[1];
var geometry = this.feature_.getGeometry(); const geometry = this.feature_.getGeometry();
geometry.translate(deltaX, deltaY); geometry.translate(deltaX, deltaY);
this.coordinate_[0] = evt.coordinate[0]; this.coordinate_[0] = evt.coordinate[0];
@@ -105,12 +105,12 @@ app.Drag.prototype.handleDragEvent = function(evt) {
*/ */
app.Drag.prototype.handleMoveEvent = function(evt) { app.Drag.prototype.handleMoveEvent = function(evt) {
if (this.cursor_) { if (this.cursor_) {
var map = evt.map; const map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel, const feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) { function(feature) {
return feature; return feature;
}); });
var element = evt.map.getTargetElement(); const element = evt.map.getTargetElement();
if (feature) { if (feature) {
if (element.style.cursor != this.cursor_) { if (element.style.cursor != this.cursor_) {
this.previousCursor_ = element.style.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( const lineFeature = new Feature(
new LineString([[-1e7, 1e6], [-1e6, 3e6]])); new LineString([[-1e7, 1e6], [-1e6, 3e6]]));
var polygonFeature = new Feature( const polygonFeature = new Feature(
new Polygon([[[-3e6, -1e6], [-3e6, 1e6], new Polygon([[[-3e6, -1e6], [-3e6, 1e6],
[-1e6, 1e6], [-1e6, -1e6], [-3e6, -1e6]]])); [-1e6, 1e6], [-1e6, -1e6], [-3e6, -1e6]]]));
var map = new Map({ const map = new Map({
interactions: defaultInteractions().extend([new app.Drag()]), interactions: defaultInteractions().extend([new app.Drag()]),
layers: [ layers: [
new TileLayer({ new TileLayer({

48
examples/d3.js vendored
View File

@@ -9,7 +9,7 @@ import ImageCanvasSource from '../src/ol/source/ImageCanvas.js';
import Stamen from '../src/ol/source/Stamen.js'; import Stamen from '../src/ol/source/Stamen.js';
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new Stamen({ source: new Stamen({
@@ -29,7 +29,7 @@ var map = new Map({
* Load the topojson data and create an ol.layer.Image for that data. * Load the topojson data and create an ol.layer.Image for that data.
*/ */
d3.json('data/topojson/us.json', function(error, us) { 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. * 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. * @param {ol.proj.Projection} projection Projection.
* @return {HTMLCanvasElement} A canvas element. * @return {HTMLCanvasElement} A canvas element.
*/ */
var canvasFunction = function(extent, resolution, pixelRatio, size, projection) { const canvasFunction = function(extent, resolution, pixelRatio, size, projection) {
var canvasWidth = size[0]; const canvasWidth = size[0];
var canvasHeight = size[1]; 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); 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]); const d3Projection = d3.geoMercator().scale(1).translate([0, 0]);
var d3Path = d3.geoPath().projection(d3Projection); let d3Path = d3.geoPath().projection(d3Projection);
var pixelBounds = d3Path.bounds(features); const pixelBounds = d3Path.bounds(features);
var pixelBoundsWidth = pixelBounds[1][0] - pixelBounds[0][0]; const pixelBoundsWidth = pixelBounds[1][0] - pixelBounds[0][0];
var pixelBoundsHeight = pixelBounds[1][1] - pixelBounds[0][1]; const pixelBoundsHeight = pixelBounds[1][1] - pixelBounds[0][1];
var geoBounds = d3.geoBounds(features); const geoBounds = d3.geoBounds(features);
var geoBoundsLeftBottom = fromLonLat(geoBounds[0], projection); const geoBoundsLeftBottom = fromLonLat(geoBounds[0], projection);
var geoBoundsRightTop = fromLonLat(geoBounds[1], projection); const geoBoundsRightTop = fromLonLat(geoBounds[1], projection);
var geoBoundsWidth = geoBoundsRightTop[0] - geoBoundsLeftBottom[0]; let geoBoundsWidth = geoBoundsRightTop[0] - geoBoundsLeftBottom[0];
if (geoBoundsWidth < 0) { if (geoBoundsWidth < 0) {
geoBoundsWidth += getWidth(projection.getExtent()); geoBoundsWidth += getWidth(projection.getExtent());
} }
var geoBoundsHeight = geoBoundsRightTop[1] - geoBoundsLeftBottom[1]; const geoBoundsHeight = geoBoundsRightTop[1] - geoBoundsLeftBottom[1];
var widthResolution = geoBoundsWidth / pixelBoundsWidth; const widthResolution = geoBoundsWidth / pixelBoundsWidth;
var heightResolution = geoBoundsHeight / pixelBoundsHeight; const heightResolution = geoBoundsHeight / pixelBoundsHeight;
var r = Math.max(widthResolution, heightResolution); const r = Math.max(widthResolution, heightResolution);
var scale = r / (resolution / pixelRatio); const scale = r / (resolution / pixelRatio);
var center = toLonLat(getCenter(extent), projection); const center = toLonLat(getCenter(extent), projection);
d3Projection.scale(scale).center(center) d3Projection.scale(scale).center(center)
.translate([canvasWidth / 2, canvasHeight / 2]); .translate([canvasWidth / 2, canvasHeight / 2]);
d3Path = d3Path.projection(d3Projection).context(context); d3Path = d3Path.projection(d3Projection).context(context);
d3Path(features); d3Path(features);
context.stroke(); context.stroke();
@@ -80,7 +80,7 @@ d3.json('data/topojson/us.json', function(error, us) {
return canvas.node(); return canvas.node();
}; };
var layer = new ImageLayer({ const layer = new ImageLayer({
source: new ImageCanvasSource({ source: new ImageCanvasSource({
canvasFunction: canvasFunction, canvasFunction: canvasFunction,
projection: 'EPSG:3857' projection: 'EPSG:3857'

View File

@@ -6,11 +6,11 @@ import TileLayer from '../src/ol/layer/Tile.js';
import {toRadians} from '../src/ol/math.js'; import {toRadians} from '../src/ol/math.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -30,15 +30,15 @@ function el(id) {
} }
var gn = new GyroNorm(); const gn = new GyroNorm();
gn.init().then(function() { gn.init().then(function() {
gn.start(function(event) { gn.start(function(event) {
var center = view.getCenter(); const center = view.getCenter();
var resolution = view.getResolution(); const resolution = view.getResolution();
var alpha = toRadians(event.do.beta); const alpha = toRadians(event.do.beta);
var beta = toRadians(event.do.beta); const beta = toRadians(event.do.beta);
var gamma = toRadians(event.do.gamma); const gamma = toRadians(event.do.gamma);
el('alpha').innerText = alpha + ' [rad]'; el('alpha').innerText = alpha + ' [rad]';
el('beta').innerText = beta + ' [rad]'; el('beta').innerText = beta + ' [rad]';

View File

@@ -17,7 +17,7 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var defaultStyle = { const defaultStyle = {
'Point': new Style({ 'Point': new Style({
image: new CircleStyle({ image: new CircleStyle({
fill: new Fill({ fill: new Fill({
@@ -74,8 +74,8 @@ var defaultStyle = {
}) })
}; };
var styleFunction = function(feature, resolution) { const styleFunction = function(feature, resolution) {
var featureStyleFunction = feature.getStyleFunction(); const featureStyleFunction = feature.getStyleFunction();
if (featureStyleFunction) { if (featureStyleFunction) {
return featureStyleFunction.call(feature, resolution); return featureStyleFunction.call(feature, resolution);
} else { } else {
@@ -83,7 +83,7 @@ var styleFunction = function(feature, resolution) {
} }
}; };
var dragAndDropInteraction = new DragAndDrop({ const dragAndDropInteraction = new DragAndDrop({
formatConstructors: [ formatConstructors: [
GPX, GPX,
GeoJSON, GeoJSON,
@@ -93,7 +93,7 @@ var dragAndDropInteraction = new DragAndDrop({
] ]
}); });
var map = new Map({ const map = new Map({
interactions: defaultInteractions().extend([dragAndDropInteraction]), interactions: defaultInteractions().extend([dragAndDropInteraction]),
layers: [ layers: [
new TileLayer({ new TileLayer({
@@ -111,7 +111,7 @@ var map = new Map({
}); });
dragAndDropInteraction.on('addfeatures', function(event) { dragAndDropInteraction.on('addfeatures', function(event) {
var vectorSource = new VectorSource({ const vectorSource = new VectorSource({
features: event.features features: event.features
}); });
map.addLayer(new VectorLayer({ map.addLayer(new VectorLayer({
@@ -122,14 +122,14 @@ dragAndDropInteraction.on('addfeatures', function(event) {
map.getView().fit(vectorSource.getExtent()); map.getView().fit(vectorSource.getExtent());
}); });
var displayFeatureInfo = function(pixel) { const displayFeatureInfo = function(pixel) {
var features = []; const features = [];
map.forEachFeatureAtPixel(pixel, function(feature) { map.forEachFeatureAtPixel(pixel, function(feature) {
features.push(feature); features.push(feature);
}); });
if (features.length > 0) { if (features.length > 0) {
var info = []; const info = [];
var i, ii; let i, ii;
for (i = 0, ii = features.length; i < ii; ++i) { for (i = 0, ii = features.length; i < ii; ++i) {
info.push(features[i].get('name')); info.push(features[i].get('name'));
} }
@@ -143,7 +143,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
var pixel = map.getEventPixel(evt.originalEvent); const pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel); displayFeatureInfo(pixel);
}); });

View File

@@ -17,7 +17,7 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var defaultStyle = { const defaultStyle = {
'Point': new Style({ 'Point': new Style({
image: new CircleStyle({ image: new CircleStyle({
fill: new Fill({ fill: new Fill({
@@ -74,8 +74,8 @@ var defaultStyle = {
}) })
}; };
var styleFunction = function(feature, resolution) { const styleFunction = function(feature, resolution) {
var featureStyleFunction = feature.getStyleFunction(); const featureStyleFunction = feature.getStyleFunction();
if (featureStyleFunction) { if (featureStyleFunction) {
return featureStyleFunction.call(feature, resolution); return featureStyleFunction.call(feature, resolution);
} else { } else {
@@ -83,7 +83,7 @@ var styleFunction = function(feature, resolution) {
} }
}; };
var dragAndDropInteraction = new DragAndDrop({ const dragAndDropInteraction = new DragAndDrop({
formatConstructors: [ formatConstructors: [
GPX, GPX,
GeoJSON, GeoJSON,
@@ -93,7 +93,7 @@ var dragAndDropInteraction = new DragAndDrop({
] ]
}); });
var map = new Map({ const map = new Map({
interactions: defaultInteractions().extend([dragAndDropInteraction]), interactions: defaultInteractions().extend([dragAndDropInteraction]),
layers: [ layers: [
new TileLayer({ new TileLayer({
@@ -111,7 +111,7 @@ var map = new Map({
}); });
dragAndDropInteraction.on('addfeatures', function(event) { dragAndDropInteraction.on('addfeatures', function(event) {
var vectorSource = new VectorSource({ const vectorSource = new VectorSource({
features: event.features features: event.features
}); });
map.addLayer(new VectorLayer({ map.addLayer(new VectorLayer({
@@ -121,14 +121,14 @@ dragAndDropInteraction.on('addfeatures', function(event) {
map.getView().fit(vectorSource.getExtent()); map.getView().fit(vectorSource.getExtent());
}); });
var displayFeatureInfo = function(pixel) { const displayFeatureInfo = function(pixel) {
var features = []; const features = [];
map.forEachFeatureAtPixel(pixel, function(feature) { map.forEachFeatureAtPixel(pixel, function(feature) {
features.push(feature); features.push(feature);
}); });
if (features.length > 0) { if (features.length > 0) {
var info = []; const info = [];
var i, ii; let i, ii;
for (i = 0, ii = features.length; i < ii; ++i) { for (i = 0, ii = features.length; i < ii; ++i) {
info.push(features[i].get('name')); info.push(features[i].get('name'));
} }
@@ -142,7 +142,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
var pixel = map.getEventPixel(evt.originalEvent); const pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel); displayFeatureInfo(pixel);
}); });

View File

@@ -6,7 +6,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var map = new Map({ const map = new Map({
interactions: defaultInteractions().extend([ interactions: defaultInteractions().extend([
new DragRotateAndZoom() new DragRotateAndZoom()
]), ]),

View File

@@ -12,12 +12,12 @@ import Fill from '../src/ol/style/Fill.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM()
}); });
var source = new VectorSource(); const source = new VectorSource();
var vector = new VectorLayer({ const vector = new VectorLayer({
source: source, source: source,
style: new Style({ style: new Style({
fill: new Fill({ fill: new Fill({
@@ -36,7 +36,7 @@ var vector = new VectorLayer({
}) })
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ 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); map.addInteraction(modify);
var draw, snap; // global so we can remove them later let draw, snap; // global so we can remove them later
var typeSelect = document.getElementById('type'); const typeSelect = document.getElementById('type');
function addInteractions() { function addInteractions() {
draw = new Draw({ draw = new Draw({

View File

@@ -6,17 +6,17 @@ import VectorLayer from '../src/ol/layer/Vector.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() 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 source: source
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ 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() { function addInteraction() {
var value = typeSelect.value; const value = typeSelect.value;
if (value !== 'None') { if (value !== 'None') {
draw = new Draw({ draw = new Draw({
source: source, source: source,

View File

@@ -6,17 +6,17 @@ import VectorLayer from '../src/ol/layer/Vector.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() 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 source: source
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ 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() { function addInteraction() {
var value = typeSelect.value; const value = typeSelect.value;
if (value !== 'None') { if (value !== 'None') {
draw = new Draw({ draw = new Draw({
source: source, source: source,

View File

@@ -7,17 +7,17 @@ import VectorLayer from '../src/ol/layer/Vector.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() 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 source: source
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ 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() { function addInteraction() {
var value = typeSelect.value; let value = typeSelect.value;
if (value !== 'None') { if (value !== 'None') {
var geometryFunction; let geometryFunction;
if (value === 'Square') { if (value === 'Square') {
value = 'Circle'; value = 'Circle';
geometryFunction = Draw.createRegularPolygon(4); geometryFunction = Draw.createRegularPolygon(4);
@@ -45,19 +45,19 @@ function addInteraction() {
if (!geometry) { if (!geometry) {
geometry = new Polygon(null); geometry = new Polygon(null);
} }
var center = coordinates[0]; const center = coordinates[0];
var last = coordinates[1]; const last = coordinates[1];
var dx = center[0] - last[0]; const dx = center[0] - last[0];
var dy = center[1] - last[1]; const dy = center[1] - last[1];
var radius = Math.sqrt(dx * dx + dy * dy); const radius = Math.sqrt(dx * dx + dy * dy);
var rotation = Math.atan2(dy, dx); const rotation = Math.atan2(dy, dx);
var newCoordinates = []; const newCoordinates = [];
var numPoints = 12; const numPoints = 12;
for (var i = 0; i < numPoints; ++i) { for (let i = 0; i < numPoints; ++i) {
var angle = rotation + i * 2 * Math.PI / numPoints; const angle = rotation + i * 2 * Math.PI / numPoints;
var fraction = i % 2 === 0 ? 1 : 0.5; const fraction = i % 2 === 0 ? 1 : 0.5;
var offsetX = radius * fraction * Math.cos(angle); const offsetX = radius * fraction * Math.cos(angle);
var offsetY = radius * fraction * Math.sin(angle); const offsetY = radius * fraction * Math.sin(angle);
newCoordinates.push([center[0] + offsetX, center[1] + offsetY]); newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
} }
newCoordinates.push(newCoordinates[0].slice()); newCoordinates.push(newCoordinates[0].slice());

View File

@@ -10,7 +10,7 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -23,7 +23,7 @@ var map = new Map({
}) })
}); });
var imageStyle = new Style({ const imageStyle = new Style({
image: new CircleStyle({ image: new CircleStyle({
radius: 5, radius: 5,
snapToPixel: false, snapToPixel: false,
@@ -32,7 +32,7 @@ var imageStyle = new Style({
}) })
}); });
var headInnerImageStyle = new Style({ const headInnerImageStyle = new Style({
image: new CircleStyle({ image: new CircleStyle({
radius: 2, radius: 2,
snapToPixel: false, snapToPixel: false,
@@ -40,7 +40,7 @@ var headInnerImageStyle = new Style({
}) })
}); });
var headOuterImageStyle = new Style({ const headOuterImageStyle = new Style({
image: new CircleStyle({ image: new CircleStyle({
radius: 5, radius: 5,
snapToPixel: false, snapToPixel: false,
@@ -48,27 +48,27 @@ var headOuterImageStyle = new Style({
}) })
}); });
var n = 200; const n = 200;
var omegaTheta = 30000; // Rotation period in ms const omegaTheta = 30000; // Rotation period in ms
var R = 7e6; const R = 7e6;
var r = 2e6; const r = 2e6;
var p = 2e6; const p = 2e6;
map.on('postcompose', function(event) { map.on('postcompose', function(event) {
var vectorContext = event.vectorContext; const vectorContext = event.vectorContext;
var frameState = event.frameState; const frameState = event.frameState;
var theta = 2 * Math.PI * frameState.time / omegaTheta; const theta = 2 * Math.PI * frameState.time / omegaTheta;
var coordinates = []; const coordinates = [];
var i; let i;
for (i = 0; i < n; ++i) { for (i = 0; i < n; ++i) {
var t = theta + 2 * Math.PI * i / n; const t = theta + 2 * Math.PI * i / n;
var x = (R + r) * Math.cos(t) + p * Math.cos((R + r) * t / r); const 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 y = (R + r) * Math.sin(t) + p * Math.sin((R + r) * t / r);
coordinates.push([x, y]); coordinates.push([x, y]);
} }
vectorContext.setStyle(imageStyle); vectorContext.setStyle(imageStyle);
vectorContext.drawGeometry(new MultiPoint(coordinates)); 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.setStyle(headOuterImageStyle);
vectorContext.drawGeometry(headPoint); vectorContext.drawGeometry(headPoint);

View File

@@ -17,21 +17,21 @@ import Style from '../src/ol/style/Style.js';
import Text from '../src/ol/style/Text.js'; import Text from '../src/ol/style/Text.js';
var earthquakeFill = new Fill({ const earthquakeFill = new Fill({
color: 'rgba(255, 153, 0, 0.8)' color: 'rgba(255, 153, 0, 0.8)'
}); });
var earthquakeStroke = new Stroke({ const earthquakeStroke = new Stroke({
color: 'rgba(255, 204, 0, 0.2)', color: 'rgba(255, 204, 0, 0.2)',
width: 1 width: 1
}); });
var textFill = new Fill({ const textFill = new Fill({
color: '#fff' color: '#fff'
}); });
var textStroke = new Stroke({ const textStroke = new Stroke({
color: 'rgba(0, 0, 0, 0.6)', color: 'rgba(0, 0, 0, 0.6)',
width: 3 width: 3
}); });
var invisibleFill = new Fill({ const invisibleFill = new Fill({
color: 'rgba(255, 255, 255, 0.01)' 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 // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a
// standards-violating <magnitude> tag in each Placemark. We extract it // standards-violating <magnitude> tag in each Placemark. We extract it
// from the Placemark's name instead. // from the Placemark's name instead.
var name = feature.get('name'); const name = feature.get('name');
var magnitude = parseFloat(name.substr(2)); const magnitude = parseFloat(name.substr(2));
var radius = 5 + 20 * (magnitude - 5); const radius = 5 + 20 * (magnitude - 5);
return new Style({ return new Style({
geometry: feature.getGeometry(), geometry: feature.getGeometry(),
@@ -56,16 +56,17 @@ function createEarthquakeStyle(feature) {
}); });
} }
var maxFeatureCount, vector; let maxFeatureCount;
function calculateClusterInfo(resolution) { let vector = null;
const calculateClusterInfo = function(resolution) {
maxFeatureCount = 0; maxFeatureCount = 0;
var features = vector.getSource().getFeatures(); const features = vector.getSource().getFeatures();
var feature, radius; let feature, radius;
for (var i = features.length - 1; i >= 0; --i) { for (let i = features.length - 1; i >= 0; --i) {
feature = features[i]; feature = features[i];
var originalFeatures = feature.get('features'); const originalFeatures = feature.get('features');
var extent = _ol_extent_.createEmpty(); const extent = _ol_extent_.createEmpty();
var j, jj; let j, jj;
for (j = 0, jj = originalFeatures.length; j < jj; ++j) { for (j = 0, jj = originalFeatures.length; j < jj; ++j) {
_ol_extent_.extend(extent, originalFeatures[j].getGeometry().getExtent()); _ol_extent_.extend(extent, originalFeatures[j].getGeometry().getExtent());
} }
@@ -74,16 +75,16 @@ function calculateClusterInfo(resolution) {
resolution; resolution;
feature.set('radius', radius); feature.set('radius', radius);
} }
} };
var currentResolution; let currentResolution;
function styleFunction(feature, resolution) { function styleFunction(feature, resolution) {
if (resolution != currentResolution) { if (resolution != currentResolution) {
calculateClusterInfo(resolution); calculateClusterInfo(resolution);
currentResolution = resolution; currentResolution = resolution;
} }
var style; let style;
var size = feature.get('features').length; const size = feature.get('features').length;
if (size > 1) { if (size > 1) {
style = new Style({ style = new Style({
image: new CircleStyle({ image: new CircleStyle({
@@ -99,22 +100,22 @@ function styleFunction(feature, resolution) {
}) })
}); });
} else { } else {
var originalFeature = feature.get('features')[0]; const originalFeature = feature.get('features')[0];
style = createEarthquakeStyle(originalFeature); style = createEarthquakeStyle(originalFeature);
} }
return style; return style;
} }
function selectStyleFunction(feature) { function selectStyleFunction(feature) {
var styles = [new Style({ const styles = [new Style({
image: new CircleStyle({ image: new CircleStyle({
radius: feature.get('radius'), radius: feature.get('radius'),
fill: invisibleFill fill: invisibleFill
}) })
})]; })];
var originalFeatures = feature.get('features'); const originalFeatures = feature.get('features');
var originalFeature; let originalFeature;
for (var i = originalFeatures.length - 1; i >= 0; --i) { for (let i = originalFeatures.length - 1; i >= 0; --i) {
originalFeature = originalFeatures[i]; originalFeature = originalFeatures[i];
styles.push(createEarthquakeStyle(originalFeature)); styles.push(createEarthquakeStyle(originalFeature));
} }
@@ -134,13 +135,13 @@ vector = new VectorLayer({
style: styleFunction style: styleFunction
}); });
var raster = new TileLayer({ const raster = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner'
}) })
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
interactions: defaultInteractions().extend([new Select({ interactions: defaultInteractions().extend([new Select({
condition: function(evt) { condition: function(evt) {

View File

@@ -13,28 +13,28 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.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]]; const symbol = [[0, 0], [4, 2], [6, 0], [10, 5], [6, 3], [4, 5], [0, 0]];
var scale; let scale;
var scaleFunction = function(coordinate) { const scaleFunction = function(coordinate) {
return [coordinate[0] * scale, coordinate[1] * scale]; return [coordinate[0] * scale, coordinate[1] * scale];
}; };
var styleCache = {}; const styleCache = {};
var styleFunction = function(feature) { const styleFunction = function(feature) {
// 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a
// standards-violating <magnitude> tag in each Placemark. We extract it from // standards-violating <magnitude> tag in each Placemark. We extract it from
// the Placemark's name instead. // the Placemark's name instead.
var name = feature.get('name'); const name = feature.get('name');
var magnitude = parseFloat(name.substr(2)); const magnitude = parseFloat(name.substr(2));
var size = parseInt(10 + 40 * (magnitude - 5), 10); const size = parseInt(10 + 40 * (magnitude - 5), 10);
scale = size / 10; scale = size / 10;
var style = styleCache[size]; let style = styleCache[size];
if (!style) { if (!style) {
var canvas = const canvas =
/** @type {HTMLCanvasElement} */ (document.createElement('canvas')); /** @type {HTMLCanvasElement} */ (document.createElement('canvas'));
var vectorContext = _ol_render_.toContext( const vectorContext = _ol_render_.toContext(
/** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d')), /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d')),
{size: [size, size], pixelRatio: 1}); {size: [size, size], pixelRatio: 1});
vectorContext.setStyle(new Style({ vectorContext.setStyle(new Style({
fill: new Fill({color: 'rgba(255, 153, 0, 0.4)'}), fill: new Fill({color: 'rgba(255, 153, 0, 0.4)'}),
stroke: new Stroke({color: 'rgba(255, 204, 0, 0.2)', width: 2}) stroke: new Stroke({color: 'rgba(255, 204, 0, 0.2)', width: 2})
@@ -52,7 +52,7 @@ var styleFunction = function(feature) {
return style; return style;
}; };
var vector = new VectorLayer({ const vector = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
url: 'data/kml/2012_Earthquakes_Mag5.kml', url: 'data/kml/2012_Earthquakes_Mag5.kml',
format: new KML({ format: new KML({
@@ -62,13 +62,13 @@ var vector = new VectorLayer({
style: styleFunction style: styleFunction
}); });
var raster = new TileLayer({ const raster = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner'
}) })
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new View({

View File

@@ -6,7 +6,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import TileWMS from '../src/ol/source/TileWMS.js'; import TileWMS from '../src/ol/source/TileWMS.js';
var layers = [ const layers = [
new TileLayer({ new TileLayer({
source: new TileWMS({ source: new TileWMS({
url: 'https://ahocevar.com/geoserver/wms', url: 'https://ahocevar.com/geoserver/wms',
@@ -18,7 +18,7 @@ var layers = [
}) })
]; ];
var map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([
new ScaleLine({ new ScaleLine({
units: 'degrees' units: 'degrees'

View File

@@ -9,7 +9,7 @@ import VectorLayer from '../src/ol/layer/Vector.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -35,7 +35,7 @@ var map = new Map({
document.getElementById('export-png').addEventListener('click', function() { document.getElementById('export-png').addEventListener('click', function() {
map.once('postcompose', function(event) { map.once('postcompose', function(event) {
var canvas = event.context.canvas; const canvas = event.context.canvas;
if (navigator.msSaveBlob) { if (navigator.msSaveBlob) {
navigator.msSaveBlob(canvas.msToBlob(), 'map.png'); navigator.msSaveBlob(canvas.msToBlob(), 'map.png');
} else { } else {

View File

@@ -8,25 +8,25 @@ import VectorLayer from '../src/ol/layer/Vector.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM()
}); });
var format = new WKT(); const format = new WKT();
var feature = format.readFeature( const feature = format.readFeature(
'POLYGON((10.689697265625 -25.0927734375, 34.595947265625 ' + 'POLYGON((10.689697265625 -25.0927734375, 34.595947265625 ' +
'-20.1708984375, 38.814697265625 -35.6396484375, 13.502197265625 ' + '-20.1708984375, 38.814697265625 -35.6396484375, 13.502197265625 ' +
'-39.1552734375, 10.689697265625 -25.0927734375))'); '-39.1552734375, 10.689697265625 -25.0927734375))');
feature.getGeometry().transform('EPSG:4326', 'EPSG:3857'); feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
var vector = new VectorLayer({ const vector = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
features: [feature] features: [feature]
}) })
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
controls: defaultControls({ controls: defaultControls({
@@ -41,7 +41,7 @@ var map = new Map({
}); });
var dims = { const dims = {
a0: [1189, 841], a0: [1189, 841],
a1: [841, 594], a1: [841, 594],
a2: [594, 420], a2: [594, 420],
@@ -50,39 +50,39 @@ var dims = {
a5: [210, 148] a5: [210, 148]
}; };
var loading = 0; let loading = 0;
var loaded = 0; let loaded = 0;
var exportButton = document.getElementById('export-pdf'); const exportButton = document.getElementById('export-pdf');
exportButton.addEventListener('click', function() { exportButton.addEventListener('click', function() {
exportButton.disabled = true; exportButton.disabled = true;
document.body.style.cursor = 'progress'; document.body.style.cursor = 'progress';
var format = document.getElementById('format').value; const format = document.getElementById('format').value;
var resolution = document.getElementById('resolution').value; const resolution = document.getElementById('resolution').value;
var dim = dims[format]; const dim = dims[format];
var width = Math.round(dim[0] * resolution / 25.4); const width = Math.round(dim[0] * resolution / 25.4);
var height = Math.round(dim[1] * resolution / 25.4); const height = Math.round(dim[1] * resolution / 25.4);
var size = /** @type {ol.Size} */ (map.getSize()); const size = /** @type {ol.Size} */ (map.getSize());
var extent = map.getView().calculateExtent(size); const extent = map.getView().calculateExtent(size);
var source = raster.getSource(); const source = raster.getSource();
var tileLoadStart = function() { const tileLoadStart = function() {
++loading; ++loading;
}; };
var tileLoadEnd = function() { function tileLoadEnd() {
++loaded; ++loaded;
if (loading === loaded) { if (loading === loaded) {
var canvas = this; const canvas = this;
window.setTimeout(function() { window.setTimeout(function() {
loading = 0; loading = 0;
loaded = 0; loaded = 0;
var data = canvas.toDataURL('image/png'); const data = canvas.toDataURL('image/png');
var pdf = new jsPDF('landscape', undefined, format); const pdf = new jsPDF('landscape', undefined, format);
pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]); pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]);
pdf.save('map.pdf'); pdf.save('map.pdf');
source.un('tileloadstart', tileLoadStart); source.un('tileloadstart', tileLoadStart);
@@ -95,7 +95,7 @@ exportButton.addEventListener('click', function() {
document.body.style.cursor = 'auto'; document.body.style.cursor = 'auto';
}, 100); }, 100);
} }
}; }
map.once('postcompose', function(event) { map.once('postcompose', function(event) {
source.on('tileloadstart', tileLoadStart); source.on('tileloadstart', tileLoadStart);

View File

@@ -8,12 +8,12 @@ import VectorLayer from '../src/ol/layer/Vector.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var vectorSource = new VectorSource({ const vectorSource = new VectorSource({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new GeoJSON()
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -29,7 +29,7 @@ var map = new Map({
}) })
}); });
var extent = new ExtentInteraction({ const extent = new ExtentInteraction({
condition: _ol_events_condition_.platformModifierKeyOnly condition: _ol_events_condition_.platformModifierKeyOnly
}); });
map.addInteraction(extent); map.addInteraction(extent);

View File

@@ -15,7 +15,7 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM({ source: new OSM({
@@ -35,38 +35,38 @@ var map = new Map({
}) })
}); });
var source = new VectorSource({ const source = new VectorSource({
wrapX: false wrapX: false
}); });
var vector = new VectorLayer({ const vector = new VectorLayer({
source: source source: source
}); });
map.addLayer(vector); map.addLayer(vector);
function addRandomFeature() { function addRandomFeature() {
var x = Math.random() * 360 - 180; const x = Math.random() * 360 - 180;
var y = Math.random() * 180 - 90; const y = Math.random() * 180 - 90;
var geom = new Point(fromLonLat([x, y])); const geom = new Point(fromLonLat([x, y]));
var feature = new Feature(geom); const feature = new Feature(geom);
source.addFeature(feature); source.addFeature(feature);
} }
var duration = 3000; const duration = 3000;
function flash(feature) { function flash(feature) {
var start = new Date().getTime(); const start = new Date().getTime();
var listenerKey; const listenerKey = map.on('postcompose', animate);
function animate(event) { function animate(event) {
var vectorContext = event.vectorContext; const vectorContext = event.vectorContext;
var frameState = event.frameState; const frameState = event.frameState;
var flashGeom = feature.getGeometry().clone(); const flashGeom = feature.getGeometry().clone();
var elapsed = frameState.time - start; const elapsed = frameState.time - start;
var elapsedRatio = elapsed / duration; const elapsedRatio = elapsed / duration;
// radius will be 5 at start and 30 at end. // radius will be 5 at start and 30 at end.
var radius = easeOut(elapsedRatio) * 25 + 5; const radius = easeOut(elapsedRatio) * 25 + 5;
var opacity = easeOut(1 - elapsedRatio); const opacity = easeOut(1 - elapsedRatio);
var style = new Style({ const style = new Style({
image: new CircleStyle({ image: new CircleStyle({
radius: radius, radius: radius,
snapToPixel: false, snapToPixel: false,
@@ -86,7 +86,6 @@ function flash(feature) {
// tell OpenLayers to continue postcompose animation // tell OpenLayers to continue postcompose animation
map.render(); map.render();
} }
listenerKey = map.on('postcompose', animate);
} }
source.on('addfeature', function(e) { source.on('addfeature', function(e) {

View File

@@ -15,7 +15,7 @@ import Style from '../src/ol/style/Style.js';
// This long string is placed here due to jsFiddle limitations. // This long string is placed here due to jsFiddle limitations.
// It is usually loaded with AJAX. // 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', 'hldhx@lnau`BCG_EaC??cFjAwDjF??uBlKMd@}@z@??aC^yk@z_@se@b[wFdE??wFfE}N',
'fIoGxB_I\\gG}@eHoCyTmPqGaBaHOoD\\??yVrGotA|N??o[N_STiwAtEmHGeHcAkiA}^', 'fIoGxB_I\\gG}@eHoCyTmPqGaBaHOoD\\??yVrGotA|N??o[N_STiwAtEmHGeHcAkiA}^',
'aMyBiHOkFNoI`CcVvM??gG^gF_@iJwC??eCcA]OoL}DwFyCaCgCcCwDcGwHsSoX??wI_E', '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' '~@ym@yjA??a@cFd@kBrCgDbAUnAcBhAyAdk@et@??kF}D??OL'
].join(''); ].join('');
var route = /** @type {ol.geom.LineString} */ (new Polyline({ const route = /** @type {ol.geom.LineString} */ (new Polyline({
factor: 1e6 factor: 1e6
}).readGeometry(polyline, { }).readGeometry(polyline, {
dataProjection: 'EPSG:4326', dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857' featureProjection: 'EPSG:3857'
})); }));
var routeCoords = route.getCoordinates(); const routeCoords = route.getCoordinates();
var routeLength = routeCoords.length; const routeLength = routeCoords.length;
var routeFeature = new Feature({ const routeFeature = new Feature({
type: 'route', type: 'route',
geometry: route geometry: route
}); });
var geoMarker = new Feature({ const geoMarker = new Feature({
type: 'geoMarker', type: 'geoMarker',
geometry: new Point(routeCoords[0]) geometry: new Point(routeCoords[0])
}); });
var startMarker = new Feature({ const startMarker = new Feature({
type: 'icon', type: 'icon',
geometry: new Point(routeCoords[0]) geometry: new Point(routeCoords[0])
}); });
var endMarker = new Feature({ const endMarker = new Feature({
type: 'icon', type: 'icon',
geometry: new Point(routeCoords[routeLength - 1]) geometry: new Point(routeCoords[routeLength - 1])
}); });
var styles = { const styles = {
'route': new Style({ 'route': new Style({
stroke: new Stroke({ stroke: new Stroke({
width: 6, color: [237, 212, 0, 0.8] width: 6, color: [237, 212, 0, 0.8]
@@ -108,12 +108,12 @@ var styles = {
}) })
}; };
var animating = false; let animating = false;
var speed, now; let speed, now;
var speedInput = document.getElementById('speed'); const speedInput = document.getElementById('speed');
var startButton = document.getElementById('start-animation'); const startButton = document.getElementById('start-animation');
var vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
features: [routeFeature, geoMarker, startMarker, endMarker] features: [routeFeature, geoMarker, startMarker, endMarker]
}), }),
@@ -126,8 +126,8 @@ var vectorLayer = new VectorLayer({
} }
}); });
var center = [-5639523.95, -3501274.52]; const center = [-5639523.95, -3501274.52];
var map = new Map({ const map = new Map({
target: document.getElementById('map'), target: document.getElementById('map'),
loadTilesWhileAnimating: true, loadTilesWhileAnimating: true,
view: new View({ view: new View({
@@ -147,23 +147,23 @@ var map = new Map({
] ]
}); });
var moveFeature = function(event) { const moveFeature = function(event) {
var vectorContext = event.vectorContext; const vectorContext = event.vectorContext;
var frameState = event.frameState; const frameState = event.frameState;
if (animating) { if (animating) {
var elapsedTime = frameState.time - now; const elapsedTime = frameState.time - now;
// here the trick to increase speed is to jump some indexes // here the trick to increase speed is to jump some indexes
// on lineString coordinates // on lineString coordinates
var index = Math.round(speed * elapsedTime / 1000); const index = Math.round(speed * elapsedTime / 1000);
if (index >= routeLength) { if (index >= routeLength) {
stopAnimation(true); stopAnimation(true);
return; return;
} }
var currentPoint = new Point(routeCoords[index]); const currentPoint = new Point(routeCoords[index]);
var feature = new Feature(currentPoint); const feature = new Feature(currentPoint);
vectorContext.drawFeature(feature, styles.geoMarker); vectorContext.drawFeature(feature, styles.geoMarker);
} }
// tell OpenLayers to continue the postcompose animation // tell OpenLayers to continue the postcompose animation
@@ -196,9 +196,9 @@ function stopAnimation(ended) {
startButton.textContent = 'Start Animation'; startButton.textContent = 'Start Animation';
// if animation cancelled set the marker at the beginning // 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()) /** @type {ol.geom.Point} */ (geoMarker.getGeometry())
.setCoordinates(coord); .setCoordinates(coord);
//remove listener //remove listener
map.un('postcompose', moveFeature); map.un('postcompose', moveFeature);
} }

View File

@@ -10,7 +10,7 @@ import VectorSource from '../src/ol/source/Vector.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new Stamen({ source: new Stamen({
@@ -25,77 +25,39 @@ var map = new Map({
}) })
}); });
var style = new Style({ const style = new Style({
stroke: new Stroke({ stroke: new Stroke({
color: '#EAE911', color: '#EAE911',
width: 2 width: 2
}) })
}); });
var flightsSource; const flightsSource = new VectorSource({
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({
wrapX: false, wrapX: false,
attributions: 'Flight data by ' + attributions: 'Flight data by ' +
'<a href="http://openflights.org/data.html">OpenFlights</a>,', '<a href="http://openflights.org/data.html">OpenFlights</a>,',
loader: function() { loader: function() {
var url = 'data/openflights/flights.json'; const url = 'data/openflights/flights.json';
fetch(url).then(function(response) { fetch(url).then(function(response) {
return response.json(); return response.json();
}).then(function(json) { }).then(function(json) {
var flightsData = json.flights; const flightsData = json.flights;
for (var i = 0; i < flightsData.length; i++) { for (let i = 0; i < flightsData.length; i++) {
var flight = flightsData[i]; const flight = flightsData[i];
var from = flight[0]; const from = flight[0];
var to = flight[1]; const to = flight[1];
// create an arc circle between the two locations // create an arc circle between the two locations
var arcGenerator = new arc.GreatCircle( const arcGenerator = new arc.GreatCircle(
{x: from[1], y: from[0]}, {x: from[1], y: from[0]},
{x: to[1], y: to[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) { 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'); line.transform('EPSG:4326', 'EPSG:3857');
var feature = new Feature({ const feature = new Feature({
geometry: line, geometry: line,
finished: false finished: false
}); });
@@ -109,7 +71,7 @@ flightsSource = new VectorSource({
} }
}); });
var flightsLayer = new VectorLayer({ const flightsLayer = new VectorLayer({
source: flightsSource, source: flightsSource,
style: function(feature) { style: function(feature) {
// if the animation is still active for a feature, do not // if the animation is still active for a feature, do not
@@ -121,4 +83,42 @@ var flightsLayer = new VectorLayer({
} }
} }
}); });
map.addLayer(flightsLayer); 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);
}

View File

@@ -5,25 +5,25 @@ import LineString from '../src/ol/geom/LineString.js';
import VectorLayer from '../src/ol/layer/Vector.js'; import VectorLayer from '../src/ol/layer/Vector.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var radius = 10e6; const radius = 10e6;
var cos30 = Math.cos(Math.PI / 6); const cos30 = Math.cos(Math.PI / 6);
var sin30 = Math.sin(Math.PI / 6); const sin30 = Math.sin(Math.PI / 6);
var rise = radius * sin30; const rise = radius * sin30;
var run = radius * cos30; const run = radius * cos30;
var triangle = new LineString([ const triangle = new LineString([
[0, radius], [run, -rise], [-run, -rise], [0, radius] [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({ source: new VectorSource({
features: [feature] features: [feature]
}) })
}); });
var map = new Map({ const map = new Map({
layers: [layer], layers: [layer],
target: 'map', target: 'map',
view: new View({ view: new View({
@@ -33,44 +33,44 @@ var map = new Map({
}); });
function makeFractal(depth) { function makeFractal(depth) {
var geometry = triangle.clone(); const geometry = triangle.clone();
var graph = coordsToGraph(geometry.getCoordinates()); const graph = coordsToGraph(geometry.getCoordinates());
for (var i = 0; i < depth; ++i) { for (let i = 0; i < depth; ++i) {
var node = graph; let node = graph;
while (node.next) { while (node.next) {
var next = node.next; const next = node.next;
injectNodes(node); injectNodes(node);
node = next; node = next;
} }
} }
var coordinates = graphToCoords(graph); const coordinates = graphToCoords(graph);
document.getElementById('count').innerHTML = coordinates.length; document.getElementById('count').innerHTML = coordinates.length;
geometry.setCoordinates(coordinates); geometry.setCoordinates(coordinates);
feature.setGeometry(geometry); feature.setGeometry(geometry);
} }
function injectNodes(startNode) { function injectNodes(startNode) {
var endNode = startNode.next; const endNode = startNode.next;
var start = startNode.point; const start = startNode.point;
var end = startNode.next.point; const end = startNode.next.point;
var dx = end[0] - start[0]; const dx = end[0] - start[0];
var dy = end[1] - start[1]; const dy = end[1] - start[1];
// first point at 1/3 along the segment // first point at 1/3 along the segment
var firstNode = { const firstNode = {
point: [start[0] + dx / 3, start[1] + dy / 3] point: [start[0] + dx / 3, start[1] + dy / 3]
}; };
// second point at peak of _/\_ // second point at peak of _/\_
var r = Math.sqrt(dx * dx + dy * dy) / (2 * cos30); const r = Math.sqrt(dx * dx + dy * dy) / (2 * cos30);
var a = Math.atan2(dy, dx) + Math.PI / 6; const a = Math.atan2(dy, dx) + Math.PI / 6;
var secondNode = { const secondNode = {
point: [start[0] + r * Math.cos(a), start[1] + r * Math.sin(a)] point: [start[0] + r * Math.cos(a), start[1] + r * Math.sin(a)]
}; };
// third point at 2/3 along the segment // third point at 2/3 along the segment
var thirdNode = { const thirdNode = {
point: [end[0] - dx / 3, end[1] - dy / 3] point: [end[0] - dx / 3, end[1] - dy / 3]
}; };
@@ -82,11 +82,11 @@ function injectNodes(startNode) {
function coordsToGraph(coordinates) { function coordsToGraph(coordinates) {
var graph = { const graph = {
point: coordinates[0] point: coordinates[0]
}; };
var length = coordinates.length; const length = coordinates.length;
for (var level = 0, node = graph; level < length - 1; ++level) { for (let level = 0, node = graph; level < length - 1; ++level) {
node.next = { node.next = {
point: coordinates[level + 1] point: coordinates[level + 1]
}; };
@@ -96,20 +96,20 @@ function coordsToGraph(coordinates) {
} }
function graphToCoords(graph) { function graphToCoords(graph) {
var coordinates = [graph.point]; const coordinates = [graph.point];
for (var node = graph, i = 1; node.next; node = node.next, ++i) { for (let node = graph, i = 1; node.next; node = node.next, ++i) {
coordinates[i] = node.next.point; coordinates[i] = node.next.point;
} }
return coordinates; return coordinates;
} }
var depthInput = document.getElementById('depth'); const depthInput = document.getElementById('depth');
function update() { function update() {
makeFractal(Number(depthInput.value)); makeFractal(Number(depthInput.value));
} }
var updateTimer; let updateTimer;
/** /**

View File

@@ -8,7 +8,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import BingMaps from '../src/ol/source/BingMaps.js'; import BingMaps from '../src/ol/source/BingMaps.js';
var map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([
new FullScreen() new FullScreen()
]), ]),

View File

@@ -6,12 +6,12 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var view = new View({ const view = new View({
center: [-9101767, 2822912], center: [-9101767, 2822912],
zoom: 14 zoom: 14
}); });
var map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([
new FullScreen({ new FullScreen({
source: 'fullscreen' source: 'fullscreen'

View File

@@ -6,12 +6,12 @@ import TileLayer from '../src/ol/layer/Tile.js';
import BingMaps from '../src/ol/source/BingMaps.js'; import BingMaps from '../src/ol/source/BingMaps.js';
var view = new View({ const view = new View({
center: [-9101767, 2822912], center: [-9101767, 2822912],
zoom: 14 zoom: 14
}); });
var map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([
new FullScreen() new FullScreen()
]), ]),

View File

@@ -9,11 +9,11 @@ import VectorTileLayer from '../src/ol/layer/VectorTile.js';
import Projection from '../src/ol/proj/Projection.js'; import Projection from '../src/ol/proj/Projection.js';
var replacer = function(key, value) { const replacer = function(key, value) {
if (value.geometry) { if (value.geometry) {
var type; let type;
var rawType = value.type; const rawType = value.type;
var geometry = value.geometry; let geometry = value.geometry;
if (rawType === 1) { if (rawType === 1) {
type = 'MultiPoint'; type = 'MultiPoint';
@@ -48,12 +48,12 @@ var replacer = function(key, value) {
} }
}; };
var tilePixels = new Projection({ const tilePixels = new Projection({
code: 'TILE_PIXELS', code: 'TILE_PIXELS',
units: 'tile-pixels' units: 'tile-pixels'
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() 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) { fetch(url).then(function(response) {
return response.json(); return response.json();
}).then(function(json) { }).then(function(json) {
var tileIndex = geojsonvt(json, { const tileIndex = geojsonvt(json, {
extent: 4096, extent: 4096,
debug: 1 debug: 1
}); });
var vectorSource = new VectorTileSource({ const vectorSource = new VectorTileSource({
format: new GeoJSON(), format: new GeoJSON(),
tileLoadFunction: function(tile) { tileLoadFunction: function(tile) {
var format = tile.getFormat(); const format = tile.getFormat();
var tileCoord = tile.getTileCoord(); const tileCoord = tile.getTileCoord();
var data = tileIndex.getTile(tileCoord[0], tileCoord[1], -tileCoord[2] - 1); const data = tileIndex.getTile(tileCoord[0], tileCoord[1], -tileCoord[2] - 1);
var features = format.readFeatures( const features = format.readFeatures(
JSON.stringify({ JSON.stringify({
type: 'FeatureCollection', type: 'FeatureCollection',
features: data ? data.features : [] features: data ? data.features : []
}, replacer)); }, replacer));
tile.setLoader(function() { tile.setLoader(function() {
tile.setFeatures(features); tile.setFeatures(features);
tile.setProjection(tilePixels); tile.setProjection(tilePixels);
@@ -93,7 +93,7 @@ fetch(url).then(function(response) {
}, },
url: 'data:' // arbitrary url, we don't use it in the tileLoadFunction url: 'data:' // arbitrary url, we don't use it in the tileLoadFunction
}); });
var vectorLayer = new VectorTileLayer({ const vectorLayer = new VectorTileLayer({
source: vectorSource source: vectorSource
}); });
map.addLayer(vectorLayer); map.addLayer(vectorLayer);

View File

@@ -14,13 +14,13 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var image = new CircleStyle({ const image = new CircleStyle({
radius: 5, radius: 5,
fill: null, fill: null,
stroke: new Stroke({color: 'red', width: 1}) stroke: new Stroke({color: 'red', width: 1})
}); });
var styles = { const styles = {
'Point': new Style({ 'Point': new Style({
image: image image: image
}), }),
@@ -85,11 +85,11 @@ var styles = {
}) })
}; };
var styleFunction = function(feature) { const styleFunction = function(feature) {
return styles[feature.getGeometry().getType()]; return styles[feature.getGeometry().getType()];
}; };
var geojsonObject = { const geojsonObject = {
'type': 'FeatureCollection', 'type': 'FeatureCollection',
'crs': { 'crs': {
'type': 'name', 'type': 'name',
@@ -160,18 +160,18 @@ var geojsonObject = {
}] }]
}; };
var vectorSource = new VectorSource({ const vectorSource = new VectorSource({
features: (new GeoJSON()).readFeatures(geojsonObject) features: (new GeoJSON()).readFeatures(geojsonObject)
}); });
vectorSource.addFeature(new Feature(new Circle([5e6, 7e6], 1e6))); vectorSource.addFeature(new Feature(new Circle([5e6, 7e6], 1e6)));
var vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: vectorSource, source: vectorSource,
style: styleFunction style: styleFunction
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()

View File

@@ -9,13 +9,13 @@ import {fromLonLat} from '../src/ol/proj.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
// creating the view // creating the view
var view = new View({ const view = new View({
center: fromLonLat([5.8713, 45.6452]), center: fromLonLat([5.8713, 45.6452]),
zoom: 19 zoom: 19
}); });
// creating the map // creating the map
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -31,8 +31,8 @@ var map = new Map({
}); });
// Geolocation marker // Geolocation marker
var markerEl = document.getElementById('geolocation_marker'); const markerEl = document.getElementById('geolocation_marker');
var marker = new Overlay({ const marker = new Overlay({
positioning: 'center-center', positioning: 'center-center',
element: markerEl, element: markerEl,
stopEvent: false stopEvent: false
@@ -42,11 +42,11 @@ map.addOverlay(marker);
// LineString to store the different geolocation positions. This LineString // LineString to store the different geolocation positions. This LineString
// is time aware. // is time aware.
// The Z dimension is actually used to store the rotation (heading). // The Z dimension is actually used to store the rotation (heading).
var positions = new LineString([], const positions = new LineString([],
/** @type {ol.geom.GeometryLayout} */ ('XYZM')); /** @type {ol.geom.GeometryLayout} */ ('XYZM'));
// Geolocation Control // Geolocation Control
var geolocation = new Geolocation({ const geolocation = new Geolocation({
projection: view.getProjection(), projection: view.getProjection(),
trackingOptions: { trackingOptions: {
maximumAge: 10000, 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 // Listen to position changes
geolocation.on('change', function() { geolocation.on('change', function() {
var position = geolocation.getPosition(); const position = geolocation.getPosition();
var accuracy = geolocation.getAccuracy(); const accuracy = geolocation.getAccuracy();
var heading = geolocation.getHeading() || 0; const heading = geolocation.getHeading() || 0;
var speed = geolocation.getSpeed() || 0; const speed = geolocation.getSpeed() || 0;
var m = Date.now(); const m = Date.now();
addPosition(position, heading, m, speed); addPosition(position, heading, m, speed);
var coords = positions.getCoordinates(); const coords = positions.getCoordinates();
var len = coords.length; const len = coords.length;
if (len >= 2) { if (len >= 2) {
deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1); deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1);
} }
var html = [ const html = [
'Position: ' + position[0].toFixed(2) + ', ' + position[1].toFixed(2), 'Position: ' + position[0].toFixed(2) + ', ' + position[1].toFixed(2),
'Accuracy: ' + accuracy, 'Accuracy: ' + accuracy,
'Heading: ' + Math.round(radToDeg(heading)) + '&deg;', 'Heading: ' + Math.round(radToDeg(heading)) + '&deg;',
@@ -102,17 +102,17 @@ function mod(n) {
} }
function addPosition(position, heading, m, speed) { function addPosition(position, heading, m, speed) {
var x = position[0]; const x = position[0];
var y = position[1]; const y = position[1];
var fCoords = positions.getCoordinates(); const fCoords = positions.getCoordinates();
var previous = fCoords[fCoords.length - 1]; const previous = fCoords[fCoords.length - 1];
var prevHeading = previous && previous[2]; const prevHeading = previous && previous[2];
if (prevHeading) { if (prevHeading) {
var headingDiff = heading - mod(prevHeading); let headingDiff = heading - mod(prevHeading);
// force the rotation change to be less than 180° // force the rotation change to be less than 180°
if (Math.abs(headingDiff) > Math.PI) { 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)); headingDiff = -sign * (2 * Math.PI - Math.abs(headingDiff));
} }
heading = prevHeading + 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 // recenters the view by putting the given coordinates at 3/4 from the top or
// the screen // the screen
function getCenterWithHeading(position, rotation, resolution) { function getCenterWithHeading(position, rotation, resolution) {
var size = map.getSize(); const size = map.getSize();
var height = size[1]; const height = size[1];
return [ return [
position[0] - Math.sin(rotation) * height * resolution * 1 / 4, 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() { function updateView() {
// use sampling period to get a smooth transition // 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); m = Math.max(m, previousM);
previousM = m; previousM = m;
// interpolate position along positions LineString // interpolate position along positions LineString
var c = positions.getCoordinateAtM(m, true); const c = positions.getCoordinateAtM(m, true);
if (c) { if (c) {
view.setCenter(getCenterWithHeading(c, -c[2], view.getResolution())); view.setCenter(getCenterWithHeading(c, -c[2], view.getResolution()));
view.setRotation(-c[2]); view.setRotation(-c[2]);
@@ -158,7 +158,7 @@ function updateView() {
} }
// geolocate device // geolocate device
var geolocateBtn = document.getElementById('geolocate'); const geolocateBtn = document.getElementById('geolocate');
geolocateBtn.addEventListener('click', function() { geolocateBtn.addEventListener('click', function() {
geolocation.setTracking(true); // Start position tracking geolocation.setTracking(true); // Start position tracking
@@ -169,8 +169,8 @@ geolocateBtn.addEventListener('click', function() {
}, false); }, false);
// simulate device move // simulate device move
var simulationData; let simulationData;
var client = new XMLHttpRequest(); const client = new XMLHttpRequest();
client.open('GET', 'data/geolocation-orientation.json'); client.open('GET', 'data/geolocation-orientation.json');
@@ -182,20 +182,20 @@ client.onload = function() {
}; };
client.send(); client.send();
var simulateBtn = document.getElementById('simulate'); const simulateBtn = document.getElementById('simulate');
simulateBtn.addEventListener('click', function() { simulateBtn.addEventListener('click', function() {
var coordinates = simulationData; const coordinates = simulationData;
var first = coordinates.shift(); const first = coordinates.shift();
simulatePositionChange(first); simulatePositionChange(first);
var prevDate = first.timestamp; let prevDate = first.timestamp;
function geolocate() { function geolocate() {
var position = coordinates.shift(); const position = coordinates.shift();
if (!position) { if (!position) {
return; return;
} }
var newDate = position.timestamp; const newDate = position.timestamp;
simulatePositionChange(position); simulatePositionChange(position);
window.setTimeout(function() { window.setTimeout(function() {
prevDate = newDate; prevDate = newDate;
@@ -211,10 +211,10 @@ simulateBtn.addEventListener('click', function() {
}, false); }, false);
function simulatePositionChange(position) { function simulatePositionChange(position) {
var coords = position.coords; const coords = position.coords;
geolocation.set('accuracy', coords.accuracy); geolocation.set('accuracy', coords.accuracy);
geolocation.set('heading', degToRad(coords.heading)); 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('position', projectedPosition);
geolocation.set('speed', coords.speed); geolocation.set('speed', coords.speed);
geolocation.changed(); geolocation.changed();

View File

@@ -13,12 +13,12 @@ import Fill from '../src/ol/style/Fill.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -33,7 +33,7 @@ var map = new Map({
view: view view: view
}); });
var geolocation = new Geolocation({ const geolocation = new Geolocation({
projection: view.getProjection() projection: view.getProjection()
}); });
@@ -56,17 +56,17 @@ geolocation.on('change', function() {
// handle geolocation error. // handle geolocation error.
geolocation.on('error', function(error) { geolocation.on('error', function(error) {
var info = document.getElementById('info'); const info = document.getElementById('info');
info.innerHTML = error.message; info.innerHTML = error.message;
info.style.display = ''; info.style.display = '';
}); });
var accuracyFeature = new Feature(); const accuracyFeature = new Feature();
geolocation.on('change:accuracyGeometry', function() { geolocation.on('change:accuracyGeometry', function() {
accuracyFeature.setGeometry(geolocation.getAccuracyGeometry()); accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
}); });
var positionFeature = new Feature(); const positionFeature = new Feature();
positionFeature.setStyle(new Style({ positionFeature.setStyle(new Style({
image: new CircleStyle({ image: new CircleStyle({
radius: 6, radius: 6,
@@ -81,7 +81,7 @@ positionFeature.setStyle(new Style({
})); }));
geolocation.on('change:position', function() { geolocation.on('change:position', function() {
var coordinates = geolocation.getPosition(); const coordinates = geolocation.getPosition();
positionFeature.setGeometry(coordinates ? positionFeature.setGeometry(coordinates ?
new Point(coordinates) : null); new Point(coordinates) : null);
}); });

View File

@@ -4,23 +4,23 @@ import ImageLayer from '../src/ol/layer/Image.js';
import ImageWMS from '../src/ol/source/ImageWMS.js'; import ImageWMS from '../src/ol/source/ImageWMS.js';
var wmsSource = new ImageWMS({ const wmsSource = new ImageWMS({
url: 'https://ahocevar.com/geoserver/wms', url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'ne:ne'}, params: {'LAYERS': 'ne:ne'},
serverType: 'geoserver', serverType: 'geoserver',
crossOrigin: 'anonymous' crossOrigin: 'anonymous'
}); });
var wmsLayer = new ImageLayer({ const wmsLayer = new ImageLayer({
source: wmsSource source: wmsSource
}); });
var view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1
}); });
var map = new Map({ const map = new Map({
layers: [wmsLayer], layers: [wmsLayer],
target: 'map', target: 'map',
view: view view: view
@@ -28,10 +28,10 @@ var map = new Map({
map.on('singleclick', function(evt) { map.on('singleclick', function(evt) {
document.getElementById('info').innerHTML = ''; document.getElementById('info').innerHTML = '';
var viewResolution = /** @type {number} */ (view.getResolution()); const viewResolution = /** @type {number} */ (view.getResolution());
var url = wmsSource.getGetFeatureInfoUrl( const url = wmsSource.getGetFeatureInfoUrl(
evt.coordinate, viewResolution, 'EPSG:3857', evt.coordinate, viewResolution, 'EPSG:3857',
{'INFO_FORMAT': 'text/html'}); {'INFO_FORMAT': 'text/html'});
if (url) { if (url) {
document.getElementById('info').innerHTML = document.getElementById('info').innerHTML =
'<iframe seamless src="' + url + '"></iframe>'; '<iframe seamless src="' + url + '"></iframe>';
@@ -42,8 +42,8 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
var pixel = map.getEventPixel(evt.originalEvent); const pixel = map.getEventPixel(evt.originalEvent);
var hit = map.forEachLayerAtPixel(pixel, function() { const hit = map.forEachLayerAtPixel(pixel, function() {
return true; return true;
}); });
map.getTargetElement().style.cursor = hit ? 'pointer' : ''; map.getTargetElement().style.cursor = hit ? 'pointer' : '';

View File

@@ -5,17 +5,17 @@ fetch('data/wmsgetfeatureinfo/osm-restaurant-hotel.xml').then(function(response)
}).then(function(response) { }).then(function(response) {
// this is the standard way to read the features // 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(); document.getElementById('all').innerText = allFeatures.length.toString();
// when specifying the 'layers' options, only the features of those // when specifying the 'layers' options, only the features of those
// layers are returned by the format // layers are returned by the format
var hotelFeatures = new WMSGetFeatureInfo({ const hotelFeatures = new WMSGetFeatureInfo({
layers: ['hotel'] layers: ['hotel']
}).readFeatures(response); }).readFeatures(response);
document.getElementById('hotel').innerText = hotelFeatures.length.toString(); document.getElementById('hotel').innerText = hotelFeatures.length.toString();
var restaurantFeatures = new WMSGetFeatureInfo({ const restaurantFeatures = new WMSGetFeatureInfo({
layers: ['restaurant'] layers: ['restaurant']
}).readFeatures(response); }).readFeatures(response);
document.getElementById('restaurant').innerText = restaurantFeatures.length.toString(); document.getElementById('restaurant').innerText = restaurantFeatures.length.toString();

View File

@@ -4,23 +4,23 @@ import TileLayer from '../src/ol/layer/Tile.js';
import TileWMS from '../src/ol/source/TileWMS.js'; import TileWMS from '../src/ol/source/TileWMS.js';
var wmsSource = new TileWMS({ const wmsSource = new TileWMS({
url: 'https://ahocevar.com/geoserver/wms', url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'ne:ne', 'TILED': true}, params: {'LAYERS': 'ne:ne', 'TILED': true},
serverType: 'geoserver', serverType: 'geoserver',
crossOrigin: 'anonymous' crossOrigin: 'anonymous'
}); });
var wmsLayer = new TileLayer({ const wmsLayer = new TileLayer({
source: wmsSource source: wmsSource
}); });
var view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1
}); });
var map = new Map({ const map = new Map({
layers: [wmsLayer], layers: [wmsLayer],
target: 'map', target: 'map',
view: view view: view
@@ -28,10 +28,10 @@ var map = new Map({
map.on('singleclick', function(evt) { map.on('singleclick', function(evt) {
document.getElementById('info').innerHTML = ''; document.getElementById('info').innerHTML = '';
var viewResolution = /** @type {number} */ (view.getResolution()); const viewResolution = /** @type {number} */ (view.getResolution());
var url = wmsSource.getGetFeatureInfoUrl( const url = wmsSource.getGetFeatureInfoUrl(
evt.coordinate, viewResolution, 'EPSG:3857', evt.coordinate, viewResolution, 'EPSG:3857',
{'INFO_FORMAT': 'text/html'}); {'INFO_FORMAT': 'text/html'});
if (url) { if (url) {
document.getElementById('info').innerHTML = document.getElementById('info').innerHTML =
'<iframe seamless src="' + url + '"></iframe>'; '<iframe seamless src="' + url + '"></iframe>';
@@ -42,8 +42,8 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
var pixel = map.getEventPixel(evt.originalEvent); const pixel = map.getEventPixel(evt.originalEvent);
var hit = map.forEachLayerAtPixel(pixel, function() { const hit = map.forEachLayerAtPixel(pixel, function() {
return true; return true;
}); });
map.getTargetElement().style.cursor = hit ? 'pointer' : ''; map.getTargetElement().style.cursor = hit ? 'pointer' : '';

View File

@@ -10,14 +10,14 @@ import Fill from '../src/ol/style/Fill.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new BingMaps({ source: new BingMaps({
imagerySet: 'Aerial', imagerySet: 'Aerial',
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'
}) })
}); });
var style = { const style = {
'Point': new Style({ 'Point': new Style({
image: new CircleStyle({ image: new CircleStyle({
fill: new Fill({ fill: new Fill({
@@ -44,7 +44,7 @@ var style = {
}) })
}; };
var vector = new VectorLayer({ const vector = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
url: 'data/gpx/fells_loop.gpx', url: 'data/gpx/fells_loop.gpx',
format: new GPX() format: new GPX()
@@ -54,7 +54,7 @@ var vector = new VectorLayer({
} }
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new View({
@@ -63,14 +63,14 @@ var map = new Map({
}) })
}); });
var displayFeatureInfo = function(pixel) { const displayFeatureInfo = function(pixel) {
var features = []; const features = [];
map.forEachFeatureAtPixel(pixel, function(feature) { map.forEachFeatureAtPixel(pixel, function(feature) {
features.push(feature); features.push(feature);
}); });
if (features.length > 0) { if (features.length > 0) {
var info = []; const info = [];
var i, ii; let i, ii;
for (i = 0, ii = features.length; i < ii; ++i) { for (i = 0, ii = features.length; i < ii; ++i) {
info.push(features[i].get('desc')); info.push(features[i].get('desc'));
} }
@@ -86,7 +86,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
var pixel = map.getEventPixel(evt.originalEvent); const pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel); displayFeatureInfo(pixel);
}); });

View File

@@ -7,7 +7,7 @@ import OSM from '../src/ol/source/OSM.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM({ source: new OSM({
@@ -23,7 +23,7 @@ var map = new Map({
}); });
// Create the graticule component // Create the graticule component
var graticule = new Graticule({ const graticule = new Graticule({
// the style to use for the lines, optional. // the style to use for the lines, optional.
strokeStyle: new Stroke({ strokeStyle: new Stroke({
color: 'rgba(255,120,0,0.9)', color: 'rgba(255,120,0,0.9)',

View File

@@ -6,10 +6,10 @@ import TileLayer from '../src/ol/layer/Tile.js';
import Stamen from '../src/ol/source/Stamen.js'; import Stamen from '../src/ol/source/Stamen.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var blur = document.getElementById('blur'); const blur = document.getElementById('blur');
var radius = document.getElementById('radius'); const radius = document.getElementById('radius');
var vector = new HeatmapLayer({ const vector = new HeatmapLayer({
source: new VectorSource({ source: new VectorSource({
url: 'data/kml/2012_Earthquakes_Mag5.kml', url: 'data/kml/2012_Earthquakes_Mag5.kml',
format: new 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 // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a
// standards-violating <magnitude> tag in each Placemark. We extract it from // standards-violating <magnitude> tag in each Placemark. We extract it from
// the Placemark's name instead. // the Placemark's name instead.
var name = event.feature.get('name'); const name = event.feature.get('name');
var magnitude = parseFloat(name.substr(2)); const magnitude = parseFloat(name.substr(2));
event.feature.set('weight', magnitude - 5); event.feature.set('weight', magnitude - 5);
}); });
var raster = new TileLayer({ const raster = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner'
}) })
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new View({

View File

@@ -3,9 +3,9 @@ import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import XYZ from '../src/ol/source/XYZ.js'; import XYZ from '../src/ol/source/XYZ.js';
var appId = 'kDm0Jq1K4Ak7Bwtn8uvk'; const appId = 'kDm0Jq1K4Ak7Bwtn8uvk';
var appCode = 'xnmvc4dKZrDfGlvQHXSvwQ'; const appCode = 'xnmvc4dKZrDfGlvQHXSvwQ';
var hereLayers = [ const hereLayers = [
{ {
base: 'base', base: 'base',
type: 'maptile', type: 'maptile',
@@ -49,13 +49,13 @@ var hereLayers = [
app_code: appCode 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' + '/{type}/2.1/maptile/newest/{scheme}/{z}/{x}/{y}/256/png' +
'?app_id={app_id}&app_code={app_code}'; '?app_id={app_id}&app_code={app_code}';
var layers = []; const layers = [];
var i, ii; let i, ii;
for (i = 0, ii = hereLayers.length; i < ii; ++i) { for (i = 0, ii = hereLayers.length; i < ii; ++i) {
var layerDesc = hereLayers[i]; const layerDesc = hereLayers[i];
layers.push(new TileLayer({ layers.push(new TileLayer({
visible: false, visible: false,
preload: Infinity, 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, layers: layers,
// Improve user experience by loading tiles while dragging/zooming. Will make // Improve user experience by loading tiles while dragging/zooming. Will make
// zooming choppy on mobile or slow devices. // zooming choppy on mobile or slow devices.
@@ -81,17 +81,17 @@ var map = new Map({
function createUrl(tpl, layerDesc) { function createUrl(tpl, layerDesc) {
return tpl return tpl
.replace('{base}', layerDesc.base) .replace('{base}', layerDesc.base)
.replace('{type}', layerDesc.type) .replace('{type}', layerDesc.type)
.replace('{scheme}', layerDesc.scheme) .replace('{scheme}', layerDesc.scheme)
.replace('{app_id}', layerDesc.app_id) .replace('{app_id}', layerDesc.app_id)
.replace('{app_code}', layerDesc.app_code); .replace('{app_code}', layerDesc.app_code);
} }
var select = document.getElementById('layer-select'); const select = document.getElementById('layer-select');
function onChange() { function onChange() {
var scheme = select.value; const scheme = select.value;
for (var i = 0, ii = layers.length; i < ii; ++i) { for (let i = 0, ii = layers.length; i < ii; ++i) {
layers[i].setVisible(hereLayers[i].scheme === scheme); layers[i].setVisible(hereLayers[i].scheme === scheme);
} }
} }

View File

@@ -9,27 +9,27 @@ import LineString from '../src/ol/geom/LineString.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM()
}); });
var style = new Style({ const style = new Style({
stroke: new Stroke({ stroke: new Stroke({
color: 'black', color: 'black',
width: 1 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({ source: new VectorSource({
features: [feature] features: [feature]
}), }),
style: style style: style
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ 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) { map.on('singleclick', function(e) {
var hit = false; let hit = false;
map.forEachFeatureAtPixel(e.pixel, function() { map.forEachFeatureAtPixel(e.pixel, function() {
hit = true; hit = true;
}, { }, {
@@ -59,16 +59,16 @@ map.on('singleclick', function(e) {
feature.changed(); feature.changed();
}); });
var selectHitToleranceElement = document.getElementById('hitTolerance'); const selectHitToleranceElement = document.getElementById('hitTolerance');
var circleCanvas = document.getElementById('circle'); const circleCanvas = document.getElementById('circle');
var changeHitTolerance = function() { const changeHitTolerance = function() {
hitTolerance = parseInt(selectHitToleranceElement.value, 10); hitTolerance = parseInt(selectHitToleranceElement.value, 10);
var size = 2 * hitTolerance + 2; const size = 2 * hitTolerance + 2;
circleCanvas.width = size; circleCanvas.width = size;
circleCanvas.height = size; circleCanvas.height = size;
var ctx = circleCanvas.getContext('2d'); const ctx = circleCanvas.getContext('2d');
ctx.clearRect(0, 0, size, size); ctx.clearRect(0, 0, size, size);
ctx.beginPath(); ctx.beginPath();
ctx.arc(hitTolerance + 1, hitTolerance + 1, hitTolerance + 0.5, 0, 2 * Math.PI); ctx.arc(hitTolerance + 1, hitTolerance + 1, hitTolerance + 0.5, 0, 2 * Math.PI);

View File

@@ -11,15 +11,15 @@ import Icon from '../src/ol/style/Icon.js';
import Style from '../src/ol/style/Style.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])) geometry: new Point(fromLonLat([12.5, 41.9]))
}); });
var london = new Feature({ const london = new Feature({
geometry: new Point(fromLonLat([-0.12755, 51.507222])) geometry: new Point(fromLonLat([-0.12755, 51.507222]))
}); });
var madrid = new Feature({ const madrid = new Feature({
geometry: new Point(fromLonLat([-3.683333, 40.4])) 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] features: [rome, london, madrid]
}); });
var vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: vectorSource source: vectorSource
}); });
var rasterLayer = new TileLayer({ const rasterLayer = new TileLayer({
source: new TileJSON({ source: new TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure', url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
crossOrigin: '' crossOrigin: ''
}) })
}); });
var map = new Map({ const map = new Map({
layers: [rasterLayer, vectorLayer], layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new View({

View File

@@ -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)); iconFeature.set('style', createStyle('data/icon.png', undefined));
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new Stamen({layer: 'watercolor'}) source: new Stamen({layer: 'watercolor'})
@@ -45,19 +45,19 @@ var map = new Map({
}) })
}); });
var selectStyle = {}; const selectStyle = {};
var select = new Select({ const select = new Select({
style: function(feature) { style: function(feature) {
var image = feature.get('style').getImage().getImage(); const image = feature.get('style').getImage().getImage();
if (!selectStyle[image.src]) { if (!selectStyle[image.src]) {
var canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
var context = canvas.getContext('2d'); const context = canvas.getContext('2d');
canvas.width = image.width; canvas.width = image.width;
canvas.height = image.height; canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height); context.drawImage(image, 0, 0, image.width, image.height);
var imageData = context.getImageData(0, 0, canvas.width, canvas.height); const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data; const data = imageData.data;
for (var i = 0, ii = data.length; i < ii; i = i + (i % 4 == 2 ? 2 : 1)) { for (let i = 0, ii = data.length; i < ii; i = i + (i % 4 == 2 ? 2 : 1)) {
data[i] = 255 - data[i]; data[i] = 255 - data[i];
} }
context.putImageData(imageData, 0, 0); context.putImageData(imageData, 0, 0);

View File

@@ -8,7 +8,7 @@ import Icon from '../src/ol/style/Icon.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var iconInfo = [{ const iconInfo = [{
offset: [0, 0], offset: [0, 0],
opacity: 1.0, opacity: 1.0,
rotateWithView: true, rotateWithView: true,
@@ -38,12 +38,12 @@ var iconInfo = [{
size: [44, 44] size: [44, 44]
}]; }];
var i; let i;
var iconCount = iconInfo.length; const iconCount = iconInfo.length;
var icons = new Array(iconCount); const icons = new Array(iconCount);
for (i = 0; i < iconCount; ++i) { for (i = 0; i < iconCount; ++i) {
var info = iconInfo[i]; const info = iconInfo[i];
icons[i] = new Icon({ icons[i] = new Icon({
offset: info.offset, offset: info.offset,
opacity: info.opacity, opacity: info.opacity,
@@ -56,30 +56,30 @@ for (i = 0; i < iconCount; ++i) {
}); });
} }
var featureCount = 50000; const featureCount = 50000;
var features = new Array(featureCount); const features = new Array(featureCount);
var feature, geometry; let feature, geometry;
var e = 25000000; const e = 25000000;
for (i = 0; i < featureCount; ++i) { for (i = 0; i < featureCount; ++i) {
geometry = new Point( 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 = new Feature(geometry);
feature.setStyle( feature.setStyle(
new Style({ new Style({
image: icons[i % (iconCount - 1)] image: icons[i % (iconCount - 1)]
}) })
); );
features[i] = feature; features[i] = feature;
} }
var vectorSource = new VectorSource({ const vectorSource = new VectorSource({
features: features features: features
}); });
var vector = new VectorLayer({ const vector = new VectorLayer({
source: vectorSource source: vectorSource
}); });
var map = new Map({ const map = new Map({
renderer: /** @type {Array<ol.renderer.Type>} */ (['webgl', 'canvas']), renderer: /** @type {Array<ol.renderer.Type>} */ (['webgl', 'canvas']),
layers: [vector], layers: [vector],
target: document.getElementById('map'), target: document.getElementById('map'),
@@ -89,9 +89,9 @@ var map = new Map({
}) })
}); });
var overlayFeatures = []; const overlayFeatures = [];
for (i = 0; i < featureCount; i += 30) { for (i = 0; i < featureCount; i += 30) {
var clone = features[i].clone(); const clone = features[i].clone();
clone.setStyle(null); clone.setStyle(null);
overlayFeatures.push(clone); overlayFeatures.push(clone);
} }
@@ -107,12 +107,12 @@ new VectorLayer({
}); });
map.on('click', function(evt) { map.on('click', function(evt) {
var info = document.getElementById('info'); const info = document.getElementById('info');
info.innerHTML = info.innerHTML =
'Hold on a second, while I catch those butterflies for you ...'; 'Hold on a second, while I catch those butterflies for you ...';
window.setTimeout(function() { window.setTimeout(function() {
var features = []; const features = [];
map.forEachFeatureAtPixel(evt.pixel, function(feature) { map.forEachFeatureAtPixel(evt.pixel, function(feature) {
features.push(feature); features.push(feature);
return false; return false;
@@ -132,7 +132,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
var pixel = map.getEventPixel(evt.originalEvent); const pixel = map.getEventPixel(evt.originalEvent);
var hit = map.hasFeatureAtPixel(pixel); const hit = map.hasFeatureAtPixel(pixel);
map.getTarget().style.cursor = hit ? 'pointer' : ''; map.getTarget().style.cursor = hit ? 'pointer' : '';
}); });

View File

@@ -11,14 +11,14 @@ import Icon from '../src/ol/style/Icon.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var iconFeature = new Feature({ const iconFeature = new Feature({
geometry: new Point([0, 0]), geometry: new Point([0, 0]),
name: 'Null Island', name: 'Null Island',
population: 4000, population: 4000,
rainfall: 500 rainfall: 500
}); });
var iconStyle = new Style({ const iconStyle = new Style({
image: new Icon(/** @type {olx.style.IconOptions} */ ({ image: new Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 46], anchor: [0.5, 46],
anchorXUnits: 'fraction', anchorXUnits: 'fraction',
@@ -29,22 +29,22 @@ var iconStyle = new Style({
iconFeature.setStyle(iconStyle); iconFeature.setStyle(iconStyle);
var vectorSource = new VectorSource({ const vectorSource = new VectorSource({
features: [iconFeature] features: [iconFeature]
}); });
var vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: vectorSource source: vectorSource
}); });
var rasterLayer = new TileLayer({ const rasterLayer = new TileLayer({
source: new TileJSON({ source: new TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure', url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
crossOrigin: '' crossOrigin: ''
}) })
}); });
var map = new Map({ const map = new Map({
layers: [rasterLayer, vectorLayer], layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ 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, element: element,
positioning: 'bottom-center', positioning: 'bottom-center',
stopEvent: false, stopEvent: false,
@@ -65,12 +65,12 @@ map.addOverlay(popup);
// display popup on click // display popup on click
map.on('click', function(evt) { map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel, const feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) { function(feature) {
return feature; return feature;
}); });
if (feature) { if (feature) {
var coordinates = feature.getGeometry().getCoordinates(); const coordinates = feature.getGeometry().getCoordinates();
popup.setPosition(coordinates); popup.setPosition(coordinates);
$(element).popover({ $(element).popover({
'placement': 'top', 'placement': 'top',
@@ -89,7 +89,7 @@ map.on('pointermove', function(e) {
$(element).popover('destroy'); $(element).popover('destroy');
return; return;
} }
var pixel = map.getEventPixel(e.originalEvent); const pixel = map.getEventPixel(e.originalEvent);
var hit = map.hasFeatureAtPixel(pixel); const hit = map.hasFeatureAtPixel(pixel);
map.getTarget().style.cursor = hit ? 'pointer' : ''; map.getTarget().style.cursor = hit ? 'pointer' : '';
}); });

View File

@@ -15,7 +15,7 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var colors = { const colors = {
'Clement Latour': 'rgba(0, 0, 255, 0.7)', 'Clement Latour': 'rgba(0, 0, 255, 0.7)',
'Damien de Baesnt': 'rgba(0, 215, 255, 0.7)', 'Damien de Baesnt': 'rgba(0, 215, 255, 0.7)',
'Sylvain Dhonneur': 'rgba(0, 165, 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)' 'Ulrich Prinz': 'rgba(0, 215, 255, 0.7)'
}; };
var styleCache = {}; const styleCache = {};
var styleFunction = function(feature) { const styleFunction = function(feature) {
var color = colors[feature.get('PLT')]; const color = colors[feature.get('PLT')];
var style = styleCache[color]; let style = styleCache[color];
if (!style) { if (!style) {
style = new Style({ style = new Style({
stroke: new Stroke({ stroke: new Stroke({
@@ -39,9 +39,9 @@ var styleFunction = function(feature) {
return style; return style;
}; };
var vectorSource = new VectorSource(); const vectorSource = new VectorSource();
var igcUrls = [ const igcUrls = [
'data/igc/Clement-Latour.igc', 'data/igc/Clement-Latour.igc',
'data/igc/Damien-de-Baenst.igc', 'data/igc/Damien-de-Baenst.igc',
'data/igc/Sylvain-Dhonneur.igc', 'data/igc/Sylvain-Dhonneur.igc',
@@ -50,7 +50,7 @@ var igcUrls = [
]; ];
function get(url, callback) { function get(url, callback) {
var client = new XMLHttpRequest(); const client = new XMLHttpRequest();
client.open('GET', url); client.open('GET', url);
client.onload = function() { client.onload = function() {
callback(client.responseText); callback(client.responseText);
@@ -58,29 +58,29 @@ function get(url, callback) {
client.send(); client.send();
} }
var igcFormat = new IGC(); const igcFormat = new IGC();
for (var i = 0; i < igcUrls.length; ++i) { for (let i = 0; i < igcUrls.length; ++i) {
get(igcUrls[i], function(data) { get(igcUrls[i], function(data) {
var features = igcFormat.readFeatures(data, const features = igcFormat.readFeatures(data,
{featureProjection: 'EPSG:3857'}); {featureProjection: 'EPSG:3857'});
vectorSource.addFeatures(features); vectorSource.addFeatures(features);
}); });
} }
var time = { const time = {
start: Infinity, start: Infinity,
stop: -Infinity, stop: -Infinity,
duration: 0 duration: 0
}; };
vectorSource.on('addfeature', function(event) { 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.start = Math.min(time.start, geometry.getFirstCoordinate()[2]);
time.stop = Math.max(time.stop, geometry.getLastCoordinate()[2]); time.stop = Math.max(time.stop, geometry.getLastCoordinate()[2]);
time.duration = time.stop - time.start; time.duration = time.stop - time.start;
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM({ source: new OSM({
@@ -110,27 +110,27 @@ var map = new Map({
}); });
var point = null; let point = null;
var line = null; let line = null;
var displaySnap = function(coordinate) { const displaySnap = function(coordinate) {
var closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate); const closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate);
var info = document.getElementById('info'); const info = document.getElementById('info');
if (closestFeature === null) { if (closestFeature === null) {
point = null; point = null;
line = null; line = null;
info.innerHTML = '&nbsp;'; info.innerHTML = '&nbsp;';
} else { } else {
var geometry = closestFeature.getGeometry(); const geometry = closestFeature.getGeometry();
var closestPoint = geometry.getClosestPoint(coordinate); const closestPoint = geometry.getClosestPoint(coordinate);
if (point === null) { if (point === null) {
point = new Point(closestPoint); point = new Point(closestPoint);
} else { } else {
point.setCoordinates(closestPoint); point.setCoordinates(closestPoint);
} }
var date = new Date(closestPoint[2] * 1000); const date = new Date(closestPoint[2] * 1000);
info.innerHTML = info.innerHTML =
closestFeature.get('PLT') + ' (' + date.toUTCString() + ')'; closestFeature.get('PLT') + ' (' + date.toUTCString() + ')';
var coordinates = [coordinate, [closestPoint[0], closestPoint[1]]]; const coordinates = [coordinate, [closestPoint[0], closestPoint[1]]];
if (line === null) { if (line === null) {
line = new LineString(coordinates); line = new LineString(coordinates);
} else { } else {
@@ -144,7 +144,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
var coordinate = map.getEventCoordinate(evt.originalEvent); const coordinate = map.getEventCoordinate(evt.originalEvent);
displaySnap(coordinate); displaySnap(coordinate);
}); });
@@ -152,11 +152,11 @@ map.on('click', function(evt) {
displaySnap(evt.coordinate); displaySnap(evt.coordinate);
}); });
var stroke = new Stroke({ const stroke = new Stroke({
color: 'rgba(255,0,0,0.9)', color: 'rgba(255,0,0,0.9)',
width: 1 width: 1
}); });
var style = new Style({ const style = new Style({
stroke: stroke, stroke: stroke,
image: new CircleStyle({ image: new CircleStyle({
radius: 5, radius: 5,
@@ -165,7 +165,7 @@ var style = new Style({
}) })
}); });
map.on('postcompose', function(evt) { map.on('postcompose', function(evt) {
var vectorContext = evt.vectorContext; const vectorContext = evt.vectorContext;
vectorContext.setStyle(style); vectorContext.setStyle(style);
if (point !== null) { if (point !== null) {
vectorContext.drawGeometry(point); vectorContext.drawGeometry(point);
@@ -175,7 +175,7 @@ map.on('postcompose', function(evt) {
} }
}); });
var featureOverlay = new VectorLayer({ const featureOverlay = new VectorLayer({
source: new VectorSource(), source: new VectorSource(),
map: map, map: map,
style: new Style({ style: new Style({
@@ -189,12 +189,12 @@ var featureOverlay = new VectorLayer({
}); });
document.getElementById('time').addEventListener('input', function() { document.getElementById('time').addEventListener('input', function() {
var value = parseInt(this.value, 10) / 100; const value = parseInt(this.value, 10) / 100;
var m = time.start + (time.duration * value); const m = time.start + (time.duration * value);
vectorSource.forEachFeature(function(feature) { vectorSource.forEachFeature(function(feature) {
var geometry = /** @type {ol.geom.LineString} */ (feature.getGeometry()); const geometry = /** @type {ol.geom.LineString} */ (feature.getGeometry());
var coordinate = geometry.getCoordinateAtM(m, true); const coordinate = geometry.getCoordinateAtM(m, true);
var highlight = feature.get('highlight'); let highlight = feature.get('highlight');
if (highlight === undefined) { if (highlight === undefined) {
highlight = new Feature(new Point(coordinate)); highlight = new Feature(new Point(coordinate));
feature.set('highlight', highlight); feature.set('highlight', highlight);

View File

@@ -4,13 +4,13 @@ import TileLayer from '../src/ol/layer/Tile.js';
import {fromLonLat} from '../src/ol/proj.js'; import {fromLonLat} from '../src/ol/proj.js';
import BingMaps from '../src/ol/source/BingMaps.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'}) source: new BingMaps({key: key, imagerySet: 'Aerial'})
}); });
var map = new Map({ const map = new Map({
layers: [imagery], layers: [imagery],
target: 'map', target: 'map',
view: new View({ view: new View({
@@ -19,7 +19,7 @@ var map = new Map({
}) })
}); });
var kernels = { const kernels = {
none: [ none: [
0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0,
@@ -58,9 +58,9 @@ var kernels = {
}; };
function normalize(kernel) { function normalize(kernel) {
var len = kernel.length; const len = kernel.length;
var normal = new Array(len); const normal = new Array(len);
var i, sum = 0; let i, sum = 0;
for (i = 0; i < len; ++i) { for (i = 0; i < len; ++i) {
sum += kernel[i]; sum += kernel[i];
} }
@@ -76,8 +76,8 @@ function normalize(kernel) {
return normal; return normal;
} }
var select = document.getElementById('kernel'); const select = document.getElementById('kernel');
var selectedKernel = normalize(kernels[select.value]); let selectedKernel = normalize(kernels[select.value]);
/** /**
@@ -104,37 +104,37 @@ imagery.on('postcompose', function(event) {
* @param {Array.<number>} kernel Kernel. * @param {Array.<number>} kernel Kernel.
*/ */
function convolve(context, kernel) { function convolve(context, kernel) {
var canvas = context.canvas; const canvas = context.canvas;
var width = canvas.width; const width = canvas.width;
var height = canvas.height; const height = canvas.height;
var size = Math.sqrt(kernel.length); const size = Math.sqrt(kernel.length);
var half = Math.floor(size / 2); 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); const output = context.createImageData(width, height);
var outputData = output.data; const outputData = output.data;
for (var pixelY = 0; pixelY < height; ++pixelY) { for (let pixelY = 0; pixelY < height; ++pixelY) {
var pixelsAbove = pixelY * width; const pixelsAbove = pixelY * width;
for (var pixelX = 0; pixelX < width; ++pixelX) { for (let pixelX = 0; pixelX < width; ++pixelX) {
var r = 0, g = 0, b = 0, a = 0; let r = 0, g = 0, b = 0, a = 0;
for (var kernelY = 0; kernelY < size; ++kernelY) { for (let kernelY = 0; kernelY < size; ++kernelY) {
for (var kernelX = 0; kernelX < size; ++kernelX) { for (let kernelX = 0; kernelX < size; ++kernelX) {
var weight = kernel[kernelY * size + kernelX]; const weight = kernel[kernelY * size + kernelX];
var neighborY = Math.min( const neighborY = Math.min(
height - 1, Math.max(0, pixelY + kernelY - half)); height - 1, Math.max(0, pixelY + kernelY - half));
var neighborX = Math.min( const neighborX = Math.min(
width - 1, Math.max(0, pixelX + kernelX - half)); width - 1, Math.max(0, pixelX + kernelX - half));
var inputIndex = (neighborY * width + neighborX) * 4; const inputIndex = (neighborY * width + neighborX) * 4;
r += inputData[inputIndex] * weight; r += inputData[inputIndex] * weight;
g += inputData[inputIndex + 1] * weight; g += inputData[inputIndex + 1] * weight;
b += inputData[inputIndex + 2] * weight; b += inputData[inputIndex + 2] * weight;
a += inputData[inputIndex + 3] * weight; a += inputData[inputIndex + 3] * weight;
} }
} }
var outputIndex = (pixelsAbove + pixelX) * 4; const outputIndex = (pixelsAbove + pixelX) * 4;
outputData[outputIndex] = r; outputData[outputIndex] = r;
outputData[outputIndex + 1] = g; outputData[outputIndex + 1] = g;
outputData[outputIndex + 2] = b; outputData[outputIndex + 2] = b;

View File

@@ -32,7 +32,7 @@ Progress.prototype.addLoading = function() {
* Increment the count of loaded tiles. * Increment the count of loaded tiles.
*/ */
Progress.prototype.addLoaded = function() { Progress.prototype.addLoaded = function() {
var this_ = this; const this_ = this;
setTimeout(function() { setTimeout(function() {
++this_.loaded; ++this_.loaded;
this_.update(); this_.update();
@@ -44,12 +44,12 @@ Progress.prototype.addLoaded = function() {
* Update the progress bar. * Update the progress bar.
*/ */
Progress.prototype.update = function() { 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; this.el.style.width = width;
if (this.loading === this.loaded) { if (this.loading === this.loaded) {
this.loading = 0; this.loading = 0;
this.loaded = 0; this.loaded = 0;
var this_ = this; const this_ = this;
setTimeout(function() { setTimeout(function() {
this_.hide(); this_.hide();
}, 500); }, 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', url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'topp:states'}, params: {'LAYERS': 'topp:states'},
serverType: 'geoserver' serverType: 'geoserver'
@@ -94,7 +94,7 @@ source.on('imageloaderror', function() {
progress.addLoaded(); progress.addLoaded();
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new ImageLayer({source: source}) new ImageLayer({source: source})
], ],

View File

@@ -9,7 +9,7 @@ import Style from '../src/ol/style/Style.js';
import Text from '../src/ol/style/Text.js'; import Text from '../src/ol/style/Text.js';
var style = new Style({ const style = new Style({
fill: new Fill({ fill: new Fill({
color: 'rgba(255, 255, 255, 0.6)' color: 'rgba(255, 255, 255, 0.6)'
}), }),
@@ -20,7 +20,7 @@ var style = new Style({
text: new Text() text: new Text()
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new VectorLayer({ new VectorLayer({
renderMode: 'image', renderMode: 'image',
@@ -41,7 +41,7 @@ var map = new Map({
}) })
}); });
var featureOverlay = new VectorLayer({ const featureOverlay = new VectorLayer({
source: new VectorSource(), source: new VectorSource(),
map: map, map: map,
style: new Style({ style: new Style({
@@ -55,14 +55,14 @@ var featureOverlay = new VectorLayer({
}) })
}); });
var highlight; let highlight;
var displayFeatureInfo = function(pixel) { const displayFeatureInfo = function(pixel) {
var feature = map.forEachFeatureAtPixel(pixel, function(feature) { const feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature; return feature;
}); });
var info = document.getElementById('info'); const info = document.getElementById('info');
if (feature) { if (feature) {
info.innerHTML = feature.getId() + ': ' + feature.get('name'); info.innerHTML = feature.getId() + ': ' + feature.get('name');
} else { } else {
@@ -85,7 +85,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
var pixel = map.getEventPixel(evt.originalEvent); const pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel); displayFeatureInfo(pixel);
}); });

View File

@@ -10,22 +10,22 @@ import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.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) { fetch('data/geojson/roads-seoul.geojson').then(function(response) {
return response.json(); return response.json();
}).then(function(json) { }).then(function(json) {
var format = new GeoJSON(); const format = new GeoJSON();
var features = format.readFeatures(json, {featureProjection: 'EPSG:3857'}); 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++) { for (let i = 0; i < features.length; i++) {
var feature = features[i]; const feature = features[i];
// convert the OpenLayers geometry to a JSTS geometry // 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 // 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 // convert back from JSTS and replace the geometry on the feature
feature.setGeometry(parser.write(buffered)); feature.setGeometry(parser.write(buffered));
@@ -33,15 +33,15 @@ fetch('data/geojson/roads-seoul.geojson').then(function(response) {
source.addFeatures(features); source.addFeatures(features);
}); });
var vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: source source: source
}); });
var rasterLayer = new TileLayer({ const rasterLayer = new TileLayer({
source: new OSM() source: new OSM()
}); });
var map = new Map({ const map = new Map({
layers: [rasterLayer, vectorLayer], layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new View({

View File

@@ -11,15 +11,15 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var styleCache = {}; const styleCache = {};
var styleFunction = function(feature) { const styleFunction = function(feature) {
// 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a
// standards-violating <magnitude> tag in each Placemark. We extract it from // standards-violating <magnitude> tag in each Placemark. We extract it from
// the Placemark's name instead. // the Placemark's name instead.
var name = feature.get('name'); const name = feature.get('name');
var magnitude = parseFloat(name.substr(2)); const magnitude = parseFloat(name.substr(2));
var radius = 5 + 20 * (magnitude - 5); const radius = 5 + 20 * (magnitude - 5);
var style = styleCache[radius]; let style = styleCache[radius];
if (!style) { if (!style) {
style = new Style({ style = new Style({
image: new CircleStyle({ image: new CircleStyle({
@@ -38,7 +38,7 @@ var styleFunction = function(feature) {
return style; return style;
}; };
var vector = new VectorLayer({ const vector = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
url: 'data/kml/2012_Earthquakes_Mag5.kml', url: 'data/kml/2012_Earthquakes_Mag5.kml',
format: new KML({ format: new KML({
@@ -48,13 +48,13 @@ var vector = new VectorLayer({
style: styleFunction style: styleFunction
}); });
var raster = new TileLayer({ const raster = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner'
}) })
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new View({
@@ -63,25 +63,25 @@ var map = new Map({
}) })
}); });
var info = $('#info'); const info = $('#info');
info.tooltip({ info.tooltip({
animation: false, animation: false,
trigger: 'manual' trigger: 'manual'
}); });
var displayFeatureInfo = function(pixel) { const displayFeatureInfo = function(pixel) {
info.css({ info.css({
left: pixel[0] + 'px', left: pixel[0] + 'px',
top: (pixel[1] - 15) + 'px' top: (pixel[1] - 15) + 'px'
}); });
var feature = map.forEachFeatureAtPixel(pixel, function(feature) { const feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature; return feature;
}); });
if (feature) { if (feature) {
info.tooltip('hide') info.tooltip('hide')
.attr('data-original-title', feature.get('name')) .attr('data-original-title', feature.get('name'))
.tooltip('fixTitle') .tooltip('fixTitle')
.tooltip('show'); .tooltip('show');
} else { } else {
info.tooltip('hide'); info.tooltip('hide');
} }

View File

@@ -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 * currently midnight would have an opacity of 0. This doesn't account for
* daylight savings, so don't use it to plan your vacation. * daylight savings, so don't use it to plan your vacation.
*/ */
var styleFunction = function(feature) { const styleFunction = function(feature) {
var offset = 0; let offset = 0;
var name = feature.get('name'); // e.g. GMT -08:30 const name = feature.get('name'); // e.g. GMT -08:30
var match = name.match(/([\-+]\d{2}):(\d{2})$/); const match = name.match(/([\-+]\d{2}):(\d{2})$/);
if (match) { if (match) {
var hours = parseInt(match[1], 10); const hours = parseInt(match[1], 10);
var minutes = parseInt(match[2], 10); const minutes = parseInt(match[2], 10);
offset = 60 * hours + minutes; offset = 60 * hours + minutes;
} }
var date = new Date(); const date = new Date();
var local = new Date(date.getTime() + const local = new Date(date.getTime() +
(date.getTimezoneOffset() + offset) * 60000); (date.getTimezoneOffset() + offset) * 60000);
// offset from local noon (in hours) // 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) { if (delta > 12) {
delta = 24 - delta; delta = 24 - delta;
} }
var opacity = 0.75 * (1 - delta / 12); const opacity = 0.75 * (1 - delta / 12);
return new Style({ return new Style({
fill: new Fill({ fill: new Fill({
color: [0xff, 0xff, 0x33, opacity] color: [0xff, 0xff, 0x33, opacity]
@@ -45,7 +45,7 @@ var styleFunction = function(feature) {
}); });
}; };
var vector = new VectorLayer({ const vector = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
url: 'data/kml/timezones.kml', url: 'data/kml/timezones.kml',
format: new KML({ format: new KML({
@@ -55,13 +55,13 @@ var vector = new VectorLayer({
style: styleFunction style: styleFunction
}); });
var raster = new TileLayer({ const raster = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner'
}) })
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new View({
@@ -70,25 +70,25 @@ var map = new Map({
}) })
}); });
var info = $('#info'); const info = $('#info');
info.tooltip({ info.tooltip({
animation: false, animation: false,
trigger: 'manual' trigger: 'manual'
}); });
var displayFeatureInfo = function(pixel) { const displayFeatureInfo = function(pixel) {
info.css({ info.css({
left: pixel[0] + 'px', left: pixel[0] + 'px',
top: (pixel[1] - 15) + 'px' top: (pixel[1] - 15) + 'px'
}); });
var feature = map.forEachFeatureAtPixel(pixel, function(feature) { const feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature; return feature;
}); });
if (feature) { if (feature) {
info.tooltip('hide') info.tooltip('hide')
.attr('data-original-title', feature.get('name')) .attr('data-original-title', feature.get('name'))
.tooltip('fixTitle') .tooltip('fixTitle')
.tooltip('show'); .tooltip('show');
} else { } else {
info.tooltip('hide'); info.tooltip('hide');
} }

View File

@@ -6,21 +6,21 @@ import VectorLayer from '../src/ol/layer/Vector.js';
import BingMaps from '../src/ol/source/BingMaps.js'; import BingMaps from '../src/ol/source/BingMaps.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new BingMaps({ source: new BingMaps({
imagerySet: 'Aerial', imagerySet: 'Aerial',
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'
}) })
}); });
var vector = new VectorLayer({ const vector = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
url: 'data/kml/2012-02-10.kml', url: 'data/kml/2012-02-10.kml',
format: new KML() format: new KML()
}) })
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new View({
@@ -30,14 +30,14 @@ var map = new Map({
}) })
}); });
var displayFeatureInfo = function(pixel) { const displayFeatureInfo = function(pixel) {
var features = []; const features = [];
map.forEachFeatureAtPixel(pixel, function(feature) { map.forEachFeatureAtPixel(pixel, function(feature) {
features.push(feature); features.push(feature);
}); });
if (features.length > 0) { if (features.length > 0) {
var info = []; const info = [];
var i, ii; let i, ii;
for (i = 0, ii = features.length; i < ii; ++i) { for (i = 0, ii = features.length; i < ii; ++i) {
info.push(features[i].get('name')); info.push(features[i].get('name'));
} }
@@ -53,7 +53,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
var pixel = map.getEventPixel(evt.originalEvent); const pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel); displayFeatureInfo(pixel);
}); });

View File

@@ -6,18 +6,18 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
if (!_ol_has_.WEBGL) { if (!_ol_has_.WEBGL) {
var info = document.getElementById('no-webgl'); const info = document.getElementById('no-webgl');
/** /**
* display error message * display error message
*/ */
info.style.display = ''; info.style.display = '';
} else { } else {
var osm = new TileLayer({ const osm = new TileLayer({
source: new OSM() source: new OSM()
}); });
var map = new Map({ const map = new Map({
layers: [osm], layers: [osm],
renderer: /** @type {Array<ol.renderer.Type>} */ (['webgl', 'canvas']), renderer: /** @type {Array<ol.renderer.Type>} */ (['webgl', 'canvas']),
target: 'map', target: 'map',
@@ -32,13 +32,13 @@ if (!_ol_has_.WEBGL) {
}) })
}); });
var fragmentShaderSource = [ const fragmentShaderSource = [
'precision mediump float;', 'precision mediump float;',
'void main() {', 'void main() {',
'}' '}'
].join(''); ].join('');
var vertexShaderSource = [ const vertexShaderSource = [
'attribute vec2 a_position;', 'attribute vec2 a_position;',
'void main() {', 'void main() {',
' gl_Position = vec4(a_position, 0, 1);', ' gl_Position = vec4(a_position, 0, 1);',
@@ -46,17 +46,17 @@ if (!_ol_has_.WEBGL) {
].join(''); ].join('');
osm.on('precompose', function(event) { osm.on('precompose', function(event) {
var context = event.glContext; const context = event.glContext;
var gl = context.getGL(); const gl = context.getGL();
var program = gl.createProgram(); const program = gl.createProgram();
var vertexShader = gl.createShader(gl.VERTEX_SHADER); const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource); gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader); gl.compileShader(vertexShader);
gl.attachShader(program, vertexShader); gl.attachShader(program, vertexShader);
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSource); gl.shaderSource(fragmentShader, fragmentShaderSource);
gl.compileShader(fragmentShader); gl.compileShader(fragmentShader);
gl.attachShader(program, fragmentShader); gl.attachShader(program, fragmentShader);
@@ -64,14 +64,14 @@ if (!_ol_has_.WEBGL) {
gl.linkProgram(program); gl.linkProgram(program);
context.useProgram(program); context.useProgram(program);
var positionLocation = gl.getAttribLocation(program, 'a_position'); const positionLocation = gl.getAttribLocation(program, 'a_position');
gl.enable(gl.STENCIL_TEST); gl.enable(gl.STENCIL_TEST);
gl.colorMask(false, false, false, false); gl.colorMask(false, false, false, false);
gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE); gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
gl.stencilFunc(gl.ALWAYS, 1, 0xff); gl.stencilFunc(gl.ALWAYS, 1, 0xff);
var buffer = gl.createBuffer(); const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
// first band // first band
@@ -101,8 +101,8 @@ if (!_ol_has_.WEBGL) {
}); });
osm.on('postcompose', function(event) { osm.on('postcompose', function(event) {
var context = event.glContext; const context = event.glContext;
var gl = context.getGL(); const gl = context.getGL();
gl.disable(gl.STENCIL_TEST); gl.disable(gl.STENCIL_TEST);
}); });
} }

View File

@@ -4,11 +4,11 @@ import {defaults as defaultControls} from '../src/ol/control.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var osm = new TileLayer({ const osm = new TileLayer({
source: new OSM() source: new OSM()
}); });
var map = new Map({ const map = new Map({
layers: [osm], layers: [osm],
target: 'map', target: 'map',
controls: defaultControls({ controls: defaultControls({
@@ -23,10 +23,10 @@ var map = new Map({
}); });
osm.on('precompose', function(event) { osm.on('precompose', function(event) {
var ctx = event.context; const ctx = event.context;
ctx.save(); ctx.save();
var pixelRatio = event.frameState.pixelRatio; const pixelRatio = event.frameState.pixelRatio;
var size = map.getSize(); const size = map.getSize();
ctx.translate(size[0] / 2 * pixelRatio, size[1] / 2 * pixelRatio); ctx.translate(size[0] / 2 * pixelRatio, size[1] / 2 * pixelRatio);
ctx.scale(3 * pixelRatio, 3 * pixelRatio); ctx.scale(3 * pixelRatio, 3 * pixelRatio);
ctx.translate(-75, -80); ctx.translate(-75, -80);
@@ -45,6 +45,6 @@ osm.on('precompose', function(event) {
}); });
osm.on('postcompose', function(event) { osm.on('postcompose', function(event) {
var ctx = event.context; const ctx = event.context;
ctx.restore(); ctx.restore();
}); });

View File

@@ -8,21 +8,21 @@ function transform(extent) {
return transformExtent(extent, 'EPSG:4326', 'EPSG:3857'); return transformExtent(extent, 'EPSG:4326', 'EPSG:3857');
} }
var extents = { const extents = {
India: transform([68.17665, 7.96553, 97.40256, 35.49401]), India: transform([68.17665, 7.96553, 97.40256, 35.49401]),
Argentina: transform([-73.41544, -55.25, -53.62835, -21.83231]), Argentina: transform([-73.41544, -55.25, -53.62835, -21.83231]),
Nigeria: transform([2.6917, 4.24059, 14.57718, 13.86592]), Nigeria: transform([2.6917, 4.24059, 14.57718, 13.86592]),
Sweden: transform([11.02737, 55.36174, 23.90338, 69.10625]) Sweden: transform([11.02737, 55.36174, 23.90338, 69.10625])
}; };
var base = new TileLayer({ const base = new TileLayer({
source: new TileJSON({ source: new TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.world-light.json?secure', url: 'https://api.tiles.mapbox.com/v3/mapbox.world-light.json?secure',
crossOrigin: 'anonymous' crossOrigin: 'anonymous'
}) })
}); });
var overlay = new TileLayer({ const overlay = new TileLayer({
extent: extents.India, extent: extents.India,
source: new TileJSON({ source: new TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.world-black.json?secure', 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], layers: [base, overlay],
target: 'map', target: 'map',
view: new View({ 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) { document.getElementById(key).onclick = function(event) {
overlay.setExtent(extents[event.target.id]); overlay.setExtent(extents[event.target.id]);
}; };

View File

@@ -6,7 +6,7 @@ import {fromLonLat} from '../src/ol/proj.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import TileJSON from '../src/ol/source/TileJSON.js'; import TileJSON from '../src/ol/source/TileJSON.js';
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -35,13 +35,13 @@ var map = new Map({
}); });
function bindInputs(layerid, layer) { function bindInputs(layerid, layer) {
var visibilityInput = $(layerid + ' input.visible'); const visibilityInput = $(layerid + ' input.visible');
visibilityInput.on('change', function() { visibilityInput.on('change', function() {
layer.setVisible(this.checked); layer.setVisible(this.checked);
}); });
visibilityInput.prop('checked', layer.getVisible()); visibilityInput.prop('checked', layer.getVisible());
var opacityInput = $(layerid + ' input.opacity'); const opacityInput = $(layerid + ' input.opacity');
opacityInput.on('input change', function() { opacityInput.on('input change', function() {
layer.setOpacity(parseFloat(this.value)); layer.setOpacity(parseFloat(this.value));
}); });

View File

@@ -4,19 +4,19 @@ import TileLayer from '../src/ol/layer/Tile.js';
import {fromLonLat} from '../src/ol/proj.js'; import {fromLonLat} from '../src/ol/proj.js';
import BingMaps from '../src/ol/source/BingMaps.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'}) source: new BingMaps({key: key, imagerySet: 'Road'})
}); });
var imagery = new TileLayer({ const imagery = new TileLayer({
source: new BingMaps({key: key, imagerySet: 'Aerial'}) 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], layers: [roads, imagery],
target: container, target: container,
view: new View({ view: new View({
@@ -25,7 +25,7 @@ var map = new Map({
}) })
}); });
var radius = 75; let radius = 75;
document.addEventListener('keydown', function(evt) { document.addEventListener('keydown', function(evt) {
if (evt.which === 38) { if (evt.which === 38) {
radius = Math.min(radius + 5, 150); radius = Math.min(radius + 5, 150);
@@ -39,7 +39,7 @@ document.addEventListener('keydown', function(evt) {
}); });
// get the pixel position with every move // get the pixel position with every move
var mousePosition = null; let mousePosition = null;
container.addEventListener('mousemove', function(event) { container.addEventListener('mousemove', function(event) {
mousePosition = map.getEventPixel(event); mousePosition = map.getEventPixel(event);
@@ -53,14 +53,14 @@ container.addEventListener('mouseout', function() {
// before rendering the layer, do some clipping // before rendering the layer, do some clipping
imagery.on('precompose', function(event) { imagery.on('precompose', function(event) {
var ctx = event.context; const ctx = event.context;
var pixelRatio = event.frameState.pixelRatio; const pixelRatio = event.frameState.pixelRatio;
ctx.save(); ctx.save();
ctx.beginPath(); ctx.beginPath();
if (mousePosition) { if (mousePosition) {
// only show a circle around the mouse // only show a circle around the mouse
ctx.arc(mousePosition[0] * pixelRatio, mousePosition[1] * pixelRatio, 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.lineWidth = 5 * pixelRatio;
ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.stroke(); ctx.stroke();
@@ -70,6 +70,6 @@ imagery.on('precompose', function(event) {
// after rendering the layer, restore the canvas context // after rendering the layer, restore the canvas context
imagery.on('postcompose', function(event) { imagery.on('postcompose', function(event) {
var ctx = event.context; const ctx = event.context;
ctx.restore(); ctx.restore();
}); });

View File

@@ -5,17 +5,17 @@ import TileLayer from '../src/ol/layer/Tile.js';
import BingMaps from '../src/ol/source/BingMaps.js'; import BingMaps from '../src/ol/source/BingMaps.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var osm = new TileLayer({ const osm = new TileLayer({
source: new OSM() source: new OSM()
}); });
var bing = new TileLayer({ const bing = new TileLayer({
source: new BingMaps({ source: new BingMaps({
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5', key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5',
imagerySet: 'Aerial' imagerySet: 'Aerial'
}) })
}); });
var map = new Map({ const map = new Map({
layers: [osm, bing], layers: [osm, bing],
target: 'map', target: 'map',
controls: defaultControls({ 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) { bing.on('precompose', function(event) {
var ctx = event.context; const ctx = event.context;
var width = ctx.canvas.width * (swipe.value / 100); const width = ctx.canvas.width * (swipe.value / 100);
ctx.save(); ctx.save();
ctx.beginPath(); ctx.beginPath();
@@ -42,7 +42,7 @@ bing.on('precompose', function(event) {
}); });
bing.on('postcompose', function(event) { bing.on('postcompose', function(event) {
var ctx = event.context; const ctx = event.context;
ctx.restore(); ctx.restore();
}); });

View File

@@ -10,9 +10,9 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.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({ 'square': new Style({
image: new RegularShape({ image: new RegularShape({
fill: new Fill({color: 'blue'}), fill: new Fill({color: 'blue'}),
@@ -46,14 +46,14 @@ var styles = {
function createLayer(coordinates, style, zIndex) { function createLayer(coordinates, style, zIndex) {
var feature = new Feature(new Point(coordinates)); const feature = new Feature(new Point(coordinates));
feature.setStyle(style); feature.setStyle(style);
var source = new VectorSource({ const source = new VectorSource({
features: [feature] features: [feature]
}); });
var vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: source source: source
}); });
vectorLayer.setZIndex(zIndex); vectorLayer.setZIndex(zIndex);
@@ -61,15 +61,15 @@ function createLayer(coordinates, style, zIndex) {
return vectorLayer; return vectorLayer;
} }
var layer0 = createLayer([40, 40], styles['star'], 0); const layer0 = createLayer([40, 40], styles['star'], 0);
var layer1 = createLayer([0, 0], styles['square'], 1); const layer1 = createLayer([0, 0], styles['square'], 1);
var layer2 = createLayer([0, 40], styles['triangle'], 0); const layer2 = createLayer([0, 40], styles['triangle'], 0);
var layers = []; const layers = [];
layers.push(layer1); layers.push(layer1);
layers.push(layer2); layers.push(layer2);
var map = new Map({ const map = new Map({
layers: layers, layers: layers,
target: 'map', target: 'map',
view: new View({ view: new View({
@@ -82,7 +82,7 @@ layer0.setMap(map);
function bindInputs(id, layer) { function bindInputs(id, layer) {
var idxInput = document.getElementById('idx' + id); const idxInput = document.getElementById('idx' + id);
idxInput.onchange = function() { idxInput.onchange = function() {
layer.setZIndex(parseInt(this.value, 10) || 0); layer.setZIndex(parseInt(this.value, 10) || 0);
}; };

View File

@@ -3,11 +3,11 @@ import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.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], layers: [layer],
target: 'map', target: 'map',
view: new View({ view: new View({

View File

@@ -10,15 +10,15 @@ import Icon from '../src/ol/style/Icon.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM()
}); });
var source = new VectorSource(); const source = new VectorSource();
var styleFunction = function(feature) { const styleFunction = function(feature) {
var geometry = feature.getGeometry(); const geometry = feature.getGeometry();
var styles = [ const styles = [
// linestring // linestring
new Style({ new Style({
stroke: new Stroke({ stroke: new Stroke({
@@ -29,9 +29,9 @@ var styleFunction = function(feature) {
]; ];
geometry.forEachSegment(function(start, end) { geometry.forEachSegment(function(start, end) {
var dx = end[0] - start[0]; const dx = end[0] - start[0];
var dy = end[1] - start[1]; const dy = end[1] - start[1];
var rotation = Math.atan2(dy, dx); const rotation = Math.atan2(dy, dx);
// arrows // arrows
styles.push(new Style({ styles.push(new Style({
geometry: new Point(end), geometry: new Point(end),
@@ -46,12 +46,12 @@ var styleFunction = function(feature) {
return styles; return styles;
}; };
var vector = new VectorLayer({ const vector = new VectorLayer({
source: source, source: source,
style: styleFunction style: styleFunction
}); });
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new View({

View File

@@ -5,7 +5,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var openCycleMapLayer = new TileLayer({ const openCycleMapLayer = new TileLayer({
source: new OSM({ source: new OSM({
attributions: [ attributions: [
'All maps © <a href="https://www.opencyclemap.org/">OpenCycleMap</a>', 'All maps © <a href="https://www.opencyclemap.org/">OpenCycleMap</a>',
@@ -16,7 +16,7 @@ var openCycleMapLayer = new TileLayer({
}) })
}); });
var openSeaMapLayer = new TileLayer({ const openSeaMapLayer = new TileLayer({
source: new OSM({ source: new OSM({
attributions: [ attributions: [
'All maps © <a href="http://www.openseamap.org/">OpenSeaMap</a>', 'All maps © <a href="http://www.openseamap.org/">OpenSeaMap</a>',
@@ -28,7 +28,7 @@ var openSeaMapLayer = new TileLayer({
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
openCycleMapLayer, openCycleMapLayer,
openSeaMapLayer openSeaMapLayer

View File

@@ -4,15 +4,15 @@ import TileLayer from '../src/ol/layer/Tile.js';
import {fromLonLat} from '../src/ol/proj.js'; import {fromLonLat} from '../src/ol/proj.js';
import BingMaps from '../src/ol/source/BingMaps.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'}) 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], layers: [imagery],
target: container, target: container,
view: new View({ view: new View({
@@ -21,7 +21,7 @@ var map = new Map({
}) })
}); });
var radius = 75; let radius = 75;
document.addEventListener('keydown', function(evt) { document.addEventListener('keydown', function(evt) {
if (evt.which === 38) { if (evt.which === 38) {
radius = Math.min(radius + 5, 150); radius = Math.min(radius + 5, 150);
@@ -35,7 +35,7 @@ document.addEventListener('keydown', function(evt) {
}); });
// get the pixel position with every move // get the pixel position with every move
var mousePosition = null; let mousePosition = null;
container.addEventListener('mousemove', function(event) { container.addEventListener('mousemove', function(event) {
mousePosition = map.getEventPixel(event); mousePosition = map.getEventPixel(event);
@@ -50,30 +50,30 @@ container.addEventListener('mouseout', function() {
// after rendering the layer, show an oversampled version around the pointer // after rendering the layer, show an oversampled version around the pointer
imagery.on('postcompose', function(event) { imagery.on('postcompose', function(event) {
if (mousePosition) { if (mousePosition) {
var context = event.context; const context = event.context;
var pixelRatio = event.frameState.pixelRatio; const pixelRatio = event.frameState.pixelRatio;
var half = radius * pixelRatio; const half = radius * pixelRatio;
var centerX = mousePosition[0] * pixelRatio; const centerX = mousePosition[0] * pixelRatio;
var centerY = mousePosition[1] * pixelRatio; const centerY = mousePosition[1] * pixelRatio;
var originX = centerX - half; const originX = centerX - half;
var originY = centerY - half; const originY = centerY - half;
var size = 2 * half + 1; const size = 2 * half + 1;
var sourceData = context.getImageData(originX, originY, size, size).data; const sourceData = context.getImageData(originX, originY, size, size).data;
var dest = context.createImageData(size, size); const dest = context.createImageData(size, size);
var destData = dest.data; const destData = dest.data;
for (var j = 0; j < size; ++j) { for (let j = 0; j < size; ++j) {
for (var i = 0; i < size; ++i) { for (let i = 0; i < size; ++i) {
var dI = i - half; const dI = i - half;
var dJ = j - half; const dJ = j - half;
var dist = Math.sqrt(dI * dI + dJ * dJ); const dist = Math.sqrt(dI * dI + dJ * dJ);
var sourceI = i; let sourceI = i;
var sourceJ = j; let sourceJ = j;
if (dist < half) { if (dist < half) {
sourceI = Math.round(half + dI / 2); sourceI = Math.round(half + dI / 2);
sourceJ = Math.round(half + dJ / 2); sourceJ = Math.round(half + dJ / 2);
} }
var destOffset = (j * size + i) * 4; const destOffset = (j * size + i) * 4;
var sourceOffset = (sourceJ * size + sourceI) * 4; const sourceOffset = (sourceJ * size + sourceI) * 4;
destData[destOffset] = sourceData[sourceOffset]; destData[destOffset] = sourceData[sourceOffset];
destData[destOffset + 1] = sourceData[sourceOffset + 1]; destData[destOffset + 1] = sourceData[sourceOffset + 1];
destData[destOffset + 2] = sourceData[sourceOffset + 2]; destData[destOffset + 2] = sourceData[sourceOffset + 2];

View File

@@ -12,25 +12,25 @@ import Text from '../src/ol/style/Text.js';
import TileGrid from '../src/ol/tilegrid/TileGrid.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. // Calculation of resolutions that match zoom levels 1, 3, 5, 7, 9, 11, 13, 15.
var resolutions = []; const resolutions = [];
for (var i = 0; i <= 8; ++i) { for (let i = 0; i <= 8; ++i) {
resolutions.push(156543.03392804097 / Math.pow(2, i * 2)); resolutions.push(156543.03392804097 / Math.pow(2, i * 2));
} }
// Calculation of tile urls for zoom levels 1, 3, 5, 7, 9, 11, 13, 15. // Calculation of tile urls for zoom levels 1, 3, 5, 7, 9, 11, 13, 15.
function tileUrlFunction(tileCoord) { function tileUrlFunction(tileCoord) {
return ('https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' + return ('https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' +
'{z}/{x}/{y}.vector.pbf?access_token=' + key) '{z}/{x}/{y}.vector.pbf?access_token=' + key)
.replace('{z}', String(tileCoord[0] * 2 - 1)) .replace('{z}', String(tileCoord[0] * 2 - 1))
.replace('{x}', String(tileCoord[1])) .replace('{x}', String(tileCoord[1]))
.replace('{y}', String(-tileCoord[2] - 1)) .replace('{y}', String(-tileCoord[2] - 1))
.replace('{a-d}', 'abcd'.substr( .replace('{a-d}', 'abcd'.substr(
((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1)); ((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1));
} }
var map = new Map({ const map = new Map({
layers: [ layers: [
new VectorTileLayer({ new VectorTileLayer({
source: new VectorTileSource({ source: new VectorTileSource({

View File

@@ -10,9 +10,9 @@ import Style from '../src/ol/style/Style.js';
import Text from '../src/ol/style/Text.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: [ layers: [
new VectorTileLayer({ new VectorTileLayer({
declutter: true, declutter: true,

View File

@@ -3,16 +3,16 @@ import View from '../src/ol/View.js';
import ImageLayer from '../src/ol/layer/Image.js'; import ImageLayer from '../src/ol/layer/Image.js';
import ImageMapGuide from '../src/ol/source/ImageMapGuide.js'; import ImageMapGuide from '../src/ol/source/ImageMapGuide.js';
var mdf = 'Library://Public/Samples/Sheboygan/Maps/Sheboygan.MapDefinition'; const mdf = 'Library://Public/Samples/Sheboygan/Maps/Sheboygan.MapDefinition';
var agentUrl = const agentUrl =
'http://www.buoyshark.com/mapguide/mapagent/mapagent.fcgi?'; 'http://www.buoyshark.com/mapguide/mapagent/mapagent.fcgi?';
var bounds = [ const bounds = [
-87.865114442365922, -87.865114442365922,
43.665065564837931, 43.665065564837931,
-87.595394059497067, -87.595394059497067,
43.823852564430069 43.823852564430069
]; ];
var map = new Map({ const map = new Map({
layers: [ layers: [
new ImageLayer({ new ImageLayer({
extent: bounds, extent: bounds,

View File

@@ -16,13 +16,13 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM()
}); });
var source = new VectorSource(); const source = new VectorSource();
var vector = new VectorLayer({ const vector = new VectorLayer({
source: source, source: source,
style: new Style({ style: new Style({
fill: new Fill({ fill: new Fill({
@@ -46,64 +46,64 @@ var vector = new VectorLayer({
* Currently drawn feature. * Currently drawn feature.
* @type {ol.Feature} * @type {ol.Feature}
*/ */
var sketch; let sketch;
/** /**
* The help tooltip element. * The help tooltip element.
* @type {Element} * @type {Element}
*/ */
var helpTooltipElement; let helpTooltipElement;
/** /**
* Overlay to show the help messages. * Overlay to show the help messages.
* @type {ol.Overlay} * @type {ol.Overlay}
*/ */
var helpTooltip; let helpTooltip;
/** /**
* The measure tooltip element. * The measure tooltip element.
* @type {Element} * @type {Element}
*/ */
var measureTooltipElement; let measureTooltipElement;
/** /**
* Overlay to show the measurement. * Overlay to show the measurement.
* @type {ol.Overlay} * @type {ol.Overlay}
*/ */
var measureTooltip; let measureTooltip;
/** /**
* Message to show when the user is drawing a polygon. * Message to show when the user is drawing a polygon.
* @type {string} * @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. * Message to show when the user is drawing a line.
* @type {string} * @type {string}
*/ */
var continueLineMsg = 'Click to continue drawing the line'; const continueLineMsg = 'Click to continue drawing the line';
/** /**
* Handle pointer move. * Handle pointer move.
* @param {ol.MapBrowserEvent} evt The event. * @param {ol.MapBrowserEvent} evt The event.
*/ */
var pointerMoveHandler = function(evt) { const pointerMoveHandler = function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
/** @type {string} */ /** @type {string} */
var helpMsg = 'Click to start drawing'; let helpMsg = 'Click to start drawing';
if (sketch) { if (sketch) {
var geom = (sketch.getGeometry()); const geom = (sketch.getGeometry());
if (geom instanceof Polygon) { if (geom instanceof Polygon) {
helpMsg = continuePolygonMsg; helpMsg = continuePolygonMsg;
} else if (geom instanceof LineString) { } else if (geom instanceof LineString) {
@@ -118,7 +118,7 @@ var pointerMoveHandler = function(evt) {
}; };
var map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new View({
@@ -133,9 +133,9 @@ map.getViewport().addEventListener('mouseout', function() {
helpTooltipElement.classList.add('hidden'); 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. * @param {ol.geom.LineString} line The line.
* @return {string} The formatted length. * @return {string} The formatted length.
*/ */
var formatLength = function(line) { const formatLength = function(line) {
var length = getLength(line); const length = getLength(line);
var output; let output;
if (length > 100) { if (length > 100) {
output = (Math.round(length / 1000 * 100) / 100) + output = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km'; ' ' + 'km';
@@ -162,9 +162,9 @@ var formatLength = function(line) {
* @param {ol.geom.Polygon} polygon The polygon. * @param {ol.geom.Polygon} polygon The polygon.
* @return {string} Formatted area. * @return {string} Formatted area.
*/ */
var formatArea = function(polygon) { const formatArea = function(polygon) {
var area = getArea(polygon); const area = getArea(polygon);
var output; let output;
if (area > 10000) { if (area > 10000) {
output = (Math.round(area / 1000000 * 100) / 100) + output = (Math.round(area / 1000000 * 100) / 100) +
' ' + 'km<sup>2</sup>'; ' ' + 'km<sup>2</sup>';
@@ -176,7 +176,7 @@ var formatArea = function(polygon) {
}; };
function addInteraction() { function addInteraction() {
var type = (typeSelect.value == 'area' ? 'Polygon' : 'LineString'); const type = (typeSelect.value == 'area' ? 'Polygon' : 'LineString');
draw = new Draw({ draw = new Draw({
source: source, source: source,
type: type, type: type,
@@ -205,41 +205,41 @@ function addInteraction() {
createMeasureTooltip(); createMeasureTooltip();
createHelpTooltip(); createHelpTooltip();
var listener; let listener;
draw.on('drawstart', draw.on('drawstart',
function(evt) { function(evt) {
// set sketch // set sketch
sketch = evt.feature; sketch = evt.feature;
/** @type {ol.Coordinate|undefined} */ /** @type {ol.Coordinate|undefined} */
var tooltipCoord = evt.coordinate; let tooltipCoord = evt.coordinate;
listener = sketch.getGeometry().on('change', function(evt) { listener = sketch.getGeometry().on('change', function(evt) {
var geom = evt.target; const geom = evt.target;
var output; let output;
if (geom instanceof Polygon) { if (geom instanceof Polygon) {
output = formatArea(geom); output = formatArea(geom);
tooltipCoord = geom.getInteriorPoint().getCoordinates(); tooltipCoord = geom.getInteriorPoint().getCoordinates();
} else if (geom instanceof LineString) { } else if (geom instanceof LineString) {
output = formatLength(geom); output = formatLength(geom);
tooltipCoord = geom.getLastCoordinate(); tooltipCoord = geom.getLastCoordinate();
} }
measureTooltipElement.innerHTML = output; measureTooltipElement.innerHTML = output;
measureTooltip.setPosition(tooltipCoord); measureTooltip.setPosition(tooltipCoord);
}); });
}, this); }, this);
draw.on('drawend', draw.on('drawend',
function() { function() {
measureTooltipElement.className = 'tooltip tooltip-static'; measureTooltipElement.className = 'tooltip tooltip-static';
measureTooltip.setOffset([0, -7]); measureTooltip.setOffset([0, -7]);
// unset sketch // unset sketch
sketch = null; sketch = null;
// unset tooltip so that a new one can be created // unset tooltip so that a new one can be created
measureTooltipElement = null; measureTooltipElement = null;
createMeasureTooltip(); createMeasureTooltip();
Observable.unByKey(listener); Observable.unByKey(listener);
}, this); }, this);
} }

View File

@@ -9,7 +9,7 @@ import TileJSON from '../src/ol/source/TileJSON.js';
/** /**
* Create the map. * Create the map.
*/ */
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM(), source: new OSM(),

View File

@@ -3,22 +3,22 @@ import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var viewport = document.getElementById('map'); const viewport = document.getElementById('map');
function getMinZoom() { function getMinZoom() {
var width = viewport.clientWidth; const width = viewport.clientWidth;
return Math.ceil(Math.LOG2E * Math.log(width / 256)); 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], center: [0, 0],
minZoom: initialZoom, minZoom: initialZoom,
zoom: initialZoom zoom: initialZoom
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -29,7 +29,7 @@ var map = new Map({
}); });
window.addEventListener('resize', function() { window.addEventListener('resize', function() {
var minZoom = getMinZoom(); const minZoom = getMinZoom();
if (minZoom !== view.getMinZoom()) { if (minZoom !== view.getMinZoom()) {
view.setMinZoom(minZoom); view.setMinZoom(minZoom);
} }

View File

@@ -5,12 +5,12 @@ import TileLayer from '../src/ol/layer/Tile.js';
import BingMaps from '../src/ol/source/BingMaps.js'; import BingMaps from '../src/ol/source/BingMaps.js';
var view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new BingMaps({ source: new BingMaps({
@@ -23,7 +23,7 @@ var map = new Map({
view: view view: view
}); });
var geolocation = new Geolocation({ const geolocation = new Geolocation({
projection: view.getProjection(), projection: view.getProjection(),
tracking: true tracking: true
}); });

View File

@@ -10,11 +10,11 @@ import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
var raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM()
}); });
var vector = new VectorLayer({ const vector = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON(), format: new GeoJSON(),
@@ -22,15 +22,15 @@ var vector = new VectorLayer({
}) })
}); });
var select = new Select({ const select = new Select({
wrapX: false wrapX: false
}); });
var modify = new Modify({ const modify = new Modify({
features: select.getFeatures() features: select.getFeatures()
}); });
var map = new Map({ const map = new Map({
interactions: defaultInteractions().extend([select, modify]), interactions: defaultInteractions().extend([select, modify]),
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',

View File

@@ -12,9 +12,9 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var styleFunction = (function() { const styleFunction = (function() {
var styles = {}; const styles = {};
var image = new CircleStyle({ const image = new CircleStyle({
radius: 5, radius: 5,
fill: null, fill: null,
stroke: new Stroke({color: 'orange', width: 2}) stroke: new Stroke({color: 'orange', width: 2})
@@ -59,7 +59,7 @@ var styleFunction = (function() {
}; };
})(); })();
var geojsonObject = { const geojsonObject = {
'type': 'FeatureCollection', 'type': 'FeatureCollection',
'crs': { 'crs': {
'type': 'name', 'type': 'name',
@@ -144,17 +144,17 @@ var geojsonObject = {
}] }]
}; };
var source = new VectorSource({ const source = new VectorSource({
features: (new GeoJSON()).readFeatures(geojsonObject) features: (new GeoJSON()).readFeatures(geojsonObject)
}); });
var layer = new VectorLayer({ const layer = new VectorLayer({
source: source, source: source,
style: styleFunction style: styleFunction
}); });
var overlayStyle = (function() { const overlayStyle = (function() {
var styles = {}; const styles = {};
styles['Polygon'] = [ styles['Polygon'] = [
new Style({ new Style({
fill: new Fill({ fill: new Fill({
@@ -216,11 +216,11 @@ var overlayStyle = (function() {
}; };
})(); })();
var select = new Select({ const select = new Select({
style: overlayStyle style: overlayStyle
}); });
var modify = new Modify({ const modify = new Modify({
features: select.getFeatures(), features: select.getFeatures(),
style: overlayStyle, style: overlayStyle,
insertVertexCondition: function() { insertVertexCondition: function() {
@@ -231,7 +231,7 @@ var modify = new Modify({
} }
}); });
var map = new Map({ const map = new Map({
interactions: defaultInteractions().extend([select, modify]), interactions: defaultInteractions().extend([select, modify]),
layers: [layer], layers: [layer],
target: 'map', target: 'map',

View File

@@ -6,7 +6,7 @@ import _ol_coordinate_ from '../src/ol/coordinate.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var mousePositionControl = new MousePosition({ const mousePositionControl = new MousePosition({
coordinateFormat: _ol_coordinate_.createStringXY(4), coordinateFormat: _ol_coordinate_.createStringXY(4),
projection: 'EPSG:4326', projection: 'EPSG:4326',
// comment the following two lines to have the mouse position // comment the following two lines to have the mouse position
@@ -16,7 +16,7 @@ var mousePositionControl = new MousePosition({
undefinedHTML: '&nbsp;' undefinedHTML: '&nbsp;'
}); });
var map = new Map({ const map = new Map({
controls: defaultControls({ controls: defaultControls({
attributionOptions: { attributionOptions: {
collapsible: false 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) { projectionSelect.addEventListener('change', function(event) {
mousePositionControl.setProjection(event.target.value); mousePositionControl.setProjection(event.target.value);
}); });
var precisionInput = document.getElementById('precision'); const precisionInput = document.getElementById('precision');
precisionInput.addEventListener('change', function(event) { precisionInput.addEventListener('change', function(event) {
var format = _ol_coordinate_.createStringXY(event.target.valueAsNumber); const format = _ol_coordinate_.createStringXY(event.target.valueAsNumber);
mousePositionControl.setCoordinateFormat(format); mousePositionControl.setCoordinateFormat(format);
}); });

View File

@@ -6,7 +6,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var map = new Map({ const map = new Map({
interactions: defaultInteractions({mouseWheelZoom: false}).extend([ interactions: defaultInteractions({mouseWheelZoom: false}).extend([
new MouseWheelZoom({ new MouseWheelZoom({
constrainResolution: true // force zooming to a integer zoom constrainResolution: true // force zooming to a integer zoom

View File

@@ -7,7 +7,7 @@ import {toLonLat} from '../src/ol/proj.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -30,15 +30,15 @@ function display(id, value) {
} }
function wrapLon(value) { function wrapLon(value) {
var worlds = Math.floor((value + 180) / 360); const worlds = Math.floor((value + 180) / 360);
return value - (worlds * 360); return value - (worlds * 360);
} }
function onMoveEnd(evt) { function onMoveEnd(evt) {
var map = evt.map; const map = evt.map;
var extent = map.getView().calculateExtent(map.getSize()); const extent = map.getView().calculateExtent(map.getSize());
var bottomLeft = toLonLat(_ol_extent_.getBottomLeft(extent)); const bottomLeft = toLonLat(_ol_extent_.getBottomLeft(extent));
var topRight = toLonLat(_ol_extent_.getTopRight(extent)); const topRight = toLonLat(_ol_extent_.getTopRight(extent));
display('left', wrapLon(bottomLeft[0])); display('left', wrapLon(bottomLeft[0]));
display('bottom', bottomLeft[1]); display('bottom', bottomLeft[1]);
display('right', wrapLon(topRight[0])); display('right', wrapLon(topRight[0]));

View File

@@ -6,7 +6,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var map = new Map({ const map = new Map({
controls: defaultControls({ controls: defaultControls({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false

View File

@@ -8,15 +8,15 @@ import Fill from '../src/ol/style/Fill.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var key = 'vector-tiles-5eJz6JX'; const key = 'vector-tiles-5eJz6JX';
var roadStyleCache = {}; const roadStyleCache = {};
var roadColor = { const roadColor = {
'major_road': '#776', 'major_road': '#776',
'minor_road': '#ccb', 'minor_road': '#ccb',
'highway': '#f39' 'highway': '#f39'
}; };
var buildingStyle = new Style({ const buildingStyle = new Style({
fill: new Fill({ fill: new Fill({
color: '#666', color: '#666',
opacity: 0.4 opacity: 0.4
@@ -26,19 +26,19 @@ var buildingStyle = new Style({
width: 1 width: 1
}) })
}); });
var waterStyle = new Style({ const waterStyle = new Style({
fill: new Fill({ fill: new Fill({
color: '#9db9e8' color: '#9db9e8'
}) })
}); });
var roadStyle = function(feature) { const roadStyle = function(feature) {
var kind = feature.get('kind'); const kind = feature.get('kind');
var railway = feature.get('railway'); const railway = feature.get('railway');
var sort_key = feature.get('sort_key'); const sort_key = feature.get('sort_key');
var styleKey = kind + '/' + railway + '/' + sort_key; const styleKey = kind + '/' + railway + '/' + sort_key;
var style = roadStyleCache[styleKey]; let style = roadStyleCache[styleKey];
if (!style) { if (!style) {
var color, width; let color, width;
if (railway) { if (railway) {
color = '#7de'; color = '#7de';
width = 1; width = 1;
@@ -58,7 +58,7 @@ var roadStyle = function(feature) {
return style; return style;
}; };
var map = new Map({ const map = new Map({
layers: [ layers: [
new VectorTileLayer({ new VectorTileLayer({
source: new VectorTileSource({ source: new VectorTileSource({

View File

@@ -7,11 +7,11 @@ import {fromLonLat, toLonLat} from '../src/ol/proj.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var layer = new TileLayer({ const layer = new TileLayer({
source: new OSM() source: new OSM()
}); });
var map = new Map({ const map = new Map({
layers: [layer], layers: [layer],
target: 'map', target: 'map',
view: new View({ 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 // Vienna marker
var marker = new Overlay({ const marker = new Overlay({
position: pos, position: pos,
positioning: 'center-center', positioning: 'center-center',
element: document.getElementById('marker'), element: document.getElementById('marker'),
@@ -32,22 +32,22 @@ var marker = new Overlay({
map.addOverlay(marker); map.addOverlay(marker);
// Vienna label // Vienna label
var vienna = new Overlay({ const vienna = new Overlay({
position: pos, position: pos,
element: document.getElementById('vienna') element: document.getElementById('vienna')
}); });
map.addOverlay(vienna); map.addOverlay(vienna);
// Popup showing the position the user clicked // Popup showing the position the user clicked
var popup = new Overlay({ const popup = new Overlay({
element: document.getElementById('popup') element: document.getElementById('popup')
}); });
map.addOverlay(popup); map.addOverlay(popup);
map.on('click', function(evt) { map.on('click', function(evt) {
var element = popup.getElement(); const element = popup.getElement();
var coordinate = evt.coordinate; const coordinate = evt.coordinate;
var hdms = _ol_coordinate_.toStringHDMS(toLonLat(coordinate)); const hdms = _ol_coordinate_.toStringHDMS(toLonLat(coordinate));
$(element).popover('destroy'); $(element).popover('destroy');
popup.setPosition(coordinate); popup.setPosition(coordinate);

View File

@@ -8,7 +8,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.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 // see in overviewmap-custom.html to see the custom CSS used
className: 'ol-overviewmap ol-custom-overviewmap', className: 'ol-overviewmap ol-custom-overviewmap',
layers: [ layers: [
@@ -24,7 +24,7 @@ var overviewMapControl = new OverviewMap({
collapsed: false collapsed: false
}); });
var map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([
overviewMapControl overviewMapControl
]), ]),

View File

@@ -5,7 +5,7 @@ import OverviewMap from '../src/ol/control/OverviewMap.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([
new OverviewMap() new OverviewMap()
]), ]),

View File

@@ -5,14 +5,14 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
// default zoom, center and rotation // default zoom, center and rotation
var zoom = 2; let zoom = 2;
var center = [0, 0]; let center = [0, 0];
var rotation = 0; let rotation = 0;
if (window.location.hash !== '') { if (window.location.hash !== '') {
// try to restore center, zoom-level and rotation from the URL // try to restore center, zoom-level and rotation from the URL
var hash = window.location.hash.replace('#map=', ''); const hash = window.location.hash.replace('#map=', '');
var parts = hash.split('/'); const parts = hash.split('/');
if (parts.length === 4) { if (parts.length === 4) {
zoom = parseInt(parts[0], 10); zoom = parseInt(parts[0], 10);
center = [ center = [
@@ -23,7 +23,7 @@ if (window.location.hash !== '') {
} }
} }
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM()
@@ -42,22 +42,22 @@ var map = new Map({
}) })
}); });
var shouldUpdate = true; let shouldUpdate = true;
var view = map.getView(); const view = map.getView();
var updatePermalink = function() { const updatePermalink = function() {
if (!shouldUpdate) { if (!shouldUpdate) {
// do not update the URL when the view was changed in the 'popstate' handler // do not update the URL when the view was changed in the 'popstate' handler
shouldUpdate = true; shouldUpdate = true;
return; return;
} }
var center = view.getCenter(); const center = view.getCenter();
var hash = '#map=' + const hash = '#map=' +
view.getZoom() + '/' + view.getZoom() + '/' +
Math.round(center[0] * 100) / 100 + '/' + Math.round(center[0] * 100) / 100 + '/' +
Math.round(center[1] * 100) / 100 + '/' + Math.round(center[1] * 100) / 100 + '/' +
view.getRotation(); view.getRotation();
var state = { const state = {
zoom: view.getZoom(), zoom: view.getZoom(),
center: view.getCenter(), center: view.getCenter(),
rotation: view.getRotation() rotation: view.getRotation()

View File

@@ -6,7 +6,7 @@ import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
var map = new Map({ const map = new Map({
interactions: defaultInteractions({pinchZoom: false}).extend([ interactions: defaultInteractions({pinchZoom: false}).extend([
new PinchZoom({ new PinchZoom({
constrainResolution: true // force zooming to a integer zoom constrainResolution: true // force zooming to a integer zoom

View File

@@ -9,7 +9,7 @@ import Fill from '../src/ol/style/Fill.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var styles = [ const styles = [
/* We are using two different styles for the polygons: /* We are using two different styles for the polygons:
* - The first style is for the polygons themselves. * - The first style is for the polygons themselves.
* - The second style is to draw the vertices of the polygons. * - The second style is to draw the vertices of the polygons.
@@ -35,13 +35,13 @@ var styles = [
}), }),
geometry: function(feature) { geometry: function(feature) {
// return the coordinates of the first ring of the polygon // 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); return new MultiPoint(coordinates);
} }
}) })
]; ];
var geojsonObject = { const geojsonObject = {
'type': 'FeatureCollection', 'type': 'FeatureCollection',
'crs': { 'crs': {
'type': 'name', 'type': 'name',
@@ -80,16 +80,16 @@ var geojsonObject = {
}] }]
}; };
var source = new VectorSource({ const source = new VectorSource({
features: (new GeoJSON()).readFeatures(geojsonObject) features: (new GeoJSON()).readFeatures(geojsonObject)
}); });
var layer = new VectorLayer({ const layer = new VectorLayer({
source: source, source: source,
style: styles style: styles
}); });
var map = new Map({ const map = new Map({
layers: [layer], layers: [layer],
target: 'map', target: 'map',
view: new View({ view: new View({

View File

@@ -10,15 +10,15 @@ import TileJSON from '../src/ol/source/TileJSON.js';
/** /**
* Elements that make up the popup. * Elements that make up the popup.
*/ */
var container = document.getElementById('popup'); const container = document.getElementById('popup');
var content = document.getElementById('popup-content'); const content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer'); const closer = document.getElementById('popup-closer');
/** /**
* Create an overlay to anchor the popup to the map. * Create an overlay to anchor the popup to the map.
*/ */
var overlay = new Overlay({ const overlay = new Overlay({
element: container, element: container,
autoPan: true, autoPan: true,
autoPanAnimation: { autoPanAnimation: {
@@ -41,7 +41,7 @@ closer.onclick = function() {
/** /**
* Create the map. * Create the map.
*/ */
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new TileJSON({ source: new TileJSON({
@@ -63,8 +63,8 @@ var map = new Map({
* Add a click handler to the map to render the popup. * Add a click handler to the map to render the popup.
*/ */
map.on('singleclick', function(evt) { map.on('singleclick', function(evt) {
var coordinate = evt.coordinate; const coordinate = evt.coordinate;
var hdms = _ol_coordinate_.toStringHDMS(toLonLat(coordinate)); const hdms = _ol_coordinate_.toStringHDMS(toLonLat(coordinate));
content.innerHTML = '<p>You clicked here:</p><code>' + hdms + content.innerHTML = '<p>You clicked here:</p><code>' + hdms +
'</code>'; '</code>';

View File

@@ -4,12 +4,12 @@ import TileLayer from '../src/ol/layer/Tile.js';
import BingMaps from '../src/ol/source/BingMaps.js'; import BingMaps from '../src/ol/source/BingMaps.js';
var view = new View({ const view = new View({
center: [-4808600, -2620936], center: [-4808600, -2620936],
zoom: 8 zoom: 8
}); });
var map1 = new Map({ const map1 = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
preload: Infinity, preload: Infinity,
@@ -23,7 +23,7 @@ var map1 = new Map({
view: view view: view
}); });
var map2 = new Map({ const map2 = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
preload: 0, // default value preload: 0, // default value

View File

@@ -7,9 +7,9 @@ import TileLayer from '../src/ol/layer/Tile.js';
import BingMaps from '../src/ol/source/BingMaps.js'; import BingMaps from '../src/ol/source/BingMaps.js';
import RasterSource from '../src/ol/source/Raster.js'; import RasterSource from '../src/ol/source/Raster.js';
var minVgi = 0; const minVgi = 0;
var maxVgi = 0.25; const maxVgi = 0.25;
var bins = 10; const bins = 10;
/** /**
@@ -19,9 +19,9 @@ var bins = 10;
* @return {number} The VGI value for the given pixel. * @return {number} The VGI value for the given pixel.
*/ */
function vgi(pixel) { function vgi(pixel) {
var r = pixel[0] / 255; const r = pixel[0] / 255;
var g = pixel[1] / 255; const g = pixel[1] / 255;
var b = pixel[2] / 255; const b = pixel[2] / 255;
return (2 * g - r - b) / (2 * g + r + b); 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. * @param {Object} counts An object for keeping track of VGI counts.
*/ */
function summarize(value, counts) { function summarize(value, counts) {
var min = counts.min; const min = counts.min;
var max = counts.max; const max = counts.max;
var num = counts.values.length; const num = counts.values.length;
if (value < min) { if (value < min) {
// do nothing // do nothing
} else if (value >= max) { } else if (value >= max) {
counts.values[num - 1] += 1; counts.values[num - 1] += 1;
} else { } else {
var index = Math.floor((value - min) / counts.delta); const index = Math.floor((value - min) / counts.delta);
counts.values[index] += 1; counts.values[index] += 1;
} }
} }
@@ -49,7 +49,7 @@ function summarize(value, counts) {
/** /**
* Use aerial imagery as the input data for the raster source. * Use aerial imagery as the input data for the raster source.
*/ */
var bing = new BingMaps({ const bing = new BingMaps({
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5', key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5',
imagerySet: 'Aerial' imagerySet: 'Aerial'
}); });
@@ -59,7 +59,7 @@ var bing = new BingMaps({
* Create a raster source where pixels with VGI values above a threshold will * Create a raster source where pixels with VGI values above a threshold will
* be colored green. * be colored green.
*/ */
var raster = new RasterSource({ const raster = new RasterSource({
sources: [bing], sources: [bing],
/** /**
* Run calculations on pixel data. * Run calculations on pixel data.
@@ -68,8 +68,8 @@ var raster = new RasterSource({
* @return {Array} The output pixel. * @return {Array} The output pixel.
*/ */
operation: function(pixels, data) { operation: function(pixels, data) {
var pixel = pixels[0]; const pixel = pixels[0];
var value = vgi(pixel); const value = vgi(pixel);
summarize(value, data.counts); summarize(value, data.counts);
if (value >= data.threshold) { if (value >= data.threshold) {
pixel[0] = 0; pixel[0] = 0;
@@ -89,8 +89,8 @@ var raster = new RasterSource({
raster.set('threshold', 0.1); raster.set('threshold', 0.1);
function createCounts(min, max, num) { function createCounts(min, max, num) {
var values = new Array(num); const values = new Array(num);
for (var i = 0; i < num; ++i) { for (let i = 0; i < num; ++i) {
values[i] = 0; values[i] = 0;
} }
return { return {
@@ -110,7 +110,7 @@ raster.on('afteroperations', function(event) {
schedulePlot(event.resolution, event.data.counts, event.data.threshold); schedulePlot(event.resolution, event.data.counts, event.data.threshold);
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: bing source: bing
@@ -129,7 +129,7 @@ var map = new Map({
}); });
var timer = null; let timer = null;
function schedulePlot(resolution, counts, threshold) { function schedulePlot(resolution, counts, threshold) {
if (timer) { if (timer) {
clearTimeout(timer); clearTimeout(timer);
@@ -138,40 +138,40 @@ function schedulePlot(resolution, counts, threshold) {
timer = setTimeout(plot.bind(null, resolution, counts, threshold), 1000 / 60); timer = setTimeout(plot.bind(null, resolution, counts, threshold), 1000 / 60);
} }
var barWidth = 15; const barWidth = 15;
var plotHeight = 150; const plotHeight = 150;
var chart = d3.select('#plot').append('svg') const chart = d3.select('#plot').append('svg')
.attr('width', barWidth * bins) .attr('width', barWidth * bins)
.attr('height', plotHeight); .attr('height', plotHeight);
var chartRect = chart.node().getBoundingClientRect(); const chartRect = chart.node().getBoundingClientRect();
var tip = d3.select(document.body).append('div') const tip = d3.select(document.body).append('div')
.attr('class', 'tip'); .attr('class', 'tip');
function plot(resolution, counts, threshold) { function plot(resolution, counts, threshold) {
var yScale = d3.scaleLinear() const yScale = d3.scaleLinear()
.domain([0, d3.max(counts.values)]) .domain([0, d3.max(counts.values)])
.range([0, plotHeight]); .range([0, plotHeight]);
var bar = chart.selectAll('rect').data(counts.values); const bar = chart.selectAll('rect').data(counts.values);
bar.enter().append('rect'); bar.enter().append('rect');
bar.attr('class', function(count, index) { 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' : ''); return 'bar' + (value >= threshold ? ' selected' : '');
}) })
.attr('width', barWidth - 2); .attr('width', barWidth - 2);
bar.transition().attr('transform', function(value, index) { bar.transition().attr('transform', function(value, index) {
return 'translate(' + (index * barWidth) + ', ' + return 'translate(' + (index * barWidth) + ', ' +
(plotHeight - yScale(value)) + ')'; (plotHeight - yScale(value)) + ')';
}) })
.attr('height', yScale); .attr('height', yScale);
bar.on('mousemove', function(count, index) { 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) { if (raster.get('threshold') !== threshold) {
raster.set('threshold', threshold); raster.set('threshold', threshold);
raster.changed(); raster.changed();
@@ -179,8 +179,8 @@ function plot(resolution, counts, threshold) {
}); });
bar.on('mouseover', function(count, index) { bar.on('mouseover', function(count, index) {
var area = 0; let area = 0;
for (var i = counts.values.length - 1; i >= index; --i) { for (let i = counts.values.length - 1; i >= index; --i) {
area += resolution * resolution * counts.values[i]; area += resolution * resolution * counts.values[i];
} }
tip.html(message(counts.min + (index * counts.delta), area)); tip.html(message(counts.min + (index * counts.delta), area));
@@ -201,6 +201,6 @@ function plot(resolution, counts, threshold) {
} }
function message(value, area) { 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<br>' + value.toFixed(2) + ' VGI or above'; return acres + ' acres at<br>' + value.toFixed(2) + ' VGI or above';
} }

View File

@@ -8,38 +8,39 @@ import BingMaps from '../src/ol/source/BingMaps.js';
import RasterSource from '../src/ol/source/Raster.js'; import RasterSource from '../src/ol/source/Raster.js';
function growRegion(inputs, data) { function growRegion(inputs, data) {
var image = inputs[0]; const image = inputs[0];
var seed = data.pixel; let seed = data.pixel;
var delta = parseInt(data.delta); const delta = parseInt(data.delta);
if (!seed) { if (!seed) {
return image; return image;
} }
seed = seed.map(Math.round); seed = seed.map(Math.round);
var width = image.width; const width = image.width;
var height = image.height; const height = image.height;
var inputData = image.data; const inputData = image.data;
var outputData = new Uint8ClampedArray(inputData); const outputData = new Uint8ClampedArray(inputData);
var seedIdx = (seed[1] * width + seed[0]) * 4; const seedIdx = (seed[1] * width + seed[0]) * 4;
var seedR = inputData[seedIdx]; const seedR = inputData[seedIdx];
var seedG = inputData[seedIdx + 1]; const seedG = inputData[seedIdx + 1];
var seedB = inputData[seedIdx + 2]; const seedB = inputData[seedIdx + 2];
var edge = [seed]; let edge = [seed];
while (edge.length) { while (edge.length) {
var newedge = []; const newedge = [];
for (var i = 0, ii = edge.length; i < ii; i++) { for (let i = 0, ii = edge.length; i < ii; i++) {
// As noted in the Raster source constructor, this function is provided // As noted in the Raster source constructor, this function is provided
// using the `lib` option. Other functions will NOT be visible unless // using the `lib` option. Other functions will NOT be visible unless
// provided using the `lib` option. // provided using the `lib` option.
var next = next4Edges(edge[i]); const next = next4Edges(edge[i]);
for (var j = 0, jj = next.length; j < jj; j++) { for (let j = 0, jj = next.length; j < jj; j++) {
var s = next[j][0], t = next[j][1]; const s = next[j][0];
const t = next[j][1];
if (s >= 0 && s < width && t >= 0 && t < height) { if (s >= 0 && s < width && t >= 0 && t < height) {
var ci = (t * width + s) * 4; const ci = (t * width + s) * 4;
var cr = inputData[ci]; const cr = inputData[ci];
var cg = inputData[ci + 1]; const cg = inputData[ci + 1];
var cb = inputData[ci + 2]; const cb = inputData[ci + 2];
var ca = inputData[ci + 3]; const ca = inputData[ci + 3];
// if alpha is zero, carry on // if alpha is zero, carry on
if (ca === 0) { if (ca === 0) {
continue; continue;
@@ -63,7 +64,8 @@ function growRegion(inputs, data) {
} }
function next4Edges(edge) { function next4Edges(edge) {
var x = edge[0], y = edge[1]; const x = edge[0];
const y = edge[1];
return [ return [
[x + 1, y], [x + 1, y],
[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'}) source: new BingMaps({key: key, imagerySet: 'Aerial'})
}); });
var raster = new RasterSource({ const raster = new RasterSource({
sources: [imagery.getSource()], sources: [imagery.getSource()],
operationType: 'image', operationType: 'image',
operation: growRegion, operation: growRegion,
@@ -89,12 +91,12 @@ var raster = new RasterSource({
} }
}); });
var rasterImage = new ImageLayer({ const rasterImage = new ImageLayer({
opacity: 0.7, opacity: 0.7,
source: raster source: raster
}); });
var map = new Map({ const map = new Map({
layers: [imagery, rasterImage], layers: [imagery, rasterImage],
target: 'map', target: 'map',
view: new View({ view: new View({
@@ -103,18 +105,18 @@ var map = new Map({
}) })
}); });
var coordinate; let coordinate;
map.on('click', function(event) { map.on('click', function(event) {
coordinate = event.coordinate; coordinate = event.coordinate;
raster.changed(); raster.changed();
}); });
var thresholdControl = document.getElementById('threshold'); const thresholdControl = document.getElementById('threshold');
raster.on('beforeoperations', function(event) { raster.on('beforeoperations', function(event) {
// the event.data object will be passed to operations // the event.data object will be passed to operations
var data = event.data; const data = event.data;
data.delta = thresholdControl.value; data.delta = thresholdControl.value;
if (coordinate) { if (coordinate) {
data.pixel = map.getPixelFromCoordinate(coordinate); data.pixel = map.getPixelFromCoordinate(coordinate);

View File

@@ -10,10 +10,10 @@ import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js'; import Style from '../src/ol/style/Style.js';
var stroke = new Stroke({color: 'black', width: 2}); const stroke = new Stroke({color: 'black', width: 2});
var fill = new Fill({color: 'red'}); const fill = new Fill({color: 'red'});
var styles = { const styles = {
'square': new Style({ 'square': new Style({
image: new RegularShape({ image: new RegularShape({
fill: fill, fill: fill,
@@ -66,25 +66,25 @@ var styles = {
}; };
var styleKeys = ['x', 'cross', 'star', 'triangle', 'square']; const styleKeys = ['x', 'cross', 'star', 'triangle', 'square'];
var count = 250; const count = 250;
var features = new Array(count); const features = new Array(count);
var e = 4500000; const e = 4500000;
for (var i = 0; i < count; ++i) { for (let i = 0; i < count; ++i) {
var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; const coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
features[i] = new Feature(new Point(coordinates)); features[i] = new Feature(new Point(coordinates));
features[i].setStyle(styles[styleKeys[Math.floor(Math.random() * 5)]]); features[i].setStyle(styles[styleKeys[Math.floor(Math.random() * 5)]]);
} }
var source = new VectorSource({ const source = new VectorSource({
features: features features: features
}); });
var vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: source source: source
}); });
var map = new Map({ const map = new Map({
layers: [ layers: [
vectorLayer vectorLayer
], ],

Some files were not shown because too many files have changed in this diff Show More