Make code prettier

This updates ESLint and our shared eslint-config-openlayers to use Prettier.  Most formatting changes were automatically applied with this:

    npm run lint -- --fix

A few manual changes were required:

 * In `examples/offscreen-canvas.js`, the `//eslint-disable-line` comment needed to be moved to the appropriate line to disable the error about the `'worker-loader!./offscreen-canvas.worker.js'` import.
 * In `examples/webpack/exapmle-builder.js`, spaces could not be added after a couple `function`s for some reason.  While editing this, I reworked `ExampleBuilder` to be a class.
 * In `src/ol/format/WMSGetFeatureInfo.js`, the `// @ts-ignore` comment needed to be moved down one line so it applied to the `parsersNS` argument.
This commit is contained in:
Tim Schaub
2020-04-06 12:25:12 -06:00
parent 53b48baf62
commit 054af09032
790 changed files with 46833 additions and 33765 deletions

View File

@@ -10,11 +10,10 @@ exports.defineTags = function(dictionary) {
onTagged: function (doclet, tag) { onTagged: function (doclet, tag) {
includeTypes(doclet); includeTypes(doclet);
doclet.stability = 'stable'; doclet.stability = 'stable';
} },
}); });
}; };
/* /*
* Based on @api annotations, and assuming that items with no @api annotation * Based on @api annotations, and assuming that items with no @api annotation
* should not be documented, this plugin removes undocumented symbols * should not be documented, this plugin removes undocumented symbols
@@ -111,11 +110,16 @@ const moduleRoot = path.join(process.cwd(), 'src');
exports.astNodeVisitor = { exports.astNodeVisitor = {
visitNode: function (node, e, parser, currentSourceName) { visitNode: function (node, e, parser, currentSourceName) {
if (node.parent && node.parent.type === 'ExportDefaultDeclaration') { if (node.parent && node.parent.type === 'ExportDefaultDeclaration') {
const modulePath = path.relative(moduleRoot, currentSourceName).replace(/\.js$/, ''); const modulePath = path
const exportName = 'module:' + modulePath.replace(/\\/g, '/') + (node.name ? '~' + node.name : ''); .relative(moduleRoot, currentSourceName)
.replace(/\.js$/, '');
const exportName =
'module:' +
modulePath.replace(/\\/g, '/') +
(node.name ? '~' + node.name : '');
defaultExports[exportName] = true; defaultExports[exportName] = true;
} }
} },
}; };
function sortOtherMembers(doclet) { function sortOtherMembers(doclet) {
@@ -132,7 +136,6 @@ function sortOtherMembers(doclet) {
} }
exports.handlers = { exports.handlers = {
newDoclet: function (e) { newDoclet: function (e) {
const doclet = e.doclet; const doclet = e.doclet;
if (doclet.stability) { if (doclet.stability) {
@@ -183,9 +186,12 @@ exports.handlers = {
// Remove all other undocumented symbols // Remove all other undocumented symbols
doclet.undocumented = true; doclet.undocumented = true;
} }
if (doclet.memberof && byLongname[doclet.memberof] && if (
doclet.memberof &&
byLongname[doclet.memberof] &&
byLongname[doclet.memberof][0].isEnum && byLongname[doclet.memberof][0].isEnum &&
!byLongname[doclet.memberof][0].properties.some(p => p.stability)) { !byLongname[doclet.memberof][0].properties.some((p) => p.stability)
) {
byLongname[doclet.memberof][0].undocumented = true; byLongname[doclet.memberof][0].undocumented = true;
} }
} }
@@ -198,6 +204,5 @@ exports.handlers = {
doclet.isDefaultExport = true; doclet.isDefaultExport = true;
}); });
} }
} },
}; };

View File

@@ -1,7 +1,6 @@
const events = {}; const events = {};
exports.handlers = { exports.handlers = {
newDoclet: function (e) { newDoclet: function (e) {
const doclet = e.doclet; const doclet = e.doclet;
if (doclet.kind !== 'event') { if (doclet.kind !== 'event') {
@@ -34,6 +33,5 @@ exports.handlers = {
} }
} }
} }
} },
}; };

View File

@@ -6,7 +6,6 @@
const properties = {}; const properties = {};
exports.handlers = { exports.handlers = {
/** /**
* Collects all typedefs, keyed by longname * Collects all typedefs, keyed by longname
* @param {Object} e Event object. * @param {Object} e Event object.
@@ -34,16 +33,18 @@ exports.handlers = {
const type = param.type.names[0]; const type = param.type.names[0];
if (type in properties) { if (type in properties) {
param.type.names[0] = type; param.type.names[0] = type;
params.push.apply(params, properties[type].map(p => { params.push.apply(
params,
properties[type].map((p) => {
const property = Object.assign({}, p); const property = Object.assign({}, p);
property.name = `${param.name}.${property.name}`; property.name = `${param.name}.${property.name}`;
return property; return property;
})); })
);
} }
} }
} }
} }
} }
} },
}; };

View File

@@ -19,7 +19,7 @@ const tags = [
'properties', 'properties',
'returns', 'returns',
'see', 'see',
'summary' 'summary',
]; ];
const hasOwnProp = Object.prototype.hasOwnProperty; const hasOwnProp = Object.prototype.hasOwnProperty;
@@ -30,29 +30,29 @@ const markedRenderer = new marked.Renderer();
markedRenderer.code = function (code, language) { markedRenderer.code = function (code, language) {
const langClass = language ? ' lang-' + language : ''; const langClass = language ? ' lang-' + language : '';
return format('<pre class="prettyprint source%s"><code>%s</code></pre>', return format(
langClass, escapeCode(code)); '<pre class="prettyprint source%s"><code>%s</code></pre>',
langClass,
escapeCode(code)
);
}; };
function escapeCode(source) { function escapeCode(source) {
return source.replace(/</g, '&lt;') return source
.replace(/</g, '&lt;')
.replace(/"/g, '&quot;') .replace(/"/g, '&quot;')
.replace(/'/g, '&#39;'); .replace(/'/g, '&#39;');
} }
function escapeUnderscoresAndTildes(source) { function escapeUnderscoresAndTildes(source) {
return source.replace(/\{@[^}\r\n]+\}/g, function (wholeMatch) { return source.replace(/\{@[^}\r\n]+\}/g, function (wholeMatch) {
return wholeMatch return wholeMatch.replace(/(^|[^\\])_/g, '$1\\_').replace('~', '&tilde;');
.replace(/(^|[^\\])_/g, '$1\\_')
.replace('~', '&tilde;');
}); });
} }
function unencodeQuotesAndTildes(source) { function unencodeQuotesAndTildes(source) {
return source.replace(/\{@[^}\r\n]+\}/g, function (wholeMatch) { return source.replace(/\{@[^}\r\n]+\}/g, function (wholeMatch) {
return wholeMatch return wholeMatch.replace(/&quot;/g, '"').replace(/&tilde;/g, '~');
.replace(/&quot;/g, '"')
.replace(/&tilde;/g, '~');
}); });
} }
@@ -63,7 +63,7 @@ function parse(source) {
result = marked(source, {renderer: markedRenderer}) result = marked(source, {renderer: markedRenderer})
.replace(/\s+$/, '') .replace(/\s+$/, '')
.replace(/&#39;/g, '\''); .replace(/&#39;/g, "'");
result = unencodeQuotesAndTildes(result); result = unencodeQuotesAndTildes(result);
@@ -87,7 +87,10 @@ function process(doclet) {
return; return;
} }
if (typeof doclet[tag] === 'string' && shouldProcessString(tag, doclet[tag])) { if (
typeof doclet[tag] === 'string' &&
shouldProcessString(tag, doclet[tag])
) {
doclet[tag] = parse(doclet[tag]); doclet[tag] = parse(doclet[tag]);
} else if (Array.isArray(doclet[tag])) { } else if (Array.isArray(doclet[tag])) {
doclet[tag].forEach(function (value, index, original) { doclet[tag].forEach(function (value, index, original) {
@@ -103,9 +106,8 @@ function process(doclet) {
}); });
} }
exports.handlers = { exports.handlers = {
newDoclet: function (e) { newDoclet: function (e) {
process(e.doclet); process(e.doclet);
} },
}; };

View File

@@ -2,7 +2,6 @@ const classes = {};
const observables = {}; const observables = {};
exports.handlers = { exports.handlers = {
newDoclet: function (e) { newDoclet: function (e) {
const doclet = e.doclet; const doclet = e.doclet;
if (doclet.kind == 'class' && !(doclet.longname in classes)) { if (doclet.kind == 'class' && !(doclet.longname in classes)) {
@@ -26,8 +25,8 @@ exports.handlers = {
} }
observable = observables[key]; observable = observables[key];
observable.name = name; observable.name = name;
observable.readonly = typeof observable.readonly == 'boolean' ? observable.readonly =
observable.readonly : true; typeof observable.readonly == 'boolean' ? observable.readonly : true;
if (doclet.name.indexOf('get') === 0) { if (doclet.name.indexOf('get') === 0) {
observable.type = doclet.returns[0].type; observable.type = doclet.returns[0].type;
observable.description = doclet.returns[0].description; observable.description = doclet.returns[0].description;
@@ -53,8 +52,7 @@ exports.handlers = {
} }
} }
} }
} },
}; };
exports.defineTags = function (dictionary) { exports.defineTags = function (dictionary) {
@@ -64,6 +62,6 @@ exports.defineTags = function(dictionary) {
canHaveName: false, canHaveName: false,
onTagged: function (doclet, tag) { onTagged: function (doclet, tag) {
doclet.observable = ''; doclet.observable = '';
} },
}); });
}; };

View File

@@ -31,7 +31,11 @@ function find(spec) {
} }
function tutoriallink(tutorial) { function tutoriallink(tutorial) {
return helper.toTutorial(tutorial, null, {tag: 'em', classname: 'disabled', prefix: 'Tutorial: '}); return helper.toTutorial(tutorial, null, {
tag: 'em',
classname: 'disabled',
prefix: 'Tutorial: ',
});
} }
function getAncestorLinks(doclet) { function getAncestorLinks(doclet) {
@@ -55,8 +59,12 @@ function needsSignature(doclet) {
// function and class definitions always get a signature // function and class definitions always get a signature
if (doclet.kind === 'function' || doclet.kind === 'class') { if (doclet.kind === 'function' || doclet.kind === 'class') {
needsSig = true; needsSig = true;
} else if (doclet.kind === 'typedef' && doclet.type && doclet.type.names && } else if (
doclet.type.names.length) { doclet.kind === 'typedef' &&
doclet.type &&
doclet.type.names &&
doclet.type.names.length
) {
// typedefs that contain functions get a signature, too // typedefs that contain functions get a signature, too
for (let i = 0, l = doclet.type.names.length; i < l; i++) { for (let i = 0, l = doclet.type.names.length; i < l; i++) {
if (doclet.type.names[i].toLowerCase() === 'function') { if (doclet.type.names[i].toLowerCase() === 'function') {
@@ -81,14 +89,21 @@ function addSignatureReturns(f) {
f.signature = '<span class="signature">' + (f.signature || '') + '</span>'; f.signature = '<span class="signature">' + (f.signature || '') + '</span>';
if (returnTypes.length) { if (returnTypes.length) {
f.signature += '<span class="glyphicon glyphicon-circle-arrow-right"></span><span class="type-signature returnType">' + (returnTypes.length ? '{' + returnTypes.join('|') + '}' : '') + '</span>'; f.signature +=
'<span class="glyphicon glyphicon-circle-arrow-right"></span><span class="type-signature returnType">' +
(returnTypes.length ? '{' + returnTypes.join('|') + '}' : '') +
'</span>';
} }
} }
function addSignatureTypes(f) { function addSignatureTypes(f) {
const types = helper.getSignatureTypes(f); const types = helper.getSignatureTypes(f);
f.signature = (f.signature || '') + '<span class="type-signature">' + (types.length ? ' :' + types.join('|') : '') + ' </span>'; f.signature =
(f.signature || '') +
'<span class="type-signature">' +
(types.length ? ' :' + types.join('|') : '') +
' </span>';
} }
function shortenPaths(files, commonPrefix) { function shortenPaths(files, commonPrefix) {
@@ -96,7 +111,8 @@ function shortenPaths(files, commonPrefix) {
const regexp = new RegExp('\\\\', 'g'); const regexp = new RegExp('\\\\', 'g');
Object.keys(files).forEach(function (file) { Object.keys(files).forEach(function (file) {
files[file].shortened = files[file].resolved.replace(commonPrefix, '') files[file].shortened = files[file].resolved
.replace(commonPrefix, '')
.replace(regexp, '/'); .replace(regexp, '/');
}); });
@@ -112,9 +128,10 @@ function getPathFromDoclet(doclet) {
return; return;
} }
const filepath = doclet.meta.path && doclet.meta.path !== 'null' ? const filepath =
doclet.meta.path + '/' + doclet.meta.filename.split(/[\/\\]/).pop() : doclet.meta.path && doclet.meta.path !== 'null'
doclet.meta.filename; ? doclet.meta.path + '/' + doclet.meta.filename.split(/[\/\\]/).pop()
: doclet.meta.filename;
return filepath; return filepath;
} }
@@ -126,7 +143,7 @@ function generate(title, docs, filename, resolveLinks) {
filename: filename, filename: filename,
title: title, title: title,
docs: docs, docs: docs,
packageInfo: (find({kind: 'package'}) || []) [0] packageInfo: (find({kind: 'package'}) || [])[0],
}; };
const outpath = path.join(outdir, filename); const outpath = path.join(outdir, filename);
@@ -149,14 +166,20 @@ function generateSourceFiles(sourceFiles) {
try { try {
source = { source = {
kind: 'source', kind: 'source',
code: helper.htmlsafe(fs.readFileSync(sourceFiles[file].resolved, 'utf8')) code: helper.htmlsafe(
fs.readFileSync(sourceFiles[file].resolved, 'utf8')
),
}; };
} catch (e) { } catch (e) {
handle(e); handle(e);
} }
generate('Source: ' + sourceFiles[file].shortened, [source], sourceOutfile, generate(
false); 'Source: ' + sourceFiles[file].shortened,
[source],
sourceOutfile,
false
);
}); });
} }
@@ -182,7 +205,8 @@ function attachModuleSymbols(doclets, modules) {
modules.forEach(function (module) { modules.forEach(function (module) {
if (symbols[module.longname]) { if (symbols[module.longname]) {
module.module = symbols[module.longname]; module.module = symbols[module.longname];
module.module.name = module.module.name.replace('module:', 'require("') + '")'; module.module.name =
module.module.name.replace('module:', 'require("') + '")';
} }
}); });
} }
@@ -220,52 +244,55 @@ function buildNav(members) {
name: v.name, name: v.name,
module: find({ module: find({
kind: 'module', kind: 'module',
longname: v.memberof longname: v.memberof,
})[0], })[0],
members: find({ members: find({
kind: 'member', kind: 'member',
memberof: v.longname memberof: v.longname,
}), }),
methods: find({ methods: find({
kind: 'function', kind: 'function',
memberof: v.longname memberof: v.longname,
}), }),
typedefs: find({ typedefs: find({
kind: 'typedef', kind: 'typedef',
memberof: v.longname memberof: v.longname,
}), }),
fires: v.fires, fires: v.fires,
events: find({ events: find({
kind: 'event', kind: 'event',
memberof: v.longname memberof: v.longname,
}) }),
}); });
} }
}); });
members.modules.forEach(function (v) { members.modules.forEach(function (v) {
const classes = find({ const classes = find({
kind: 'class', kind: 'class',
memberof: v.longname memberof: v.longname,
}); });
const members = find({ const members = find({
kind: 'member', kind: 'member',
memberof: v.longname memberof: v.longname,
}); });
const methods = find({ const methods = find({
kind: 'function', kind: 'function',
memberof: v.longname memberof: v.longname,
}); });
const typedefs = find({ const typedefs = find({
kind: 'typedef', kind: 'typedef',
memberof: v.longname memberof: v.longname,
}); });
const events = find({ const events = find({
kind: 'event', kind: 'event',
memberof: v.longname memberof: v.longname,
}); });
// Only add modules that contain more than just classes with their // Only add modules that contain more than just classes with their
// associated Options typedef // associated Options typedef
if (typedefs.length > classes.length || members.length + methods.length > 0) { if (
typedefs.length > classes.length ||
members.length + methods.length > 0
) {
nav.push({ nav.push({
type: 'module', type: 'module',
longname: v.longname, longname: v.longname,
@@ -275,7 +302,7 @@ function buildNav(members) {
methods: methods, methods: methods,
typedefs: typedefs, typedefs: typedefs,
fires: v.fires, fires: v.fires,
events: events events: events,
}); });
} }
}); });
@@ -294,7 +321,6 @@ function buildNav(members) {
return nav; return nav;
} }
/** /**
* @param {Object} taffyData See <http://taffydb.com/>. * @param {Object} taffyData See <http://taffydb.com/>.
* @param {Object} opts Options. * @param {Object} opts Options.
@@ -336,14 +362,18 @@ exports.publish = function(taffyData, opts, tutorials) {
doclet.examples = doclet.examples.map(function (example) { doclet.examples = doclet.examples.map(function (example) {
let caption, code; let caption, code;
if (example.match(/^\s*<caption>([\s\S]+?)<\/caption>(\s*[\n\r])([\s\S]+)$/i)) { if (
example.match(
/^\s*<caption>([\s\S]+?)<\/caption>(\s*[\n\r])([\s\S]+)$/i
)
) {
caption = RegExp.$1; caption = RegExp.$1;
code = RegExp.$3; code = RegExp.$3;
} }
return { return {
caption: caption || '', caption: caption || '',
code: code || example code: code || example,
}; };
}); });
} }
@@ -361,7 +391,7 @@ exports.publish = function(taffyData, opts, tutorials) {
resolvedSourcePath = resolveSourcePath(sourcePath); resolvedSourcePath = resolveSourcePath(sourcePath);
sourceFiles[sourcePath] = { sourceFiles[sourcePath] = {
resolved: resolvedSourcePath, resolved: resolvedSourcePath,
shortened: null shortened: null,
}; };
sourceFilePaths.push(resolvedSourcePath); sourceFilePaths.push(resolvedSourcePath);
} }
@@ -385,15 +415,22 @@ exports.publish = function(taffyData, opts, tutorials) {
let staticFileScanner; let staticFileScanner;
if (conf['default'].staticFiles) { if (conf['default'].staticFiles) {
staticFilePaths = conf['default'].staticFiles.paths || []; staticFilePaths = conf['default'].staticFiles.paths || [];
staticFileFilter = new (require('jsdoc/lib/jsdoc/src/filter')).Filter(conf['default'].staticFiles); staticFileFilter = new (require('jsdoc/lib/jsdoc/src/filter').Filter)(
staticFileScanner = new (require('jsdoc/lib/jsdoc/src/scanner')).Scanner(); conf['default'].staticFiles
);
staticFileScanner = new (require('jsdoc/lib/jsdoc/src/scanner').Scanner)();
staticFilePaths.forEach(function (filePath) { staticFilePaths.forEach(function (filePath) {
const extraStaticFiles = staticFileScanner.scan([filePath], 10, staticFileFilter); const extraStaticFiles = staticFileScanner.scan(
[filePath],
10,
staticFileFilter
);
extraStaticFiles.forEach(function (fileName) { extraStaticFiles.forEach(function (fileName) {
const sourcePath = fs.statSync(filePath).isDirectory() ? filePath : const sourcePath = fs.statSync(filePath).isDirectory()
path.dirname(filePath); ? filePath
: path.dirname(filePath);
const toDir = fs.toDir(fileName.replace(sourcePath, outdir)); const toDir = fs.toDir(fileName.replace(sourcePath, outdir));
fs.mkPath(toDir); fs.mkPath(toDir);
fs.copyFileSync(fileName, toDir); fs.copyFileSync(fileName, toDir);
@@ -461,8 +498,10 @@ exports.publish = function(taffyData, opts, tutorials) {
// once for all // once for all
view.nav = buildNav(members); view.nav = buildNav(members);
attachModuleSymbols(find({kind: ['class', 'function'], longname: {left: 'module:'}}), attachModuleSymbols(
members.modules); find({kind: ['class', 'function'], longname: {left: 'module:'}}),
members.modules
);
// only output pretty-printed source files if requested; do this before generating any other // only output pretty-printed source files if requested; do this before generating any other
// pages, so the other pages can link to the source files // pages, so the other pages can link to the source files
@@ -478,9 +517,17 @@ exports.publish = function(taffyData, opts, tutorials) {
const files = find({kind: 'file'}); const files = find({kind: 'file'});
view.navigationHtml = helper.resolveLinks(view.partial('navigation.tmpl')); view.navigationHtml = helper.resolveLinks(view.partial('navigation.tmpl'));
generate('Index', generate(
[{kind: 'mainpage', readme: opts.readme, longname: (opts.mainpagetitle) ? opts.mainpagetitle : 'Main Page'}].concat(files), 'Index',
indexUrl); [
{
kind: 'mainpage',
readme: opts.readme,
longname: opts.mainpagetitle ? opts.mainpagetitle : 'Main Page',
},
].concat(files),
indexUrl
);
// set up the lists that we'll use to generate pages // set up the lists that we'll use to generate pages
const classes = taffy(members.classes); const classes = taffy(members.classes);
@@ -493,27 +540,47 @@ exports.publish = function(taffyData, opts, tutorials) {
if (hasOwnProp.call(helper.longnameToUrl, longname)) { if (hasOwnProp.call(helper.longnameToUrl, longname)) {
const myClasses = helper.find(classes, {longname: longname}); const myClasses = helper.find(classes, {longname: longname});
if (myClasses.length) { if (myClasses.length) {
generate('Class: ' + myClasses[0].name, myClasses, helper.longnameToUrl[longname]); generate(
'Class: ' + myClasses[0].name,
myClasses,
helper.longnameToUrl[longname]
);
} }
const myModules = helper.find(modules, {longname: longname}); const myModules = helper.find(modules, {longname: longname});
if (myModules.length) { if (myModules.length) {
generate('Module: ' + myModules[0].name, myModules, helper.longnameToUrl[longname]); generate(
'Module: ' + myModules[0].name,
myModules,
helper.longnameToUrl[longname]
);
} }
const myNamespaces = helper.find(namespaces, {longname: longname}); const myNamespaces = helper.find(namespaces, {longname: longname});
if (myNamespaces.length) { if (myNamespaces.length) {
generate('Namespace: ' + myNamespaces[0].name, myNamespaces, helper.longnameToUrl[longname]); generate(
'Namespace: ' + myNamespaces[0].name,
myNamespaces,
helper.longnameToUrl[longname]
);
} }
const myMixins = helper.find(mixins, {longname: longname}); const myMixins = helper.find(mixins, {longname: longname});
if (myMixins.length) { if (myMixins.length) {
generate('Mixin: ' + myMixins[0].name, myMixins, helper.longnameToUrl[longname]); generate(
'Mixin: ' + myMixins[0].name,
myMixins,
helper.longnameToUrl[longname]
);
} }
const myExternals = helper.find(externals, {longname: longname}); const myExternals = helper.find(externals, {longname: longname});
if (myExternals.length) { if (myExternals.length) {
generate('External: ' + myExternals[0].name, myExternals, helper.longnameToUrl[longname]); generate(
'External: ' + myExternals[0].name,
myExternals,
helper.longnameToUrl[longname]
);
} }
} }
} }
@@ -524,7 +591,7 @@ exports.publish = function(taffyData, opts, tutorials) {
title: title, title: title,
header: tutorial.title, header: tutorial.title,
content: tutorial.parse(), content: tutorial.parse(),
children: tutorial.children children: tutorial.children,
}; };
let html = view.render('tutorial.tmpl', tutorialData); let html = view.render('tutorial.tmpl', tutorialData);
@@ -538,7 +605,11 @@ exports.publish = function(taffyData, opts, tutorials) {
// tutorials can have only one parent so there is no risk for loops // tutorials can have only one parent so there is no risk for loops
function saveChildren(node) { function saveChildren(node) {
node.children.forEach(function (child) { node.children.forEach(function (child) {
generateTutorial('Tutorial: ' + child.title, child, helper.tutorialToUrl(child.name)); generateTutorial(
'Tutorial: ' + child.title,
child,
helper.tutorialToUrl(child.name)
);
saveChildren(child); saveChildren(child);
}); });
} }

View File

@@ -1,15 +1,11 @@
/** /**
* Handle the api annotation. * Handle the api annotation.
* @param {Object} dictionary The tag dictionary. * @param {Object} dictionary The tag dictionary.
*/ */
exports.defineTags = function (dictionary) { exports.defineTags = function (dictionary) {
dictionary.defineTag('api', { dictionary.defineTag('api', {
onTagged: function (doclet, tag) { onTagged: function (doclet, tag) {
doclet.api = true; doclet.api = true;
} },
}); });
}; };

View File

@@ -5,16 +5,13 @@
* insensitive, with or without ticks). * insensitive, with or without ticks).
*/ */
const DEFAULT_VALUE = /default\s+is\s+`?(true|false)`?/i; const DEFAULT_VALUE = /default\s+is\s+`?(true|false)`?/i;
/** /**
* Hook to define new tags. * Hook to define new tags.
* @param {Object} dictionary The tag dictionary. * @param {Object} dictionary The tag dictionary.
*/ */
exports.defineTags = function (dictionary) { exports.defineTags = function (dictionary) {
dictionary.defineTag('define', { dictionary.defineTag('define', {
canHaveType: true, canHaveType: true,
mustHaveValue: true, mustHaveValue: true,
@@ -24,12 +21,11 @@ exports.defineTags = function(dictionary) {
const match = tag.value.description.match(DEFAULT_VALUE); const match = tag.value.description.match(DEFAULT_VALUE);
if (match) { if (match) {
doclet.define = { doclet.define = {
default: match[1] === 'true' default: match[1] === 'true',
}; };
doclet.description = tag.value.description; doclet.description = tag.value.description;
} }
} }
} },
}); });
}; };

View File

@@ -5,7 +5,6 @@
const assert = require('assert'); const assert = require('assert');
const path = require('path'); const path = require('path');
/** /**
* Publish hook for the JSDoc template. Writes to JSON stdout. * Publish hook for the JSDoc template. Writes to JSON stdout.
* @param {function} data The root of the Taffy DB containing doclet records. * @param {function} data The root of the Taffy DB containing doclet records.
@@ -13,7 +12,6 @@ const path = require('path');
* @return {Promise} A promise that resolves when writing is complete. * @return {Promise} A promise that resolves when writing is complete.
*/ */
exports.publish = function (data, opts) { exports.publish = function (data, opts) {
function getTypes(data) { function getTypes(data) {
const types = []; const types = [];
data.forEach(function (name) { data.forEach(function (name) {
@@ -34,12 +32,15 @@ exports.publish = function(data, opts) {
return true; return true;
} }
} }
return (typeof this.api == 'boolean' || return (
this.meta && (/[\\\/]externs$/).test(this.meta.path)); typeof this.api == 'boolean' ||
} (this.meta && /[\\\/]externs$/.test(this.meta.path))
);
},
], ],
{kind: {'!is': 'file'}}, {kind: {'!is': 'file'}},
{kind: {'!is': 'event'}}).get(); {kind: {'!is': 'event'}}
).get();
// get symbols data, filter out those that are members of private classes // get symbols data, filter out those that are members of private classes
const symbols = []; const symbols = [];
@@ -49,35 +50,44 @@ exports.publish = function(data, opts) {
let base = []; let base = [];
const augments = {}; const augments = {};
const symbolsByName = {}; const symbolsByName = {};
docs.filter(function(doc) { docs
.filter(function (doc) {
let include = true; let include = true;
const constructor = doc.memberof; const constructor = doc.memberof;
if (constructor && constructor.substr(-1) === '_' && constructor.indexOf('module:') === -1) { if (
assert.strictEqual(doc.inherited, true, constructor &&
'Unexpected export on private class: ' + doc.longname); constructor.substr(-1) === '_' &&
constructor.indexOf('module:') === -1
) {
assert.strictEqual(
doc.inherited,
true,
'Unexpected export on private class: ' + doc.longname
);
include = false; include = false;
} }
return include; return include;
}).forEach(function(doc) { })
const isExterns = (/[\\\/]externs$/).test(doc.meta.path); .forEach(function (doc) {
const isExterns = /[\\\/]externs$/.test(doc.meta.path);
if (doc.define) { if (doc.define) {
defines.push({ defines.push({
name: doc.longname, name: doc.longname,
description: doc.description, description: doc.description,
path: path.join(doc.meta.path, doc.meta.filename), path: path.join(doc.meta.path, doc.meta.filename),
default: doc.define.default default: doc.define.default,
}); });
} else if (doc.kind == 'typedef' || doc.isEnum === true) { } else if (doc.kind == 'typedef' || doc.isEnum === true) {
typedefs.push({ typedefs.push({
name: doc.longname, name: doc.longname,
types: getTypes(doc.type.names) types: getTypes(doc.type.names),
}); });
} else { } else {
const symbol = { const symbol = {
name: doc.longname, name: doc.longname,
kind: doc.kind, kind: doc.kind,
description: doc.classdesc || doc.description, description: doc.classdesc || doc.description,
path: path.join(doc.meta.path, doc.meta.filename) path: path.join(doc.meta.path, doc.meta.filename),
}; };
if (doc.augments) { if (doc.augments) {
symbol.extends = doc.augments[0]; symbol.extends = doc.augments[0];
@@ -92,7 +102,7 @@ exports.publish = function(data, opts) {
const params = []; const params = [];
doc.params.forEach(function (param) { doc.params.forEach(function (param) {
const paramInfo = { const paramInfo = {
name: param.name name: param.name,
}; };
params.push(paramInfo); params.push(paramInfo);
paramInfo.types = getTypes(param.type.names); paramInfo.types = getTypes(param.type.names);
@@ -110,7 +120,7 @@ exports.publish = function(data, opts) {
} }
if (doc.returns) { if (doc.returns) {
symbol.returns = { symbol.returns = {
types: getTypes(doc.returns[0].type.names) types: getTypes(doc.returns[0].type.names),
}; };
if (typeof doc.returns[0].nullable == 'boolean') { if (typeof doc.returns[0].nullable == 'boolean') {
symbol.returns.nullable = doc.returns[0].nullable; symbol.returns.nullable = doc.returns[0].nullable;
@@ -126,7 +136,7 @@ exports.publish = function(data, opts) {
}); });
} }
const target = isExterns ? externs : (doc.api ? symbols : base); const target = isExterns ? externs : doc.api ? symbols : base;
const existingSymbol = symbolsByName[symbol.name]; const existingSymbol = symbolsByName[symbol.name];
if (existingSymbol) { if (existingSymbol) {
const idx = target.indexOf(existingSymbol); const idx = target.indexOf(existingSymbol);
@@ -136,8 +146,11 @@ exports.publish = function(data, opts) {
symbolsByName[symbol.name] = symbol; symbolsByName[symbol.name] = symbol;
if (doc.api && symbol.extends) { if (doc.api && symbol.extends) {
while (symbol.extends in classes && !classes[symbol.extends].api && while (
classes[symbol.extends].augments) { symbol.extends in classes &&
!classes[symbol.extends].api &&
classes[symbol.extends].augments
) {
symbol.extends = classes[symbol.extends].augments[0]; symbol.extends = classes[symbol.extends].augments[0];
} }
if (symbol.extends) { if (symbol.extends) {
@@ -148,18 +161,22 @@ exports.publish = function(data, opts) {
}); });
base = base.filter(function (symbol) { base = base.filter(function (symbol) {
return (symbol.name in augments || symbol.virtual); return symbol.name in augments || symbol.virtual;
}); });
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
process.stdout.write( process.stdout.write(
JSON.stringify({ JSON.stringify(
{
symbols: symbols, symbols: symbols,
defines: defines, defines: defines,
typedefs: typedefs, typedefs: typedefs,
externs: externs, externs: externs,
base: base base: base,
}, null, 2)); },
null,
2
)
);
}); });
}; };

View File

@@ -3,14 +3,12 @@
* @param {Object} dictionary The tag dictionary. * @param {Object} dictionary The tag dictionary.
*/ */
exports.defineTags = function (dictionary) { exports.defineTags = function (dictionary) {
const classTag = dictionary.lookUp('class'); const classTag = dictionary.lookUp('class');
dictionary.defineTag('interface', { dictionary.defineTag('interface', {
mustNotHaveValue: true, mustNotHaveValue: true,
onTagged: function (doclet, tag) { onTagged: function (doclet, tag) {
classTag.onTagged.apply(this, arguments); classTag.onTagged.apply(this, arguments);
doclet.virtual = true; doclet.virtual = true;
} },
}); });
}; };

View File

@@ -8,6 +8,6 @@ module.exports = {
filename: 'ol.js', filename: 'ol.js',
library: 'ol', library: 'ol',
libraryTarget: 'umd', libraryTarget: 'umd',
libraryExport: 'default' libraryExport: 'default',
} },
}; };

View File

@@ -1,20 +1,19 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
document.getElementById('zoom-out').onclick = function () { document.getElementById('zoom-out').onclick = function () {

View File

@@ -1,9 +1,9 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import OSM from '../src/ol/source/OSM.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {easeIn, easeOut} from '../src/ol/easing.js'; import {easeIn, easeOut} from '../src/ol/easing.js';
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';
const london = fromLonLat([-0.12755, 51.507222]); const london = fromLonLat([-0.12755, 51.507222]);
const moscow = fromLonLat([37.6178, 55.7517]); const moscow = fromLonLat([37.6178, 55.7517]);
@@ -13,7 +13,7 @@ const bern = fromLonLat([7.4458, 46.95]);
const view = new View({ const view = new View({
center: istanbul, center: istanbul,
zoom: 6 zoom: 6,
}); });
const map = new Map({ const map = new Map({
@@ -21,10 +21,10 @@ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
preload: 4, preload: 4,
source: new OSM() source: new OSM(),
}) }),
], ],
view: view view: view,
}); });
// A bounce easing method (from https://github.com/DmitryBaranovskiy/raphael). // A bounce easing method (from https://github.com/DmitryBaranovskiy/raphael).
@@ -32,18 +32,18 @@ function bounce(t) {
const s = 7.5625; const s = 7.5625;
const p = 2.75; const p = 2.75;
let l; let l;
if (t < (1 / p)) { if (t < 1 / p) {
l = s * t * t; l = s * t * t;
} else { } else {
if (t < (2 / p)) { if (t < 2 / p) {
t -= (1.5 / p); t -= 1.5 / p;
l = s * t * t + 0.75; l = s * t * t + 0.75;
} else { } else {
if (t < (2.5 / p)) { if (t < 2.5 / p) {
t -= (2.25 / p); t -= 2.25 / p;
l = s * t * t + 0.9375; l = s * t * t + 0.9375;
} else { } else {
t -= (2.625 / p); t -= 2.625 / p;
l = s * t * t + 0.984375; l = s * t * t + 0.984375;
} }
} }
@@ -53,7 +53,9 @@ function bounce(t) {
// An elastic easing method (from https://github.com/DmitryBaranovskiy/raphael). // An elastic easing method (from https://github.com/DmitryBaranovskiy/raphael).
function elastic(t) { function elastic(t) {
return Math.pow(2, -10 * t) * Math.sin((t - 0.075) * (2 * Math.PI) / 0.3) + 1; return (
Math.pow(2, -10 * t) * Math.sin(((t - 0.075) * (2 * Math.PI)) / 0.3) + 1
);
} }
function onClick(id, callback) { function onClick(id, callback) {
@@ -62,34 +64,37 @@ function onClick(id, callback) {
onClick('rotate-left', function () { onClick('rotate-left', function () {
view.animate({ view.animate({
rotation: view.getRotation() + Math.PI / 2 rotation: view.getRotation() + Math.PI / 2,
}); });
}); });
onClick('rotate-right', function () { onClick('rotate-right', function () {
view.animate({ view.animate({
rotation: view.getRotation() - Math.PI / 2 rotation: view.getRotation() - Math.PI / 2,
}); });
}); });
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
const rotation = view.getRotation(); const rotation = view.getRotation();
view.animate({ view.animate(
{
rotation: rotation + Math.PI, rotation: rotation + Math.PI,
anchor: rome, anchor: rome,
easing: easeIn easing: easeIn,
}, { },
{
rotation: rotation + 2 * Math.PI, rotation: rotation + 2 * Math.PI,
anchor: rome, anchor: rome,
easing: easeOut easing: easeOut,
}); }
);
}); });
onClick('pan-to-london', function () { onClick('pan-to-london', function () {
view.animate({ view.animate({
center: london, center: london,
duration: 2000 duration: 2000,
}); });
}); });
@@ -97,7 +102,7 @@ onClick('elastic-to-moscow', function() {
view.animate({ view.animate({
center: moscow, center: moscow,
duration: 2000, duration: 2000,
easing: elastic easing: elastic,
}); });
}); });
@@ -105,25 +110,28 @@ onClick('bounce-to-istanbul', function() {
view.animate({ view.animate({
center: istanbul, center: istanbul,
duration: 2000, duration: 2000,
easing: bounce easing: bounce,
}); });
}); });
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
const 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,
center[1] + (rome[1] - center[1]) / 2 center[1] + (rome[1] - center[1]) / 2,
], ],
rotation: Math.PI, rotation: Math.PI,
easing: easeIn easing: easeIn,
}, { },
{
center: rome, center: rome,
rotation: 2 * Math.PI, rotation: 2 * Math.PI,
easing: easeOut easing: easeOut,
}); }
);
}); });
function flyTo(location, done) { function flyTo(location, done) {
@@ -141,17 +149,24 @@ function flyTo(location, done) {
done(complete); done(complete);
} }
} }
view.animate({ view.animate(
{
center: location, center: location,
duration: duration duration: duration,
}, callback); },
view.animate({ callback
);
view.animate(
{
zoom: zoom - 1, zoom: zoom - 1,
duration: duration / 2 duration: duration / 2,
}, { },
{
zoom: zoom, zoom: zoom,
duration: duration / 2 duration: duration / 2,
}, callback); },
callback
);
} }
onClick('fly-to-bern', function () { onClick('fly-to-bern', function () {

View File

@@ -1,28 +1,29 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {Tile as TileLayer, Image as ImageLayer} from '../src/ol/layer.js'; import {ImageArcGISRest, OSM} from '../src/ol/source.js';
import {OSM, ImageArcGISRest} from '../src/ol/source.js'; import {Image as ImageLayer, Tile as TileLayer} from '../src/ol/layer.js';
const 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';
const layers = [ const layers = [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
new ImageLayer({ new ImageLayer({
source: new ImageArcGISRest({ source: new ImageArcGISRest({
ratio: 1, ratio: 1,
params: {}, params: {},
url: url url: url,
}) }),
}) }),
]; ];
const map = new Map({ const map = new Map({
layers: layers, layers: layers,
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-10997148, 4569099], center: [-10997148, 4569099],
zoom: 4 zoom: 4,
}) }),
}); });

View File

@@ -1,27 +1,28 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {OSM, TileArcGISRest} from '../src/ol/source.js'; import {OSM, TileArcGISRest} from '../src/ol/source.js';
const 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';
const layers = [ const layers = [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
new TileLayer({ new TileLayer({
extent: [-13884991, 2870341, -7455066, 6338219], extent: [-13884991, 2870341, -7455066, 6338219],
source: new TileArcGISRest({ source: new TileArcGISRest({
url: url url: url,
}) }),
}) }),
]; ];
const map = new Map({ const map = new Map({
layers: layers, layers: layers,
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-10997148, 4569099], center: [-10997148, 4569099],
zoom: 4 zoom: 4,
}) }),
}); });

View File

@@ -1,24 +1,24 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {defaults as defaultControls, Attribution} from '../src/ol/control.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {Attribution, defaults as defaultControls} from '../src/ol/control.js';
const attribution = new Attribution({ const attribution = new Attribution({
collapsible: false collapsible: false,
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
controls: defaultControls({attribution: false}).extend([attribution]), controls: defaultControls({attribution: false}).extend([attribution]),
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
function checkSize() { function checkSize() {

View File

@@ -1,38 +1,40 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
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 Map from '../src/ol/Map.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
const styles = [ const styles = [
'RoadOnDemand', 'RoadOnDemand',
'Aerial', 'Aerial',
'AerialWithLabelsOnDemand', 'AerialWithLabelsOnDemand',
'CanvasDark', 'CanvasDark',
'OrdnanceSurvey' 'OrdnanceSurvey',
]; ];
const layers = []; const layers = [];
let 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,
preload: Infinity, preload: Infinity,
source: new BingMaps({ source: new BingMaps({
key: 'ApTJzdkyN1DdFKkRAE6QIDtzihNaf6IWJsT-nQ_2eMoO4PN__0Tzhl2-WgJtXFSp ', key:
imagerySet: styles[i] 'ApTJzdkyN1DdFKkRAE6QIDtzihNaf6IWJsT-nQ_2eMoO4PN__0Tzhl2-WgJtXFSp ',
imagerySet: styles[i],
// use maxZoom 19 to see stretched tiles instead of the BingMaps // use maxZoom 19 to see stretched tiles instead of the BingMaps
// "no photos at this zoom level" tiles // "no photos at this zoom level" tiles
// maxZoom: 19 // maxZoom: 19
}),
}) })
})); );
} }
const map = new Map({ const map = new Map({
layers: layers, layers: layers,
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-6655.5402445057125, 6709968.258934638], center: [-6655.5402445057125, 6709968.258934638],
zoom: 13 zoom: 13,
}) }),
}); });
const select = document.getElementById('layer-select'); const select = document.getElementById('layer-select');

View File

@@ -1,33 +1,31 @@
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {platformModifierKeyOnly} from '../src/ol/events/condition.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import {DragBox, Select} from '../src/ol/interaction.js'; import {DragBox, Select} from '../src/ol/interaction.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {platformModifierKeyOnly} from '../src/ol/events/condition.js';
const vectorSource = new VectorSource({ const vectorSource = new VectorSource({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new GeoJSON(),
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
new VectorLayer({ new VectorLayer({
source: vectorSource source: vectorSource,
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2, zoom: 2,
constrainRotation: 16 constrainRotation: 16,
}) }),
}); });
// a normal select interaction to handle click // a normal select interaction to handle click
@@ -38,7 +36,7 @@ const selectedFeatures = select.getFeatures();
// a DragBox interaction used to select features by drawing boxes // a DragBox interaction used to select features by drawing boxes
const dragBox = new DragBox({ const dragBox = new DragBox({
condition: platformModifierKeyOnly condition: platformModifierKeyOnly,
}); });
map.addInteraction(dragBox); map.addInteraction(dragBox);
@@ -76,7 +74,6 @@ dragBox.on('boxend', function() {
} }
}); });
} }
}); });
// clear selection when drawing a new box and when clicking on the map // clear selection when drawing a new box and when clicking on the map

View File

@@ -1,26 +1,25 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-8730000, 5930000], center: [-8730000, 5930000],
rotation: Math.PI / 5, rotation: Math.PI / 5,
zoom: 8 zoom: 8,
}) }),
}); });
$('.ol-zoom-in, .ol-zoom-out').tooltip({ $('.ol-zoom-in, .ol-zoom-out').tooltip({
placement: 'right' placement: 'right',
}); });
$('.ol-rotate-reset, .ol-attribution button[title]').tooltip({ $('.ol-rotate-reset, .ol-attribution button[title]').tooltip({
placement: 'left' placement: 'left',
}); });

View File

@@ -1,11 +1,11 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import GeoJSON from '../src/ol/format/GeoJSON.js'; import GeoJSON from '../src/ol/format/GeoJSON.js';
import {DEVICE_PIXEL_RATIO} from '../src/ol/has.js'; import Map from '../src/ol/Map.js';
import VectorLayer from '../src/ol/layer/Vector.js'; import VectorLayer from '../src/ol/layer/Vector.js';
import {fromLonLat} from '../src/ol/proj.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
import {DEVICE_PIXEL_RATIO} from '../src/ol/has.js';
import {Fill, Stroke, Style} from '../src/ol/style.js'; import {Fill, Stroke, Style} from '../src/ol/style.js';
import {fromLonLat} from '../src/ol/proj.js';
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const context = canvas.getContext('2d'); const context = canvas.getContext('2d');
@@ -45,7 +45,7 @@ const pattern = (function() {
context.arc(4 * pixelRatio, 4 * pixelRatio, 1.5 * pixelRatio, 0, 2 * Math.PI); context.arc(4 * pixelRatio, 4 * pixelRatio, 1.5 * pixelRatio, 0, 2 * Math.PI);
context.fill(); context.fill();
return context.createPattern(canvas, 'repeat'); return context.createPattern(canvas, 'repeat');
}()); })();
// Generate style for gradient or pattern fill // Generate style for gradient or pattern fill
const fill = new Fill(); const fill = new Fill();
@@ -53,8 +53,8 @@ const style = new Style({
fill: fill, fill: fill,
stroke: new Stroke({ stroke: new Stroke({
color: '#333', color: '#333',
width: 2 width: 2,
}) }),
}); });
/** /**
@@ -74,19 +74,17 @@ const getStackedStyle = function(feature) {
const 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(),
}), }),
style: getStackedStyle style: getStackedStyle,
}); });
// … finally create a map with that layer. // … finally create a map with that layer.
const map = new Map({ const map = new Map({
layers: [ layers: [vectorLayer],
vectorLayer
],
target: 'map', target: 'map',
view: new View({ view: new View({
center: fromLonLat([16, 48]), center: fromLonLat([16, 48]),
zoom: 3 zoom: 3,
}) }),
}); });

View File

@@ -1,21 +1,20 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {OSM, TileDebug} from '../src/ol/source.js'; import {OSM, TileDebug} from '../src/ol/source.js';
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
new TileLayer({ new TileLayer({
source: new TileDebug() source: new TileDebug(),
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1,
}) }),
}); });

View File

@@ -1,38 +1,40 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {CartoDB, OSM} from '../src/ol/source.js'; import {CartoDB, OSM} from '../src/ol/source.js';
const mapConfig = { const mapConfig = {
'layers': [{ 'layers': [
{
'type': 'cartodb', 'type': 'cartodb',
'options': { 'options': {
'cartocss_version': '2.1.1', 'cartocss_version': '2.1.1',
'cartocss': '#layer { polygon-fill: #F00; }', 'cartocss': '#layer { polygon-fill: #F00; }',
'sql': 'select * from european_countries_e where area > 0' 'sql': 'select * from european_countries_e where area > 0',
} },
}] },
],
}; };
const cartoDBSource = new CartoDB({ const cartoDBSource = new CartoDB({
account: 'documentation', account: 'documentation',
config: mapConfig config: mapConfig,
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
new TileLayer({ new TileLayer({
source: cartoDBSource source: cartoDBSource,
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
function setArea(n) { function setArea(n) {
@@ -41,7 +43,6 @@ function setArea(n) {
cartoDBSource.setConfig(mapConfig); cartoDBSource.setConfig(mapConfig);
} }
document.getElementById('country-area').addEventListener('change', function () { document.getElementById('country-area').addEventListener('change', function () {
setArea(this.value); setArea(this.value);
}); });

View File

@@ -1,72 +1,83 @@
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js'; import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
/** @type {VectorSource<import("../src/ol/geom/SimpleGeometry.js").default>} */ /** @type {VectorSource<import("../src/ol/geom/SimpleGeometry.js").default>} */
const source = new VectorSource({ const source = new VectorSource({
url: 'data/geojson/switzerland.geojson', url: 'data/geojson/switzerland.geojson',
format: new GeoJSON() format: new GeoJSON(),
}); });
const 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)',
}), }),
stroke: new Stroke({ stroke: new Stroke({
color: '#319FD3', color: '#319FD3',
width: 1 width: 1,
}), }),
image: new CircleStyle({ image: new CircleStyle({
radius: 5, radius: 5,
fill: new Fill({ fill: new Fill({
color: 'rgba(255, 255, 255, 0.6)' color: 'rgba(255, 255, 255, 0.6)',
}), }),
stroke: new Stroke({ stroke: new Stroke({
color: '#319FD3', color: '#319FD3',
width: 1 width: 1,
}) }),
}) }),
}); });
const vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: source, source: source,
style: style style: style,
}); });
const view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1,
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
vectorLayer vectorLayer,
], ],
target: 'map', target: 'map',
view: view view: view,
}); });
const zoomtoswitzerland = const zoomtoswitzerland = document.getElementById('zoomtoswitzerland');
document.getElementById('zoomtoswitzerland'); zoomtoswitzerland.addEventListener(
zoomtoswitzerland.addEventListener('click', function() { 'click',
function () {
const feature = source.getFeatures()[0]; const feature = source.getFeatures()[0];
const polygon = feature.getGeometry(); const polygon = feature.getGeometry();
view.fit(polygon, {padding: [170, 50, 30, 150]}); view.fit(polygon, {padding: [170, 50, 30, 150]});
}, false); },
false
);
const zoomtolausanne = document.getElementById('zoomtolausanne'); const zoomtolausanne = document.getElementById('zoomtolausanne');
zoomtolausanne.addEventListener('click', function() { zoomtolausanne.addEventListener(
'click',
function () {
const feature = source.getFeatures()[1]; const feature = source.getFeatures()[1];
const point = feature.getGeometry(); const point = feature.getGeometry();
view.fit(point, {padding: [170, 50, 30, 150], minResolution: 50}); view.fit(point, {padding: [170, 50, 30, 150], minResolution: 50});
}, false); },
false
);
const centerlausanne = document.getElementById('centerlausanne'); const centerlausanne = document.getElementById('centerlausanne');
centerlausanne.addEventListener('click', function() { centerlausanne.addEventListener(
'click',
function () {
const feature = source.getFeatures()[1]; const feature = source.getFeatures()[1];
const point = feature.getGeometry(); const point = feature.getGeometry();
const size = map.getSize(); const size = map.getSize();
view.centerOn(point.getCoordinates(), size, [570, 500]); view.centerOn(point.getCoordinates(), size, [570, 500]);
}, false); },
false
);

View File

@@ -1,8 +1,8 @@
import Draw from '../src/ol/interaction/Draw.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import Draw from '../src/ol/interaction/Draw.js'; import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import smooth from 'chaikin-smooth'; import smooth from 'chaikin-smooth';
@@ -21,17 +21,17 @@ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM(), source: new OSM(),
opacity: 0.5 opacity: 0.5,
}), }),
new VectorLayer({ new VectorLayer({
source: vectorSource source: vectorSource,
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [1078373.5950, 6871994.5910], center: [1078373.595, 6871994.591],
zoom: 5 zoom: 5,
}) }),
}); });
const shallSmoothen = document.getElementById('shall-smoothen'); const shallSmoothen = document.getElementById('shall-smoothen');
@@ -39,7 +39,7 @@ const numIterations = document.getElementById('iterations');
const draw = new Draw({ const draw = new Draw({
source: vectorSource, source: vectorSource,
type: 'LineString' type: 'LineString',
}); });
map.addInteraction(draw); map.addInteraction(draw);
draw.on('drawend', function (event) { draw.on('drawend', function (event) {

View File

@@ -1,11 +1,16 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import Point from '../src/ol/geom/Point.js'; import Point from '../src/ol/geom/Point.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import View from '../src/ol/View.js';
import {
Circle as CircleStyle,
Fill,
Stroke,
Style,
Text,
} from '../src/ol/style.js';
import {Cluster, OSM, Vector as VectorSource} from '../src/ol/source.js'; import {Cluster, OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Circle as CircleStyle, Fill, Stroke, Style, Text} from '../src/ol/style.js'; import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const distance = document.getElementById('distance'); const distance = document.getElementById('distance');
@@ -18,12 +23,12 @@ for (let i = 0; i < count; ++i) {
} }
const source = new VectorSource({ const source = new VectorSource({
features: features features: features,
}); });
const clusterSource = new Cluster({ const clusterSource = new Cluster({
distance: parseInt(distance.value, 10), distance: parseInt(distance.value, 10),
source: source source: source,
}); });
const styleCache = {}; const styleCache = {};
@@ -37,27 +42,27 @@ const clusters = new VectorLayer({
image: new CircleStyle({ image: new CircleStyle({
radius: 10, radius: 10,
stroke: new Stroke({ stroke: new Stroke({
color: '#fff' color: '#fff',
}), }),
fill: new Fill({ fill: new Fill({
color: '#3399CC' color: '#3399CC',
}) }),
}), }),
text: new Text({ text: new Text({
text: size.toString(), text: size.toString(),
fill: new Fill({ fill: new Fill({
color: '#fff' color: '#fff',
}) }),
}) }),
}); });
styleCache[size] = style; styleCache[size] = style;
} }
return style; return style;
} },
}); });
const raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const map = new Map({ const map = new Map({
@@ -65,8 +70,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
distance.addEventListener('input', function () { distance.addEventListener('input', function () {

View File

@@ -1,23 +1,21 @@
import ImageLayer from '../src/ol/layer/Image.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import ImageLayer from '../src/ol/layer/Image.js';
import {Raster as RasterSource, Stamen} from '../src/ol/source.js'; import {Raster as RasterSource, Stamen} from '../src/ol/source.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.
*/ */
const Xn = 0.950470; const Xn = 0.95047;
const Yn = 1; const Yn = 1;
const Zn = 1.088830; const Zn = 1.08883;
const t0 = 4 / 29; const t0 = 4 / 29;
const t1 = 6 / 29; const t1 = 6 / 29;
const t2 = 3 * t1 * t1; const t2 = 3 * t1 * t1;
const t3 = t1 * t1 * t1; const t3 = t1 * t1 * t1;
const twoPi = 2 * Math.PI; const twoPi = 2 * Math.PI;
/** /**
* Convert an RGB pixel into an HCL pixel. * Convert an RGB pixel into an HCL pixel.
* @param {Array<number>} pixel A pixel in RGB space. * @param {Array<number>} pixel A pixel in RGB space.
@@ -29,11 +27,14 @@ function rgb2hcl(pixel) {
const blue = rgb2xyz(pixel[2]); const blue = rgb2xyz(pixel[2]);
const 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
);
const y = xyz2lab( const y = xyz2lab(
(0.2126729 * red + 0.7151522 * green + 0.0721750 * blue) / Yn); (0.2126729 * red + 0.7151522 * green + 0.072175 * blue) / Yn
);
const z = xyz2lab( const z = xyz2lab(
(0.0193339 * red + 0.1191920 * green + 0.9503041 * blue) / Zn); (0.0193339 * red + 0.119192 * green + 0.9503041 * blue) / Zn
);
const l = 116 * y - 16; const l = 116 * y - 16;
const a = 500 * (x - y); const a = 500 * (x - y);
@@ -52,7 +53,6 @@ function rgb2hcl(pixel) {
return pixel; return pixel;
} }
/** /**
* Convert an HCL pixel into an RGB pixel. * Convert an HCL pixel into an RGB pixel.
* @param {Array<number>} pixel A pixel in HCL space. * @param {Array<number>} pixel A pixel in HCL space.
@@ -75,7 +75,7 @@ function hcl2rgb(pixel) {
z = Zn * lab2xyz(z); z = Zn * lab2xyz(z);
pixel[0] = xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z); pixel[0] = xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z);
pixel[1] = xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z); pixel[1] = xyz2rgb(-0.969266 * x + 1.8760108 * y + 0.041556 * z);
pixel[2] = xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z); pixel[2] = xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z);
return pixel; return pixel;
@@ -94,18 +94,21 @@ function rgb2xyz(x) {
} }
function xyz2rgb(x) { function xyz2rgb(x) {
return 255 * (x <= 0.0031308 ? return (
12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055)
);
} }
const raster = new RasterSource({ const raster = new RasterSource({
sources: [new Stamen({ sources: [
layer: 'watercolor' new Stamen({
})], layer: 'watercolor',
}),
],
operation: function (pixels, data) { operation: function (pixels, data) {
const hcl = rgb2hcl(pixels[0]); const hcl = rgb2hcl(pixels[0]);
let 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) {
@@ -113,8 +116,8 @@ const raster = new RasterSource({
} }
hcl[0] = h; hcl[0] = h;
hcl[1] *= (data.chroma / 100); hcl[1] *= data.chroma / 100;
hcl[2] *= (data.lightness / 100); hcl[2] *= data.lightness / 100;
return hcl2rgb(hcl); return hcl2rgb(hcl);
}, },
@@ -132,8 +135,8 @@ const raster = new RasterSource({
t1: t1, t1: t1,
t2: t2, t2: t2,
t3: t3, t3: t3,
twoPi: twoPi twoPi: twoPi,
} },
}); });
const controls = {}; const controls = {};
@@ -148,15 +151,15 @@ raster.on('beforeoperations', function(event) {
const map = new Map({ const map = new Map({
layers: [ layers: [
new ImageLayer({ new ImageLayer({
source: raster source: raster,
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 2500000], center: [0, 2500000],
zoom: 2, zoom: 2,
maxZoom: 18 maxZoom: 18,
}) }),
}); });
const controlIds = ['hue', 'chroma', 'lightness']; const controlIds = ['hue', 'chroma', 'lightness'];

View File

@@ -1,16 +1,14 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {defaults as defaultControls, Control} from '../src/ol/control.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {Control, defaults as defaultControls} from '../src/ol/control.js';
// //
// Define rotate to north control. // Define rotate to north control.
// //
class RotateNorthControl extends Control { class RotateNorthControl extends Control {
/** /**
* @param {Object=} opt_options Control options. * @param {Object=} opt_options Control options.
*/ */
@@ -26,7 +24,7 @@ class RotateNorthControl extends Control {
super({ super({
element: element, element: element,
target: options.target target: options.target,
}); });
button.addEventListener('click', this.handleRotateNorth.bind(this), false); button.addEventListener('click', this.handleRotateNorth.bind(this), false);
@@ -35,28 +33,23 @@ class RotateNorthControl extends Control {
handleRotateNorth() { handleRotateNorth() {
this.getMap().getView().setRotation(0); this.getMap().getView().setRotation(0);
} }
} }
// //
// Create map, giving it a rotate to north control. // Create map, giving it a rotate to north control.
// //
const map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([new RotateNorthControl()]),
new RotateNorthControl()
]),
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 3, zoom: 3,
rotation: 1 rotation: 1,
}) }),
}); });

View File

@@ -1,12 +1,14 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {LineString, Point, Polygon} from '../src/ol/geom.js';
import {defaults as defaultInteractions, Pointer as PointerInteraction} from '../src/ol/interaction.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {TileJSON, Vector as VectorSource} from '../src/ol/source.js';
import {Fill, Icon, Stroke, Style} from '../src/ol/style.js'; import {Fill, Icon, Stroke, Style} from '../src/ol/style.js';
import {LineString, Point, Polygon} from '../src/ol/geom.js';
import {
Pointer as PointerInteraction,
defaults as defaultInteractions,
} from '../src/ol/interaction.js';
import {TileJSON, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
class Drag extends PointerInteraction { class Drag extends PointerInteraction {
constructor() { constructor() {
@@ -14,7 +16,7 @@ class Drag extends PointerInteraction {
handleDownEvent: handleDownEvent, handleDownEvent: handleDownEvent,
handleDragEvent: handleDragEvent, handleDragEvent: handleDragEvent,
handleMoveEvent: handleMoveEvent, handleMoveEvent: handleMoveEvent,
handleUpEvent: handleUpEvent handleUpEvent: handleUpEvent,
}); });
/** /**
@@ -43,7 +45,6 @@ class Drag extends PointerInteraction {
} }
} }
/** /**
* @param {import("../src/ol/MapBrowserEvent.js").default} evt Map browser event. * @param {import("../src/ol/MapBrowserEvent.js").default} evt Map browser event.
* @return {boolean} `true` to start the drag sequence. * @return {boolean} `true` to start the drag sequence.
@@ -51,8 +52,7 @@ class Drag extends PointerInteraction {
function handleDownEvent(evt) { function handleDownEvent(evt) {
const map = evt.map; const map = evt.map;
const feature = map.forEachFeatureAtPixel(evt.pixel, const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
function(feature) {
return feature; return feature;
}); });
@@ -64,7 +64,6 @@ function handleDownEvent(evt) {
return !!feature; return !!feature;
} }
/** /**
* @param {import("../src/ol/MapBrowserEvent.js").default} evt Map browser event. * @param {import("../src/ol/MapBrowserEvent.js").default} evt Map browser event.
*/ */
@@ -79,15 +78,13 @@ function handleDragEvent(evt) {
this.coordinate_[1] = evt.coordinate[1]; this.coordinate_[1] = evt.coordinate[1];
} }
/** /**
* @param {import("../src/ol/MapBrowserEvent.js").default} evt Event. * @param {import("../src/ol/MapBrowserEvent.js").default} evt Event.
*/ */
function handleMoveEvent(evt) { function handleMoveEvent(evt) {
if (this.cursor_) { if (this.cursor_) {
const map = evt.map; const map = evt.map;
const feature = map.forEachFeatureAtPixel(evt.pixel, const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
function(feature) {
return feature; return feature;
}); });
const element = evt.map.getTargetElement(); const element = evt.map.getTargetElement();
@@ -103,7 +100,6 @@ function handleMoveEvent(evt) {
} }
} }
/** /**
* @return {boolean} `false` to stop the drag sequence. * @return {boolean} `false` to stop the drag sequence.
*/ */
@@ -113,29 +109,43 @@ function handleUpEvent() {
return false; return false;
} }
const pointFeature = new Feature(new Point([0, 0])); const pointFeature = new Feature(new Point([0, 0]));
const lineFeature = new Feature( const lineFeature = new Feature(
new LineString([[-1e7, 1e6], [-1e6, 3e6]])); new LineString([
[-1e7, 1e6],
[-1e6, 3e6],
])
);
const polygonFeature = new Feature( const polygonFeature = new Feature(
new Polygon([[[-3e6, -1e6], [-3e6, 1e6], new Polygon([
[-1e6, 1e6], [-1e6, -1e6], [-3e6, -1e6]]])); [
[-3e6, -1e6],
[-3e6, 1e6],
[-1e6, 1e6],
[-1e6, -1e6],
[-3e6, -1e6],
],
])
);
const key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q'; const key =
'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q';
const map = new Map({ const map = new Map({
interactions: defaultInteractions().extend([new Drag()]), interactions: defaultInteractions().extend([new Drag()]),
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new TileJSON({ source: new TileJSON({
url: 'https://a.tiles.mapbox.com/v4/aj.1x1-degrees.json?access_token=' + key url:
}) 'https://a.tiles.mapbox.com/v4/aj.1x1-degrees.json?access_token=' +
key,
}),
}), }),
new VectorLayer({ new VectorLayer({
source: new VectorSource({ source: new VectorSource({
features: [pointFeature, lineFeature, polygonFeature] features: [pointFeature, lineFeature, polygonFeature],
}), }),
style: new Style({ style: new Style({
image: new Icon({ image: new Icon({
@@ -143,21 +153,21 @@ const map = new Map({
anchorXUnits: 'fraction', anchorXUnits: 'fraction',
anchorYUnits: 'pixels', anchorYUnits: 'pixels',
opacity: 0.95, opacity: 0.95,
src: 'data/icon.png' src: 'data/icon.png',
}), }),
stroke: new Stroke({ stroke: new Stroke({
width: 3, width: 3,
color: [255, 0, 0, 1] color: [255, 0, 0, 1],
}), }),
fill: new Fill({ fill: new Fill({
color: [0, 0, 255, 0.6] color: [0, 0, 255, 0.6],
}) }),
}) }),
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });

39
examples/d3.js vendored
View File

@@ -1,24 +1,23 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {getWidth, getCenter} from '../src/ol/extent.js';
import {Layer, Tile as TileLayer} from '../src/ol/layer.js';
import SourceState from '../src/ol/source/State.js'; import SourceState from '../src/ol/source/State.js';
import {fromLonLat, toLonLat} from '../src/ol/proj.js';
import Stamen from '../src/ol/source/Stamen.js'; import Stamen from '../src/ol/source/Stamen.js';
import View from '../src/ol/View.js';
import {Layer, Tile as TileLayer} from '../src/ol/layer.js';
import {fromLonLat, toLonLat} from '../src/ol/proj.js';
import {getCenter, getWidth} from '../src/ol/extent.js';
class CanvasLayer extends Layer { class CanvasLayer extends Layer {
constructor(options) { constructor(options) {
super(options); super(options);
this.features = options.features; this.features = options.features;
this.svg = d3.select(document.createElement('div')).append('svg') this.svg = d3
.select(document.createElement('div'))
.append('svg')
.style('position', 'absolute'); .style('position', 'absolute');
this.svg.append('path') this.svg.append('path').datum(this.features).attr('class', 'boundary');
.datum(this.features)
.attr('class', 'boundary');
} }
getSourceState() { getSourceState() {
@@ -51,7 +50,10 @@ class CanvasLayer extends Layer {
const scale = r / frameState.viewState.resolution; const scale = r / frameState.viewState.resolution;
const center = toLonLat(getCenter(frameState.extent), projection); const center = toLonLat(getCenter(frameState.extent), projection);
d3Projection.scale(scale).center(center).translate([width / 2, height / 2]); d3Projection
.scale(scale)
.center(center)
.translate([width / 2, height / 2]);
d3Path = d3Path.projection(d3Projection); d3Path = d3Path.projection(d3Projection);
d3Path(this.features); d3Path(this.features);
@@ -59,8 +61,7 @@ class CanvasLayer extends Layer {
this.svg.attr('width', width); this.svg.attr('width', width);
this.svg.attr('height', height); this.svg.attr('height', height);
this.svg.select('path') this.svg.select('path').attr('d', d3Path);
.attr('d', d3Path);
return this.svg.node(); return this.svg.node();
} }
@@ -70,25 +71,23 @@ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'watercolor' layer: 'watercolor',
}) }),
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: fromLonLat([-97, 38]), center: fromLonLat([-97, 38]),
zoom: 4 zoom: 4,
}) }),
}); });
/** /**
* 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').then(function (us) { d3.json('data/topojson/us.json').then(function (us) {
const layer = new CanvasLayer({ const layer = new CanvasLayer({
features: topojson.feature(us, us.objects.counties) features: topojson.feature(us, us.objects.counties),
}); });
map.addLayer(layer); map.addLayer(layer);

View File

@@ -1,28 +1,27 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js';
import {toRadians} from '../src/ol/math.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {toRadians} from '../src/ol/math.js';
const view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
target: 'map', target: 'map',
view: view view: view,
}); });
function el(id) { function el(id) {
return document.getElementById(id); return document.getElementById(id);
} }
const gn = new GyroNorm(); const gn = new GyroNorm();
gn.init().then(function () { gn.init().then(function () {

View File

@@ -1,10 +1,11 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js'; import XYZ from '../src/ol/source/XYZ.js';
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const disabledLayer = new TileLayer({ const disabledLayer = new TileLayer({
@@ -12,11 +13,12 @@ const disabledLayer = new TileLayer({
className: 'ol-layer-dem', className: 'ol-layer-dem',
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/terrain-rgb/{z}/{x}/{y}.png?key=' + key, url:
'https://api.maptiler.com/tiles/terrain-rgb/{z}/{x}/{y}.png?key=' + key,
maxZoom: 10, maxZoom: 10,
crossOrigin: '', crossOrigin: '',
imageSmoothing: false imageSmoothing: false,
}) }),
}); });
const imagery = new TileLayer({ const imagery = new TileLayer({
@@ -25,24 +27,30 @@ const imagery = new TileLayer({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
maxZoom: 20, maxZoom: 20,
crossOrigin: '' crossOrigin: '',
}) }),
}); });
const enabledLayer = new TileLayer({ const enabledLayer = new TileLayer({
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/terrain-rgb/{z}/{x}/{y}.png?key=' + key, url:
'https://api.maptiler.com/tiles/terrain-rgb/{z}/{x}/{y}.png?key=' + key,
maxZoom: 10, maxZoom: 10,
crossOrigin: '' crossOrigin: '',
}) }),
}); });
imagery.on('prerender', function (evt) { imagery.on('prerender', function (evt) {
// use opaque background to conceal DEM while fully opaque imagery renders // use opaque background to conceal DEM while fully opaque imagery renders
if (imagery.getOpacity() === 1) { if (imagery.getOpacity() === 1) {
evt.context.fillStyle = 'white'; evt.context.fillStyle = 'white';
evt.context.fillRect(0, 0, evt.context.canvas.width, evt.context.canvas.height); evt.context.fillRect(
0,
0,
evt.context.canvas.width,
evt.context.canvas.height
);
} }
}); });
@@ -58,19 +66,19 @@ imagery.setOpacity(control.value / 100);
const view = new View({ const view = new View({
center: [6.893, 45.8295], center: [6.893, 45.8295],
zoom: 16, zoom: 16,
projection: 'EPSG:4326' projection: 'EPSG:4326',
}); });
const map1 = new Map({ const map1 = new Map({
target: 'map1', target: 'map1',
layers: [disabledLayer, imagery], layers: [disabledLayer, imagery],
view: view view: view,
}); });
const map2 = new Map({ const map2 = new Map({
target: 'map2', target: 'map2',
layers: [enabledLayer], layers: [enabledLayer],
view: view view: view,
}); });
const info1 = document.getElementById('info1'); const info1 = document.getElementById('info1');
@@ -83,25 +91,27 @@ const showElevations = function(evt) {
map1.forEachLayerAtPixel( map1.forEachLayerAtPixel(
evt.pixel, evt.pixel,
function (layer, pixel) { function (layer, pixel) {
const height = -10000 + (pixel[0] * 256 * 256 + pixel[1] * 256 + pixel[2]) * 0.1; const height =
-10000 + (pixel[0] * 256 * 256 + pixel[1] * 256 + pixel[2]) * 0.1;
info1.innerText = height.toFixed(1); info1.innerText = height.toFixed(1);
}, },
{ {
layerFilter: function (layer) { layerFilter: function (layer) {
return layer === disabledLayer; return layer === disabledLayer;
} },
} }
); );
map2.forEachLayerAtPixel( map2.forEachLayerAtPixel(
evt.pixel, evt.pixel,
function (layer, pixel) { function (layer, pixel) {
const height = -10000 + (pixel[0] * 256 * 256 + pixel[1] * 256 + pixel[2]) * 0.1; const height =
-10000 + (pixel[0] * 256 * 256 + pixel[1] * 256 + pixel[2]) * 0.1;
info2.innerText = height.toFixed(1); info2.innerText = height.toFixed(1);
}, },
{ {
layerFilter: function (layer) { layerFilter: function (layer) {
return layer === enabledLayer; return layer === enabledLayer;
} },
} }
); );
}; };

View File

@@ -1,22 +1,23 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {
DragAndDrop,
defaults as defaultInteractions,
} from '../src/ol/interaction.js';
import {GPX, GeoJSON, IGC, KML, TopoJSON} from '../src/ol/format.js'; import {GPX, GeoJSON, IGC, KML, TopoJSON} from '../src/ol/format.js';
import {defaults as defaultInteractions, DragAndDrop} from '../src/ol/interaction.js'; import {
import {VectorImage as VectorImageLayer, Tile as TileLayer} from '../src/ol/layer.js'; Tile as TileLayer,
import {XYZ, Vector as VectorSource} from '../src/ol/source.js'; VectorImage as VectorImageLayer,
} from '../src/ol/layer.js';
import {Vector as VectorSource, XYZ} from '../src/ol/source.js';
const dragAndDropInteraction = new DragAndDrop({ const dragAndDropInteraction = new DragAndDrop({
formatConstructors: [ formatConstructors: [GPX, GeoJSON, IGC, KML, TopoJSON],
GPX,
GeoJSON,
IGC,
KML,
TopoJSON
]
}); });
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const map = new Map({ const map = new Map({
@@ -25,25 +26,28 @@ const map = new Map({
new TileLayer({ new TileLayer({
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url:
maxZoom: 20 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
}) maxZoom: 20,
}) }),
}),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
dragAndDropInteraction.on('addfeatures', function (event) { dragAndDropInteraction.on('addfeatures', function (event) {
const vectorSource = new VectorSource({ const vectorSource = new VectorSource({
features: event.features features: event.features,
}); });
map.addLayer(new VectorImageLayer({ map.addLayer(
source: vectorSource new VectorImageLayer({
})); source: vectorSource,
})
);
map.getView().fit(vectorSource.getExtent()); map.getView().fit(vectorSource.getExtent());
}); });

View File

@@ -1,22 +1,20 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {
DragAndDrop,
defaults as defaultInteractions,
} from '../src/ol/interaction.js';
import {GPX, GeoJSON, IGC, KML, TopoJSON} from '../src/ol/format.js'; import {GPX, GeoJSON, IGC, KML, TopoJSON} from '../src/ol/format.js';
import {defaults as defaultInteractions, DragAndDrop} from '../src/ol/interaction.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {XYZ, Vector as VectorSource} from '../src/ol/source.js'; import {Vector as VectorSource, XYZ} from '../src/ol/source.js';
const dragAndDropInteraction = new DragAndDrop({ const dragAndDropInteraction = new DragAndDrop({
formatConstructors: [ formatConstructors: [GPX, GeoJSON, IGC, KML, TopoJSON],
GPX,
GeoJSON,
IGC,
KML,
TopoJSON
]
}); });
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const map = new Map({ const map = new Map({
@@ -25,25 +23,28 @@ const map = new Map({
new TileLayer({ new TileLayer({
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url:
maxZoom: 20 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
}) maxZoom: 20,
}) }),
}),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
dragAndDropInteraction.on('addfeatures', function (event) { dragAndDropInteraction.on('addfeatures', function (event) {
const vectorSource = new VectorSource({ const vectorSource = new VectorSource({
features: event.features features: event.features,
}); });
map.addLayer(new VectorLayer({ map.addLayer(
source: vectorSource new VectorLayer({
})); source: vectorSource,
})
);
map.getView().fit(vectorSource.getExtent()); map.getView().fit(vectorSource.getExtent());
}); });

View File

@@ -1,22 +1,22 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {defaults as defaultInteractions, DragRotateAndZoom} from '../src/ol/interaction.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {
DragRotateAndZoom,
defaults as defaultInteractions,
} from '../src/ol/interaction.js';
const map = new Map({ const map = new Map({
interactions: defaultInteractions().extend([ interactions: defaultInteractions().extend([new DragRotateAndZoom()]),
new DragRotateAndZoom()
]),
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });

View File

@@ -1,12 +1,12 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {Draw, Modify, Snap} from '../src/ol/interaction.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js'; import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js';
import {Draw, Modify, Snap} from '../src/ol/interaction.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const source = new VectorSource(); const source = new VectorSource();
@@ -14,19 +14,19 @@ const vector = new VectorLayer({
source: source, source: source,
style: new Style({ style: new Style({
fill: new Fill({ fill: new Fill({
color: 'rgba(255, 255, 255, 0.2)' color: 'rgba(255, 255, 255, 0.2)',
}), }),
stroke: new Stroke({ stroke: new Stroke({
color: '#ffcc33', color: '#ffcc33',
width: 2 width: 2,
}), }),
image: new CircleStyle({ image: new CircleStyle({
radius: 7, radius: 7,
fill: new Fill({ fill: new Fill({
color: '#ffcc33' color: '#ffcc33',
}) }),
}) }),
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -34,8 +34,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-11000000, 4600000], center: [-11000000, 4600000],
zoom: 4 zoom: 4,
}) }),
}); });
const modify = new Modify({source: source}); const modify = new Modify({source: source});
@@ -47,12 +47,11 @@ const typeSelect = document.getElementById('type');
function addInteractions() { function addInteractions() {
draw = new Draw({ draw = new Draw({
source: source, source: source,
type: typeSelect.value type: typeSelect.value,
}); });
map.addInteraction(draw); map.addInteraction(draw);
snap = new Snap({source: source}); snap = new Snap({source: source});
map.addInteraction(snap); map.addInteraction(snap);
} }
/** /**

View File

@@ -1,17 +1,17 @@
import Draw from '../src/ol/interaction/Draw.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import Draw from '../src/ol/interaction/Draw.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const source = new VectorSource({wrapX: false}); const source = new VectorSource({wrapX: false});
const vector = new VectorLayer({ const vector = new VectorLayer({
source: source source: source,
}); });
const map = new Map({ const map = new Map({
@@ -19,8 +19,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-11000000, 4600000], center: [-11000000, 4600000],
zoom: 4 zoom: 4,
}) }),
}); });
const typeSelect = document.getElementById('type'); const typeSelect = document.getElementById('type');
@@ -31,13 +31,12 @@ function addInteraction() {
if (value !== 'None') { if (value !== 'None') {
draw = new Draw({ draw = new Draw({
source: source, source: source,
type: typeSelect.value type: typeSelect.value,
}); });
map.addInteraction(draw); map.addInteraction(draw);
} }
} }
/** /**
* Handle change event. * Handle change event.
*/ */

View File

@@ -1,17 +1,17 @@
import Draw from '../src/ol/interaction/Draw.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import Draw from '../src/ol/interaction/Draw.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const source = new VectorSource({wrapX: false}); const source = new VectorSource({wrapX: false});
const vector = new VectorLayer({ const vector = new VectorLayer({
source: source source: source,
}); });
const map = new Map({ const map = new Map({
@@ -19,8 +19,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-11000000, 4600000], center: [-11000000, 4600000],
zoom: 4 zoom: 4,
}) }),
}); });
const typeSelect = document.getElementById('type'); const typeSelect = document.getElementById('type');
@@ -32,13 +32,12 @@ function addInteraction() {
draw = new Draw({ draw = new Draw({
source: source, source: source,
type: typeSelect.value, type: typeSelect.value,
freehand: true freehand: true,
}); });
map.addInteraction(draw); map.addInteraction(draw);
} }
} }
/** /**
* Handle change event. * Handle change event.
*/ */

View File

@@ -1,18 +1,21 @@
import Draw, {
createBox,
createRegularPolygon,
} from '../src/ol/interaction/Draw.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import Polygon from '../src/ol/geom/Polygon.js'; import Polygon from '../src/ol/geom/Polygon.js';
import Draw, {createRegularPolygon, createBox} from '../src/ol/interaction/Draw.js'; import View from '../src/ol/View.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const source = new VectorSource({wrapX: false}); const source = new VectorSource({wrapX: false});
const vector = new VectorLayer({ const vector = new VectorLayer({
source: source source: source,
}); });
const map = new Map({ const map = new Map({
@@ -20,8 +23,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-11000000, 4600000], center: [-11000000, 4600000],
zoom: 4 zoom: 4,
}) }),
}); });
const typeSelect = document.getElementById('type'); const typeSelect = document.getElementById('type');
@@ -49,7 +52,7 @@ function addInteraction() {
const newCoordinates = []; const newCoordinates = [];
const numPoints = 12; const numPoints = 12;
for (let i = 0; i < numPoints; ++i) { for (let i = 0; i < numPoints; ++i) {
const angle = rotation + i * 2 * Math.PI / numPoints; const angle = rotation + (i * 2 * Math.PI) / numPoints;
const fraction = i % 2 === 0 ? 1 : 0.5; const fraction = i % 2 === 0 ? 1 : 0.5;
const offsetX = radius * fraction * Math.cos(angle); const offsetX = radius * fraction * Math.cos(angle);
const offsetY = radius * fraction * Math.sin(angle); const offsetY = radius * fraction * Math.sin(angle);
@@ -67,13 +70,12 @@ function addInteraction() {
draw = new Draw({ draw = new Draw({
source: source, source: source,
type: value, type: value,
geometryFunction: geometryFunction geometryFunction: geometryFunction,
}); });
map.addInteraction(draw); map.addInteraction(draw);
} }
} }
/** /**
* Handle change event. * Handle change event.
*/ */

View File

@@ -1,13 +1,13 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {MultiPoint, Point} from '../src/ol/geom.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js'; import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js';
import {MultiPoint, Point} from '../src/ol/geom.js';
import {getVectorContext} from '../src/ol/render.js'; import {getVectorContext} from '../src/ol/render.js';
const tileLayer = new TileLayer({ const tileLayer = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const map = new Map({ const map = new Map({
@@ -15,30 +15,30 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const imageStyle = new Style({ const imageStyle = new Style({
image: new CircleStyle({ image: new CircleStyle({
radius: 5, radius: 5,
fill: new Fill({color: 'yellow'}), fill: new Fill({color: 'yellow'}),
stroke: new Stroke({color: 'red', width: 1}) stroke: new Stroke({color: 'red', width: 1}),
}) }),
}); });
const headInnerImageStyle = new Style({ const headInnerImageStyle = new Style({
image: new CircleStyle({ image: new CircleStyle({
radius: 2, radius: 2,
fill: new Fill({color: 'blue'}) fill: new Fill({color: 'blue'}),
}) }),
}); });
const headOuterImageStyle = new Style({ const headOuterImageStyle = new Style({
image: new CircleStyle({ image: new CircleStyle({
radius: 5, radius: 5,
fill: new Fill({color: 'black'}) fill: new Fill({color: 'black'}),
}) }),
}); });
const n = 200; const n = 200;
@@ -49,13 +49,13 @@ const p = 2e6;
tileLayer.on('postrender', function (event) { tileLayer.on('postrender', function (event) {
const vectorContext = getVectorContext(event); const vectorContext = getVectorContext(event);
const frameState = event.frameState; const frameState = event.frameState;
const theta = 2 * Math.PI * frameState.time / omegaTheta; const theta = (2 * Math.PI * frameState.time) / omegaTheta;
const coordinates = []; const coordinates = [];
let i; let i;
for (i = 0; i < n; ++i) { for (i = 0; i < n; ++i) {
const t = theta + 2 * Math.PI * i / n; const t = theta + (2 * Math.PI * i) / n;
const 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);
const 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);

View File

@@ -1,29 +1,38 @@
import KML from '../src/ol/format/KML.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {createEmpty, getWidth, getHeight, extend} from '../src/ol/extent.js'; import {
import KML from '../src/ol/format/KML.js'; Circle as CircleStyle,
import {defaults as defaultInteractions, Select} from '../src/ol/interaction.js'; Fill,
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; RegularShape,
Stroke,
Style,
Text,
} from '../src/ol/style.js';
import {Cluster, Stamen, Vector as VectorSource} from '../src/ol/source.js'; import {Cluster, Stamen, Vector as VectorSource} from '../src/ol/source.js';
import {Circle as CircleStyle, Fill, RegularShape, Stroke, Style, Text} from '../src/ol/style.js'; import {
Select,
defaults as defaultInteractions,
} from '../src/ol/interaction.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {createEmpty, extend, getHeight, getWidth} from '../src/ol/extent.js';
const earthquakeFill = new Fill({ const earthquakeFill = new Fill({
color: 'rgba(255, 153, 0, 0.8)' color: 'rgba(255, 153, 0, 0.8)',
}); });
const 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,
}); });
const textFill = new Fill({ const textFill = new Fill({
color: '#fff' color: '#fff',
}); });
const 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,
}); });
const invisibleFill = new Fill({ const invisibleFill = new Fill({
color: 'rgba(255, 255, 255, 0.01)' color: 'rgba(255, 255, 255, 0.01)',
}); });
function createEarthquakeStyle(feature) { function createEarthquakeStyle(feature) {
@@ -42,8 +51,8 @@ function createEarthquakeStyle(feature) {
points: 5, points: 5,
angle: Math.PI, angle: Math.PI,
fill: earthquakeFill, fill: earthquakeFill,
stroke: earthquakeStroke stroke: earthquakeStroke,
}) }),
}); });
} }
@@ -62,8 +71,7 @@ const calculateClusterInfo = function(resolution) {
extend(extent, originalFeatures[j].getGeometry().getExtent()); extend(extent, originalFeatures[j].getGeometry().getExtent());
} }
maxFeatureCount = Math.max(maxFeatureCount, jj); maxFeatureCount = Math.max(maxFeatureCount, jj);
radius = 0.25 * (getWidth(extent) + getHeight(extent)) / radius = (0.25 * (getWidth(extent) + getHeight(extent))) / resolution;
resolution;
feature.set('radius', radius); feature.set('radius', radius);
} }
}; };
@@ -81,14 +89,14 @@ function styleFunction(feature, resolution) {
image: new CircleStyle({ image: new CircleStyle({
radius: feature.get('radius'), radius: feature.get('radius'),
fill: new Fill({ fill: new Fill({
color: [255, 153, 0, Math.min(0.8, 0.4 + (size / maxFeatureCount))] color: [255, 153, 0, Math.min(0.8, 0.4 + size / maxFeatureCount)],
}) }),
}), }),
text: new Text({ text: new Text({
text: size.toString(), text: size.toString(),
fill: textFill, fill: textFill,
stroke: textStroke stroke: textStroke,
}) }),
}); });
} else { } else {
const originalFeature = feature.get('features')[0]; const originalFeature = feature.get('features')[0];
@@ -98,12 +106,14 @@ function styleFunction(feature, resolution) {
} }
function selectStyleFunction(feature) { function selectStyleFunction(feature) {
const 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,
}) }),
})]; }),
];
const originalFeatures = feature.get('features'); const originalFeatures = feature.get('features');
let originalFeature; let originalFeature;
for (let i = originalFeatures.length - 1; i >= 0; --i) { for (let i = originalFeatures.length - 1; i >= 0; --i) {
@@ -119,31 +129,32 @@ 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({
extractStyles: false extractStyles: false,
})
})
}), }),
style: styleFunction }),
}),
style: styleFunction,
}); });
const raster = new TileLayer({ const raster = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner',
}) }),
}); });
const 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) {
return evt.type == 'pointermove' || return evt.type == 'pointermove' || evt.type == 'singleclick';
evt.type == 'singleclick';
}, },
style: selectStyleFunction style: selectStyleFunction,
})]), }),
]),
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });

View File

@@ -1,15 +1,22 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import KML from '../src/ol/format/KML.js'; import KML from '../src/ol/format/KML.js';
import Map from '../src/ol/Map.js';
import Polygon from '../src/ol/geom/Polygon.js'; import Polygon from '../src/ol/geom/Polygon.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {toContext} from '../src/ol/render.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';
import View from '../src/ol/View.js';
import {Fill, Icon, Stroke, Style} from '../src/ol/style.js'; import {Fill, Icon, Stroke, Style} from '../src/ol/style.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {toContext} from '../src/ol/render.js';
const symbol = [
const symbol = [[0, 0], [4, 2], [6, 0], [10, 5], [6, 3], [4, 5], [0, 0]]; [0, 0],
[4, 2],
[6, 0],
[10, 5],
[6, 3],
[4, 5],
[0, 0],
];
let scale; let scale;
const scaleFunction = function (coordinate) { const scaleFunction = function (coordinate) {
return [coordinate[0] * scale, coordinate[1] * scale]; return [coordinate[0] * scale, coordinate[1] * scale];
@@ -27,19 +34,23 @@ const styleFunction = function(feature) {
let style = styleCache[size]; let style = styleCache[size];
if (!style) { if (!style) {
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const vectorContext = toContext(canvas.getContext('2d'), const vectorContext = toContext(canvas.getContext('2d'), {
{size: [size, size], pixelRatio: 1}); size: [size, size],
vectorContext.setStyle(new Style({ pixelRatio: 1,
});
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}),
})); })
);
vectorContext.drawGeometry(new Polygon([symbol.map(scaleFunction)])); vectorContext.drawGeometry(new Polygon([symbol.map(scaleFunction)]));
style = new Style({ style = new Style({
image: new Icon({ image: new Icon({
img: canvas, img: canvas,
imgSize: [size, size], imgSize: [size, size],
rotation: 1.2 rotation: 1.2,
}) }),
}); });
styleCache[size] = style; styleCache[size] = style;
} }
@@ -50,16 +61,16 @@ 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({
extractStyles: false extractStyles: false,
})
}), }),
style: styleFunction }),
style: styleFunction,
}); });
const raster = new TileLayer({ const raster = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner',
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -67,6 +78,6 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });

View File

@@ -1,46 +1,46 @@
import {Map, View} from '../src/ol/index.js';
import GeoJSON from '../src/ol/format/GeoJSON.js'; import GeoJSON from '../src/ol/format/GeoJSON.js';
import {Modify, Select, Draw, Snap} from '../src/ol/interaction.js'; import {Draw, Modify, Select, Snap} from '../src/ol/interaction.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import {Map, View} from '../src/ol/index.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {useGeographic} from '../src/ol/proj.js'; import {useGeographic} from '../src/ol/proj.js';
useGeographic(); useGeographic();
const source = new VectorSource({ const source = new VectorSource({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new GeoJSON(),
}); });
const map = new Map({ const map = new Map({
target: 'map', target: 'map',
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
new VectorLayer({ new VectorLayer({
source: source source: source,
}) }),
], ],
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const select = new Select(); const select = new Select();
const modify = new Modify({ const modify = new Modify({
features: select.getFeatures() features: select.getFeatures(),
}); });
const draw = new Draw({ const draw = new Draw({
type: 'Polygon', type: 'Polygon',
source: source source: source,
}); });
const snap = new Snap({ const snap = new Snap({
source: source source: source,
}); });
function removeInteractions() { function removeInteractions() {

View File

@@ -1,9 +1,8 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {defaults as defaultControls, ScaleLine} from '../src/ol/control.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import TileWMS from '../src/ol/source/TileWMS.js'; import TileWMS from '../src/ol/source/TileWMS.js';
import View from '../src/ol/View.js';
import {ScaleLine, defaults as defaultControls} from '../src/ol/control.js';
const layers = [ const layers = [
new TileLayer({ new TileLayer({
@@ -11,23 +10,23 @@ const layers = [
url: 'https://ahocevar.com/geoserver/wms', url: 'https://ahocevar.com/geoserver/wms',
params: { params: {
'LAYERS': 'ne:NE1_HR_LC_SR_W_DR', 'LAYERS': 'ne:NE1_HR_LC_SR_W_DR',
'TILED': true 'TILED': true,
} },
}) }),
}) }),
]; ];
const map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([
new ScaleLine({ new ScaleLine({
units: 'degrees' units: 'degrees',
}) }),
]), ]),
layers: layers, layers: layers,
target: 'map', target: 'map',
view: new View({ view: new View({
projection: 'EPSG:4326', projection: 'EPSG:4326',
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });

View File

@@ -1,10 +1,9 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
class OLComponent extends HTMLElement { class OLComponent extends HTMLElement {
constructor() { constructor() {
super(); super();
this.shadow = this.attachShadow({mode: 'open'}); this.shadow = this.attachShadow({mode: 'open'});
@@ -28,15 +27,14 @@ class OLComponent extends HTMLElement {
target: div, target: div,
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
} }
} }

View File

@@ -1,27 +1,27 @@
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
new 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(),
}),
opacity: 0.5,
}), }),
opacity: 0.5
})
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
document.getElementById('export-png').addEventListener('click', function () { document.getElementById('export-png').addEventListener('click', function () {
@@ -31,18 +31,27 @@ document.getElementById('export-png').addEventListener('click', function() {
mapCanvas.width = size[0]; mapCanvas.width = size[0];
mapCanvas.height = size[1]; mapCanvas.height = size[1];
const mapContext = mapCanvas.getContext('2d'); const mapContext = mapCanvas.getContext('2d');
Array.prototype.forEach.call(document.querySelectorAll('.ol-layer canvas'), function(canvas) { Array.prototype.forEach.call(
document.querySelectorAll('.ol-layer canvas'),
function (canvas) {
if (canvas.width > 0) { if (canvas.width > 0) {
const opacity = canvas.parentNode.style.opacity; const opacity = canvas.parentNode.style.opacity;
mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity); mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
const transform = canvas.style.transform; const transform = canvas.style.transform;
// Get the transform parameters from the style's transform matrix // Get the transform parameters from the style's transform matrix
const matrix = transform.match(/^matrix\(([^\(]*)\)$/)[1].split(',').map(Number); const matrix = transform
.match(/^matrix\(([^\(]*)\)$/)[1]
.split(',')
.map(Number);
// Apply the transform to the export map context // Apply the transform to the export map context
CanvasRenderingContext2D.prototype.setTransform.apply(mapContext, matrix); CanvasRenderingContext2D.prototype.setTransform.apply(
mapContext,
matrix
);
mapContext.drawImage(canvas, 0, 0); mapContext.drawImage(canvas, 0, 0);
} }
}); }
);
if (navigator.msSaveBlob) { if (navigator.msSaveBlob) {
// link download attribuute does not work on MS browsers // link download attribuute does not work on MS browsers
navigator.msSaveBlob(mapCanvas.msToBlob(), 'map.png'); navigator.msSaveBlob(mapCanvas.msToBlob(), 'map.png');

View File

@@ -1,60 +1,59 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import WKT from '../src/ol/format/WKT.js'; import WKT from '../src/ol/format/WKT.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const format = new WKT(); const format = new WKT();
const 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');
const vector = new VectorLayer({ const vector = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
features: [feature] features: [feature],
}), }),
opacity: 0.5 opacity: 0.5,
}); });
const map = new Map({ const map = new Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const dims = { const dims = {
a0: [1189, 841], a0: [1189, 841],
a1: [841, 594], a1: [841, 594],
a2: [594, 420], a2: [594, 420],
a3: [420, 297], a3: [420, 297],
a4: [297, 210], a4: [297, 210],
a5: [210, 148] a5: [210, 148],
}; };
const 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';
const format = document.getElementById('format').value; const format = document.getElementById('format').value;
const resolution = document.getElementById('resolution').value; const resolution = document.getElementById('resolution').value;
const dim = dims[format]; const dim = dims[format];
const width = Math.round(dim[0] * resolution / 25.4); const width = Math.round((dim[0] * resolution) / 25.4);
const height = Math.round(dim[1] * resolution / 25.4); const height = Math.round((dim[1] * resolution) / 25.4);
const size = map.getSize(); const size = map.getSize();
const viewResolution = map.getView().getResolution(); const viewResolution = map.getView().getResolution();
@@ -63,20 +62,36 @@ exportButton.addEventListener('click', function() {
mapCanvas.width = width; mapCanvas.width = width;
mapCanvas.height = height; mapCanvas.height = height;
const mapContext = mapCanvas.getContext('2d'); const mapContext = mapCanvas.getContext('2d');
Array.prototype.forEach.call(document.querySelectorAll('.ol-layer canvas'), function(canvas) { Array.prototype.forEach.call(
document.querySelectorAll('.ol-layer canvas'),
function (canvas) {
if (canvas.width > 0) { if (canvas.width > 0) {
const opacity = canvas.parentNode.style.opacity; const opacity = canvas.parentNode.style.opacity;
mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity); mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
const transform = canvas.style.transform; const transform = canvas.style.transform;
// Get the transform parameters from the style's transform matrix // Get the transform parameters from the style's transform matrix
const matrix = transform.match(/^matrix\(([^\(]*)\)$/)[1].split(',').map(Number); const matrix = transform
.match(/^matrix\(([^\(]*)\)$/)[1]
.split(',')
.map(Number);
// Apply the transform to the export map context // Apply the transform to the export map context
CanvasRenderingContext2D.prototype.setTransform.apply(mapContext, matrix); CanvasRenderingContext2D.prototype.setTransform.apply(
mapContext,
matrix
);
mapContext.drawImage(canvas, 0, 0); mapContext.drawImage(canvas, 0, 0);
} }
}); }
);
const pdf = new jsPDF('landscape', undefined, format); const pdf = new jsPDF('landscape', undefined, format);
pdf.addImage(mapCanvas.toDataURL('image/jpeg'), 'JPEG', 0, 0, dim[0], dim[1]); pdf.addImage(
mapCanvas.toDataURL('image/jpeg'),
'JPEG',
0,
0,
dim[0],
dim[1]
);
pdf.save('map.pdf'); pdf.save('map.pdf');
// Reset original map size // Reset original map size
map.setSize(size); map.setSize(size);
@@ -90,5 +105,6 @@ exportButton.addEventListener('click', function() {
map.setSize(printSize); map.setSize(printSize);
const scaling = Math.min(width / size[0], height / size[1]); const scaling = Math.min(width / size[0], height / size[1]);
map.getView().setResolution(viewResolution / scaling); map.getView().setResolution(viewResolution / scaling);
},
}, false); false
);

View File

@@ -1,25 +1,24 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.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';
import {defaults as defaultControls} from '../src/ol/control.js'; import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import ZoomSlider from '../src/ol/control/ZoomSlider.js'; import ZoomSlider from '../src/ol/control/ZoomSlider.js';
import {defaults as defaultControls} from '../src/ol/control.js';
const view = new View({ const view = new View({
center: [328627.563458, 5921296.662223], center: [328627.563458, 5921296.662223],
zoom: 8, zoom: 8,
extent: [-572513.341856, 5211017.966314, extent: [-572513.341856, 5211017.966314, 916327.095083, 6636950.728974],
916327.095083, 6636950.728974]
}); });
new Map({ new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
keyboardEventTarget: document, keyboardEventTarget: document,
target: 'map', target: 'map',
view: view, view: view,
controls: defaultControls().extend([new ZoomSlider()]) controls: defaultControls().extend([new ZoomSlider()]),
}); });

View File

@@ -1,29 +1,29 @@
import ExtentInteraction from '../src/ol/interaction/Extent.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import ExtentInteraction from '../src/ol/interaction/Extent.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const vectorSource = new VectorSource({ const vectorSource = new VectorSource({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new GeoJSON(),
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
new VectorLayer({ new VectorLayer({
source: vectorSource source: vectorSource,
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const extent = new ExtentInteraction(); const extent = new ExtentInteraction();

View File

@@ -1,19 +1,19 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import {unByKey} from '../src/ol/Observable.js';
import View from '../src/ol/View.js';
import {easeOut} from '../src/ol/easing.js';
import Point from '../src/ol/geom/Point.js'; import Point from '../src/ol/geom/Point.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import View from '../src/ol/View.js';
import {fromLonLat} from '../src/ol/proj.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Circle as CircleStyle, Stroke, Style} from '../src/ol/style.js'; import {Circle as CircleStyle, Stroke, Style} from '../src/ol/style.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {easeOut} from '../src/ol/easing.js';
import {fromLonLat} from '../src/ol/proj.js';
import {getVectorContext} from '../src/ol/render.js'; import {getVectorContext} from '../src/ol/render.js';
import {unByKey} from '../src/ol/Observable.js';
const tileLayer = new TileLayer({ const tileLayer = new TileLayer({
source: new OSM({ source: new OSM({
wrapX: false wrapX: false,
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -22,15 +22,15 @@ const map = new Map({
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 1, zoom: 1,
multiWorld: true multiWorld: true,
}) }),
}); });
const source = new VectorSource({ const source = new VectorSource({
wrapX: false wrapX: false,
}); });
const vector = new VectorLayer({ const vector = new VectorLayer({
source: source source: source,
}); });
map.addLayer(vector); map.addLayer(vector);
@@ -62,9 +62,9 @@ function flash(feature) {
radius: radius, radius: radius,
stroke: new Stroke({ stroke: new Stroke({
color: 'rgba(255, 0, 0, ' + opacity + ')', color: 'rgba(255, 0, 0, ' + opacity + ')',
width: 0.25 + opacity width: 0.25 + opacity,
}) }),
}) }),
}); });
vectorContext.setStyle(style); vectorContext.setStyle(style);

View File

@@ -1,12 +1,18 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import Polyline from '../src/ol/format/Polyline.js';
import Point from '../src/ol/geom/Point.js'; import Point from '../src/ol/geom/Point.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import Polyline from '../src/ol/format/Polyline.js';
import XYZ from '../src/ol/source/XYZ.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
import {Circle as CircleStyle, Fill, Icon, Stroke, Style} from '../src/ol/style.js'; import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js';
import {
Circle as CircleStyle,
Fill,
Icon,
Stroke,
Style,
} from '../src/ol/style.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {getVectorContext} from '../src/ol/render.js'; import {getVectorContext} from '../src/ol/render.js';
// This long string is placed here due to jsFiddle limitations. // This long string is placed here due to jsFiddle limitations.
@@ -50,14 +56,16 @@ const polyline = [
'ab@`CuOlC}YnAcV`@_^m@aeB}@yk@YuTuBg^uCkZiGk\\yGeY}Lu_@oOsZiTe[uWi[sl@', 'ab@`CuOlC}YnAcV`@_^m@aeB}@yk@YuTuBg^uCkZiGk\\yGeY}Lu_@oOsZiTe[uWi[sl@',
'mo@soAauAsrBgzBqgAglAyd@ig@asAcyAklA}qAwHkGi{@s~@goAmsAyDeEirB_{B}IsJ', 'mo@soAauAsrBgzBqgAglAyd@ig@asAcyAklA}qAwHkGi{@s~@goAmsAyDeEirB_{B}IsJ',
'uEeFymAssAkdAmhAyTcVkFeEoKiH}l@kp@wg@sj@ku@ey@uh@kj@}EsFmG}Jk^_r@_f@m', 'uEeFymAssAkdAmhAyTcVkFeEoKiH}l@kp@wg@sj@ku@ey@uh@kj@}EsFmG}Jk^_r@_f@m',
'~@ym@yjA??a@cFd@kBrCgDbAUnAcBhAyAdk@et@??kF}D??OL' '~@ym@yjA??a@cFd@kBrCgDbAUnAcBhAyAdk@et@??kF}D??OL',
].join(''); ].join('');
const route = /** @type {import("../src/ol/geom/LineString.js").default} */ (new Polyline({ const route = /** @type {import("../src/ol/geom/LineString.js").default} */ (new Polyline(
factor: 1e6 {
}).readGeometry(polyline, { factor: 1e6,
}
).readGeometry(polyline, {
dataProjection: 'EPSG:4326', dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857' featureProjection: 'EPSG:3857',
})); }));
const routeCoords = route.getCoordinates(); const routeCoords = route.getCoordinates();
@@ -65,42 +73,46 @@ const routeLength = routeCoords.length;
const routeFeature = new Feature({ const routeFeature = new Feature({
type: 'route', type: 'route',
geometry: route geometry: route,
}); });
const geoMarker = /** @type Feature<import("../src/ol/geom/Point").default> */(new Feature({ const geoMarker = /** @type Feature<import("../src/ol/geom/Point").default> */ (new Feature(
{
type: 'geoMarker', type: 'geoMarker',
geometry: new Point(routeCoords[0]) geometry: new Point(routeCoords[0]),
})); }
));
const startMarker = new Feature({ const startMarker = new Feature({
type: 'icon', type: 'icon',
geometry: new Point(routeCoords[0]) geometry: new Point(routeCoords[0]),
}); });
const endMarker = new Feature({ const endMarker = new Feature({
type: 'icon', type: 'icon',
geometry: new Point(routeCoords[routeLength - 1]) geometry: new Point(routeCoords[routeLength - 1]),
}); });
const 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],
}),
}), }),
'icon': new Style({ 'icon': new Style({
image: new Icon({ image: new Icon({
anchor: [0.5, 1], anchor: [0.5, 1],
src: 'data/icon.png' src: 'data/icon.png',
}) }),
}), }),
'geoMarker': new Style({ 'geoMarker': new Style({
image: new CircleStyle({ image: new CircleStyle({
radius: 7, radius: 7,
fill: new Fill({color: 'black'}), fill: new Fill({color: 'black'}),
stroke: new Stroke({ stroke: new Stroke({
color: 'white', width: 2 color: 'white',
}) width: 2,
}) }),
}) }),
}),
}; };
let animating = false; let animating = false;
@@ -110,7 +122,7 @@ const startButton = document.getElementById('start-animation');
const vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
features: [routeFeature, geoMarker, startMarker, endMarker] features: [routeFeature, geoMarker, startMarker, endMarker],
}), }),
style: function (feature) { style: function (feature) {
// hide geoMarker if animation is active // hide geoMarker if animation is active
@@ -118,11 +130,12 @@ const vectorLayer = new VectorLayer({
return null; return null;
} }
return styles[feature.get('type')]; return styles[feature.get('type')];
} },
}); });
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const center = [-5639523.95, -3501274.52]; const center = [-5639523.95, -3501274.52];
@@ -132,18 +145,18 @@ const map = new Map({
center: center, center: center,
zoom: 10, zoom: 10,
minZoom: 2, minZoom: 2,
maxZoom: 19 maxZoom: 19,
}), }),
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/maps/hybrid/{z}/{x}/{y}.jpg?key=' + key, url: 'https://api.maptiler.com/maps/hybrid/{z}/{x}/{y}.jpg?key=' + key,
tileSize: 512 tileSize: 512,
})
}), }),
vectorLayer }),
] vectorLayer,
],
}); });
const moveFeature = function (event) { const moveFeature = function (event) {
@@ -154,7 +167,7 @@ const moveFeature = function(event) {
const 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
const index = Math.round(speed * elapsedTime / 1000); const index = Math.round((speed * elapsedTime) / 1000);
if (index >= routeLength) { if (index >= routeLength) {
stopAnimation(true); stopAnimation(true);
@@ -186,7 +199,6 @@ function startAnimation() {
} }
} }
/** /**
* @param {boolean} ended end of animation. * @param {boolean} ended end of animation.
*/ */

View File

@@ -1,61 +1,54 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js';
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js';
import Point from '../src/ol/geom/Point.js'; import Point from '../src/ol/geom/Point.js';
import Stamen from '../src/ol/source/Stamen.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import WebGLPointsLayer from '../src/ol/layer/WebGLPoints.js';
import {Vector} from '../src/ol/source.js'; import {Vector} from '../src/ol/source.js';
import {fromLonLat} from '../src/ol/proj.js'; import {fromLonLat} from '../src/ol/proj.js';
import Stamen from '../src/ol/source/Stamen.js';
import WebGLPointsLayer from '../src/ol/layer/WebGLPoints.js';
const vectorSource = new Vector({ const vectorSource = new Vector({
attributions: 'NASA' attributions: 'NASA',
}); });
const oldColor = 'rgba(242,56,22,0.61)'; const oldColor = 'rgba(242,56,22,0.61)';
const newColor = '#ffe52c'; const newColor = '#ffe52c';
const period = 12; // animation period in seconds const period = 12; // animation period in seconds
const animRatio = const animRatio = [
['^', '^',
['/',
['%',
['+',
['time'],
[ [
'interpolate', '/',
['linear'], [
['get', 'year'], '%',
1850, 0, [
2015, period '+',
] ['time'],
['interpolate', ['linear'], ['get', 'year'], 1850, 0, 2015, period],
], ],
period period,
], ],
period period,
], ],
0.5 0.5,
]; ];
const style = { const style = {
variables: { variables: {
minYear: 1850, minYear: 1850,
maxYear: 2015 maxYear: 2015,
}, },
filter: ['between', ['get', 'year'], ['var', 'minYear'], ['var', 'maxYear']], filter: ['between', ['get', 'year'], ['var', 'minYear'], ['var', 'maxYear']],
symbol: { symbol: {
symbolType: 'circle', symbolType: 'circle',
size: ['*', size: [
'*',
['interpolate', ['linear'], ['get', 'mass'], 0, 8, 200000, 26], ['interpolate', ['linear'], ['get', 'mass'], 0, 8, 200000, 26],
['-', 1.75, ['*', animRatio, 0.75]] ['-', 1.75, ['*', animRatio, 0.75]],
], ],
color: ['interpolate', color: ['interpolate', ['linear'], animRatio, 0, newColor, 1, oldColor],
['linear'], opacity: ['-', 1.0, ['*', animRatio, 0.75]],
animRatio, },
0, newColor,
1, oldColor
],
opacity: ['-', 1.0, ['*', animRatio, 0.75]]
}
}; };
// handle input values & events // handle input values & events
@@ -102,11 +95,13 @@ client.onload = function() {
continue; continue;
} }
features.push(new Feature({ features.push(
new Feature({
mass: parseFloat(line[1]) || 0, mass: parseFloat(line[1]) || 0,
year: parseInt(line[2]) || 0, year: parseInt(line[2]) || 0,
geometry: new Point(coords) geometry: new Point(coords),
})); })
);
} }
vectorSource.addFeatures(features); vectorSource.addFeatures(features);
@@ -117,20 +112,20 @@ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner',
}) }),
}), }),
new WebGLPointsLayer({ new WebGLPointsLayer({
style: style, style: style,
source: vectorSource, source: vectorSource,
disableHitDetection: true disableHitDetection: true,
}) }),
], ],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
// animate the map // animate the map

View File

@@ -1,46 +1,47 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import LineString from '../src/ol/geom/LineString.js'; import LineString from '../src/ol/geom/LineString.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import Map from '../src/ol/Map.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';
import View from '../src/ol/View.js';
import {Stroke, Style} from '../src/ol/style.js'; import {Stroke, Style} from '../src/ol/style.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {getVectorContext} from '../src/ol/render.js'; import {getVectorContext} from '../src/ol/render.js';
const tileLayer = new TileLayer({ const tileLayer = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner',
}) }),
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [tileLayer],
tileLayer
],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const style = new Style({ const style = new Style({
stroke: new Stroke({ stroke: new Stroke({
color: '#EAE911', color: '#EAE911',
width: 2 width: 2,
}) }),
}); });
const flightsSource = new VectorSource({ const 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 () {
const 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) {
const flightsData = json.flights; const flightsData = json.flights;
for (let i = 0; i < flightsData.length; i++) { for (let i = 0; i < flightsData.length; i++) {
const flight = flightsData[i]; const flight = flightsData[i];
@@ -50,7 +51,8 @@ const flightsSource = new VectorSource({
// create an arc circle between the two locations // create an arc circle between the two locations
const 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]}
);
const arcLine = arcGenerator.Arc(100, {offset: 10}); const arcLine = arcGenerator.Arc(100, {offset: 10});
if (arcLine.geometries.length === 1) { if (arcLine.geometries.length === 1) {
@@ -59,7 +61,7 @@ const flightsSource = new VectorSource({
const feature = new Feature({ const feature = new Feature({
geometry: line, geometry: line,
finished: false finished: false,
}); });
// add the feature with a delay so that the animation // add the feature with a delay so that the animation
// for all features does not start at the same time // for all features does not start at the same time
@@ -68,7 +70,7 @@ const flightsSource = new VectorSource({
} }
tileLayer.on('postrender', animateFlights); tileLayer.on('postrender', animateFlights);
}); });
} },
}); });
const flightsLayer = new VectorLayer({ const flightsLayer = new VectorLayer({
@@ -81,7 +83,7 @@ const flightsLayer = new VectorLayer({
} else { } else {
return null; return null;
} }
} },
}); });
map.addLayer(flightsLayer); map.addLayer(flightsLayer);

View File

@@ -1,9 +1,9 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import LineString from '../src/ol/geom/LineString.js'; import LineString from '../src/ol/geom/LineString.js';
import Map from '../src/ol/Map.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';
import View from '../src/ol/View.js';
const radius = 10e6; const radius = 10e6;
const cos30 = Math.cos(Math.PI / 6); const cos30 = Math.cos(Math.PI / 6);
@@ -12,15 +12,18 @@ const rise = radius * sin30;
const run = radius * cos30; const run = radius * cos30;
const triangle = new LineString([ const triangle = new LineString([
[0, radius], [run, -rise], [-run, -rise], [0, radius] [0, radius],
[run, -rise],
[-run, -rise],
[0, radius],
]); ]);
const feature = new Feature(triangle); const feature = new Feature(triangle);
const layer = new VectorLayer({ const layer = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
features: [feature] features: [feature],
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -28,8 +31,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1,
}) }),
}); });
function makeFractal(depth) { function makeFractal(depth) {
@@ -59,19 +62,19 @@ function injectNodes(startNode) {
// first point at 1/3 along the segment // first point at 1/3 along the segment
const 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 _/\_
const r = Math.sqrt(dx * dx + dy * dy) / (2 * cos30); const r = Math.sqrt(dx * dx + dy * dy) / (2 * cos30);
const a = Math.atan2(dy, dx) + Math.PI / 6; const a = Math.atan2(dy, dx) + Math.PI / 6;
const 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
const thirdNode = { const thirdNode = {
point: [end[0] - dx / 3, end[1] - dy / 3] point: [end[0] - dx / 3, end[1] - dy / 3],
}; };
startNode.next = firstNode; startNode.next = firstNode;
@@ -80,15 +83,14 @@ function injectNodes(startNode) {
thirdNode.next = endNode; thirdNode.next = endNode;
} }
function coordsToGraph(coordinates) { function coordsToGraph(coordinates) {
const graph = { const graph = {
point: coordinates[0] point: coordinates[0],
}; };
const length = coordinates.length; const length = coordinates.length;
for (let 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],
}; };
node = node.next; node = node.next;
} }
@@ -111,7 +113,6 @@ function update() {
let updateTimer; let updateTimer;
/** /**
* Regenerate fractal on depth change. Change events are debounced so updates * Regenerate fractal on depth change. Change events are debounced so updates
* only occur every 200ms. * only occur every 200ms.

View File

@@ -1,35 +1,35 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {defaults as defaultControls, FullScreen} from '../src/ol/control.js';
import {defaults as defaultInteractions, DragRotateAndZoom} from '../src/ol/interaction.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js'; import XYZ from '../src/ol/source/XYZ.js';
import {
DragRotateAndZoom,
defaults as defaultInteractions,
} from '../src/ol/interaction.js';
import {FullScreen, defaults as defaultControls} from '../src/ol/control.js';
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([new FullScreen()]),
new FullScreen() interactions: defaultInteractions().extend([new DragRotateAndZoom()]),
]),
interactions: defaultInteractions().extend([
new DragRotateAndZoom()
]),
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url:
maxZoom: 20 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
}) maxZoom: 20,
}) }),
}),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-33519607, 5616436], center: [-33519607, 5616436],
rotation: -Math.PI / 8, rotation: -Math.PI / 8,
zoom: 8 zoom: 8,
}) }),
}); });

View File

@@ -1,26 +1,25 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {defaults as defaultControls, FullScreen} from '../src/ol/control.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {FullScreen, defaults as defaultControls} from '../src/ol/control.js';
const view = new View({ const view = new View({
center: [-9101767, 2822912], center: [-9101767, 2822912],
zoom: 14 zoom: 14,
}); });
const map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([
new FullScreen({ new FullScreen({
source: 'fullscreen' source: 'fullscreen',
}) }),
]), ]),
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
target: 'map', target: 'map',
view: view view: view,
}); });

View File

@@ -1,32 +1,31 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {defaults as defaultControls, FullScreen} from '../src/ol/control.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js'; import XYZ from '../src/ol/source/XYZ.js';
import {FullScreen, defaults as defaultControls} from '../src/ol/control.js';
const view = new View({ const view = new View({
center: [-9101767, 2822912], center: [-9101767, 2822912],
zoom: 14 zoom: 14,
}); });
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const map = new Map({ const map = new Map({
controls: defaultControls().extend([ controls: defaultControls().extend([new FullScreen()]),
new FullScreen()
]),
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url:
maxZoom: 20 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
}) maxZoom: 20,
}) }),
}),
], ],
target: 'map', target: 'map',
view: view view: view,
}); });

View File

@@ -1,9 +1,9 @@
import {useGeographic} from '../src/ol/proj.js'; import {Circle, Fill, Style} from '../src/ol/style.js';
import {Map, View, Feature, Overlay} from '../src/ol/index.js'; import {Feature, Map, Overlay, View} from '../src/ol/index.js';
import {Point} from '../src/ol/geom.js';
import {Vector as VectorLayer, Tile as TileLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Style, Circle, Fill} from '../src/ol/style.js'; import {Point} from '../src/ol/geom.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {useGeographic} from '../src/ol/proj.js';
useGeographic(); useGeographic();
@@ -15,26 +15,24 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: place, center: place,
zoom: 8 zoom: 8,
}), }),
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
new VectorLayer({ new VectorLayer({
source: new VectorSource({ source: new VectorSource({
features: [ features: [new Feature(point)],
new Feature(point)
]
}), }),
style: new Style({ style: new Style({
image: new Circle({ image: new Circle({
radius: 9, radius: 9,
fill: new Fill({color: 'red'}) fill: new Fill({color: 'red'}),
}) }),
}) }),
}) }),
] ],
}); });
const element = document.getElementById('popup'); const element = document.getElementById('popup');
@@ -43,7 +41,7 @@ const popup = new Overlay({
element: element, element: element,
positioning: 'bottom-center', positioning: 'bottom-center',
stopEvent: false, stopEvent: false,
offset: [0, -10] offset: [0, -10],
}); });
map.addOverlay(popup); map.addOverlay(popup);
@@ -72,7 +70,7 @@ map.on('click', function(event) {
$(element).popover({ $(element).popover({
placement: 'top', placement: 'top',
html: true, html: true,
content: formatCoordinate(coordinate) content: formatCoordinate(coordinate),
}); });
$(element).popover('show'); $(element).popover('show');
} else { } else {

View File

@@ -1,10 +1,13 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import GeoJSON from '../src/ol/format/GeoJSON.js'; import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import VectorTileSource from '../src/ol/source/VectorTile.js';
import {Tile as TileLayer, VectorTile as VectorTileLayer} from '../src/ol/layer.js';
import Projection from '../src/ol/proj/Projection.js'; import Projection from '../src/ol/proj/Projection.js';
import VectorTileSource from '../src/ol/source/VectorTile.js';
import View from '../src/ol/View.js';
import {
Tile as TileLayer,
VectorTile as VectorTileLayer,
} from '../src/ol/layer.js';
// Converts geojson-vt data to GeoJSON // Converts geojson-vt data to GeoJSON
const replacer = function (key, value) { const replacer = function (key, value) {
@@ -37,9 +40,9 @@ const replacer = function(key, value) {
'type': 'Feature', 'type': 'Feature',
'geometry': { 'geometry': {
'type': type, 'type': type,
'coordinates': geometry 'coordinates': geometry,
}, },
'properties': value.tags 'properties': value.tags,
}; };
} else { } else {
return value; return value;
@@ -49,23 +52,25 @@ const replacer = function(key, value) {
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const 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) {
const tileIndex = geojsonvt(json, { const tileIndex = geojsonvt(json, {
extent: 4096, extent: 4096,
debug: 1 debug: 1,
}); });
const vectorSource = new VectorTileSource({ const vectorSource = new VectorTileSource({
format: new GeoJSON({ format: new GeoJSON({
@@ -73,20 +78,27 @@ fetch(url).then(function(response) {
dataProjection: new Projection({ dataProjection: new Projection({
code: 'TILE_PIXELS', code: 'TILE_PIXELS',
units: 'tile-pixels', units: 'tile-pixels',
extent: [0, 0, 4096, 4096] extent: [0, 0, 4096, 4096],
}) }),
}), }),
tileUrlFunction: function (tileCoord) { tileUrlFunction: function (tileCoord) {
const data = tileIndex.getTile(tileCoord[0], tileCoord[1], tileCoord[2]); const data = tileIndex.getTile(
const geojson = JSON.stringify({ tileCoord[0],
tileCoord[1],
tileCoord[2]
);
const geojson = JSON.stringify(
{
type: 'FeatureCollection', type: 'FeatureCollection',
features: data ? data.features : [] features: data ? data.features : [],
}, replacer); },
replacer
);
return 'data:application/json;charset=UTF-8,' + geojson; return 'data:application/json;charset=UTF-8,' + geojson;
} },
}); });
const vectorLayer = new VectorTileLayer({ const vectorLayer = new VectorTileLayer({
source: vectorSource source: vectorSource,
}); });
map.addLayer(vectorLayer); map.addLayer(vectorLayer);
}); });

View File

@@ -1,82 +1,81 @@
import Circle from '../src/ol/geom/Circle.js';
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Circle from '../src/ol/geom/Circle.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js'; import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const 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}),
}); });
const styles = { const styles = {
'Point': new Style({ 'Point': new Style({
image: image image: image,
}), }),
'LineString': new Style({ 'LineString': new Style({
stroke: new Stroke({ stroke: new Stroke({
color: 'green', color: 'green',
width: 1 width: 1,
}) }),
}), }),
'MultiLineString': new Style({ 'MultiLineString': new Style({
stroke: new Stroke({ stroke: new Stroke({
color: 'green', color: 'green',
width: 1 width: 1,
}) }),
}), }),
'MultiPoint': new Style({ 'MultiPoint': new Style({
image: image image: image,
}), }),
'MultiPolygon': new Style({ 'MultiPolygon': new Style({
stroke: new Stroke({ stroke: new Stroke({
color: 'yellow', color: 'yellow',
width: 1 width: 1,
}), }),
fill: new Fill({ fill: new Fill({
color: 'rgba(255, 255, 0, 0.1)' color: 'rgba(255, 255, 0, 0.1)',
}) }),
}), }),
'Polygon': new Style({ 'Polygon': new Style({
stroke: new Stroke({ stroke: new Stroke({
color: 'blue', color: 'blue',
lineDash: [4], lineDash: [4],
width: 3 width: 3,
}), }),
fill: new Fill({ fill: new Fill({
color: 'rgba(0, 0, 255, 0.1)' color: 'rgba(0, 0, 255, 0.1)',
}) }),
}), }),
'GeometryCollection': new Style({ 'GeometryCollection': new Style({
stroke: new Stroke({ stroke: new Stroke({
color: 'magenta', color: 'magenta',
width: 2 width: 2,
}), }),
fill: new Fill({ fill: new Fill({
color: 'magenta' color: 'magenta',
}), }),
image: new CircleStyle({ image: new CircleStyle({
radius: 10, radius: 10,
fill: null, fill: null,
stroke: new Stroke({ stroke: new Stroke({
color: 'magenta' color: 'magenta',
}) }),
}) }),
}), }),
'Circle': new Style({ 'Circle': new Style({
stroke: new Stroke({ stroke: new Stroke({
color: 'red', color: 'red',
width: 2 width: 2,
}), }),
fill: new Fill({ fill: new Fill({
color: 'rgba(255,0,0,0.2)' color: 'rgba(255,0,0,0.2)',
}) }),
}) }),
}; };
const styleFunction = function (feature) { const styleFunction = function (feature) {
@@ -88,93 +87,159 @@ const geojsonObject = {
'crs': { 'crs': {
'type': 'name', 'type': 'name',
'properties': { 'properties': {
'name': 'EPSG:3857' 'name': 'EPSG:3857',
}
}, },
'features': [{ },
'features': [
{
'type': 'Feature', 'type': 'Feature',
'geometry': { 'geometry': {
'type': 'Point', 'type': 'Point',
'coordinates': [0, 0] 'coordinates': [0, 0],
} },
}, { },
{
'type': 'Feature', 'type': 'Feature',
'geometry': { 'geometry': {
'type': 'LineString', 'type': 'LineString',
'coordinates': [[4e6, -2e6], [8e6, 2e6]] 'coordinates': [
} [4e6, -2e6],
}, { [8e6, 2e6],
],
},
},
{
'type': 'Feature', 'type': 'Feature',
'geometry': { 'geometry': {
'type': 'LineString', 'type': 'LineString',
'coordinates': [[4e6, 2e6], [8e6, -2e6]] 'coordinates': [
} [4e6, 2e6],
}, { [8e6, -2e6],
],
},
},
{
'type': 'Feature', 'type': 'Feature',
'geometry': { 'geometry': {
'type': 'Polygon', 'type': 'Polygon',
'coordinates': [[[-5e6, -1e6], [-4e6, 1e6], [-3e6, -1e6]]] 'coordinates': [
} [
}, { [-5e6, -1e6],
[-4e6, 1e6],
[-3e6, -1e6],
],
],
},
},
{
'type': 'Feature', 'type': 'Feature',
'geometry': { 'geometry': {
'type': 'MultiLineString', 'type': 'MultiLineString',
'coordinates': [ 'coordinates': [
[[-1e6, -7.5e5], [-1e6, 7.5e5]], [
[[1e6, -7.5e5], [1e6, 7.5e5]], [-1e6, -7.5e5],
[[-7.5e5, -1e6], [7.5e5, -1e6]], [-1e6, 7.5e5],
[[-7.5e5, 1e6], [7.5e5, 1e6]] ],
] [
} [1e6, -7.5e5],
}, { [1e6, 7.5e5],
],
[
[-7.5e5, -1e6],
[7.5e5, -1e6],
],
[
[-7.5e5, 1e6],
[7.5e5, 1e6],
],
],
},
},
{
'type': 'Feature', 'type': 'Feature',
'geometry': { 'geometry': {
'type': 'MultiPolygon', 'type': 'MultiPolygon',
'coordinates': [ 'coordinates': [
[[[-5e6, 6e6], [-5e6, 8e6], [-3e6, 8e6], [-3e6, 6e6]]], [
[[[-2e6, 6e6], [-2e6, 8e6], [0, 8e6], [0, 6e6]]], [
[[[1e6, 6e6], [1e6, 8e6], [3e6, 8e6], [3e6, 6e6]]] [-5e6, 6e6],
] [-5e6, 8e6],
} [-3e6, 8e6],
}, { [-3e6, 6e6],
],
],
[
[
[-2e6, 6e6],
[-2e6, 8e6],
[0, 8e6],
[0, 6e6],
],
],
[
[
[1e6, 6e6],
[1e6, 8e6],
[3e6, 8e6],
[3e6, 6e6],
],
],
],
},
},
{
'type': 'Feature', 'type': 'Feature',
'geometry': { 'geometry': {
'type': 'GeometryCollection', 'type': 'GeometryCollection',
'geometries': [{ 'geometries': [
{
'type': 'LineString', 'type': 'LineString',
'coordinates': [[-5e6, -5e6], [0, -5e6]] 'coordinates': [
}, { [-5e6, -5e6],
[0, -5e6],
],
},
{
'type': 'Point', 'type': 'Point',
'coordinates': [4e6, -5e6] 'coordinates': [4e6, -5e6],
}, { },
{
'type': 'Polygon', 'type': 'Polygon',
'coordinates': [[[1e6, -6e6], [2e6, -4e6], [3e6, -6e6]]] 'coordinates': [
}] [
} [1e6, -6e6],
}] [2e6, -4e6],
[3e6, -6e6],
],
],
},
],
},
},
],
}; };
const 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)));
const vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: vectorSource, source: vectorSource,
style: styleFunction style: styleFunction,
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), }),
vectorLayer vectorLayer,
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });

View File

@@ -1,27 +1,27 @@
import Geolocation from '../src/ol/Geolocation.js'; import Geolocation from '../src/ol/Geolocation.js';
import Map from '../src/ol/Map.js';
import Overlay from '../src/ol/Overlay.js';
import View from '../src/ol/View.js';
import LineString from '../src/ol/geom/LineString.js'; import LineString from '../src/ol/geom/LineString.js';
import TileLayer from '../src/ol/layer/Tile.js'; import Map from '../src/ol/Map.js';
import {fromLonLat} from '../src/ol/proj.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import Overlay from '../src/ol/Overlay.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {fromLonLat} from '../src/ol/proj.js';
// creating the view // creating the view
const view = new View({ const view = new View({
center: fromLonLat([5.8713, 45.6452]), center: fromLonLat([5.8713, 45.6452]),
zoom: 19 zoom: 19,
}); });
const tileLayer = new TileLayer({ const tileLayer = new TileLayer({
source: new OSM() source: new OSM(),
}); });
// creating the map // creating the map
const map = new Map({ const map = new Map({
layers: [tileLayer], layers: [tileLayer],
target: 'map', target: 'map',
view: view view: view,
}); });
// Geolocation marker // Geolocation marker
@@ -29,7 +29,7 @@ const markerEl = document.getElementById('geolocation_marker');
const marker = new Overlay({ const marker = new Overlay({
positioning: 'center-center', positioning: 'center-center',
element: markerEl, element: markerEl,
stopEvent: false stopEvent: false,
}); });
map.addOverlay(marker); map.addOverlay(marker);
@@ -44,8 +44,8 @@ const geolocation = new Geolocation({
trackingOptions: { trackingOptions: {
maximumAge: 10000, maximumAge: 10000,
enableHighAccuracy: true, enableHighAccuracy: true,
timeout: 600000 timeout: 600000,
} },
}); });
let deltaMean = 500; // the geolocation sampling period mean in ms let deltaMean = 500; // the geolocation sampling period mean in ms
@@ -71,7 +71,7 @@ geolocation.on('change', function() {
'Accuracy: ' + accuracy, 'Accuracy: ' + accuracy,
'Heading: ' + Math.round(radToDeg(heading)) + '&deg;', 'Heading: ' + Math.round(radToDeg(heading)) + '&deg;',
'Speed: ' + (speed * 3.6).toFixed(1) + ' km/h', 'Speed: ' + (speed * 3.6).toFixed(1) + ' km/h',
'Delta: ' + Math.round(deltaMean) + 'ms' 'Delta: ' + Math.round(deltaMean) + 'ms',
].join('<br />'); ].join('<br />');
document.getElementById('info').innerHTML = html; document.getElementById('info').innerHTML = html;
}); });
@@ -83,15 +83,15 @@ geolocation.on('error', function() {
// convert radians to degrees // convert radians to degrees
function radToDeg(rad) { function radToDeg(rad) {
return rad * 360 / (Math.PI * 2); return (rad * 360) / (Math.PI * 2);
} }
// convert degrees to radians // convert degrees to radians
function degToRad(deg) { function degToRad(deg) {
return deg * Math.PI * 2 / 360; return (deg * Math.PI * 2) / 360;
} }
// modulo for negative values // modulo for negative values
function mod(n) { function mod(n) {
return ((n % (2 * Math.PI)) + (2 * Math.PI)) % (2 * Math.PI); return ((n % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
} }
function addPosition(position, heading, m, speed) { function addPosition(position, heading, m, speed) {
@@ -105,7 +105,7 @@ function addPosition(position, heading, m, speed) {
// 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) {
const 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;
@@ -130,8 +130,8 @@ function getCenterWithHeading(position, rotation, resolution) {
const 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,
position[1] + Math.cos(rotation) * height * resolution * 1 / 4 position[1] + (Math.cos(rotation) * height * resolution * 1) / 4,
]; ];
} }
@@ -153,21 +153,24 @@ function updateView() {
// geolocate device // geolocate device
const 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
tileLayer.on('postrender', updateView); tileLayer.on('postrender', updateView);
map.render(); map.render();
disableButtons(); disableButtons();
}, false); },
false
);
// simulate device move // simulate device move
let simulationData; let simulationData;
const client = new XMLHttpRequest(); const client = new XMLHttpRequest();
client.open('GET', 'data/geolocation-orientation.json'); client.open('GET', 'data/geolocation-orientation.json');
/** /**
* Handle data loading. * Handle data loading.
*/ */
@@ -177,7 +180,9 @@ client.onload = function() {
client.send(); client.send();
const simulateBtn = document.getElementById('simulate'); const simulateBtn = document.getElementById('simulate');
simulateBtn.addEventListener('click', function() { simulateBtn.addEventListener(
'click',
function () {
const coordinates = simulationData; const coordinates = simulationData;
const first = coordinates.shift(); const first = coordinates.shift();
@@ -202,7 +207,9 @@ simulateBtn.addEventListener('click', function() {
map.render(); map.render();
disableButtons(); disableButtons();
}, false); },
false
);
function simulatePositionChange(position) { function simulatePositionChange(position) {
const coords = position.coords; const coords = position.coords;

View File

@@ -1,33 +1,33 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Geolocation from '../src/ol/Geolocation.js'; import Geolocation from '../src/ol/Geolocation.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import Point from '../src/ol/geom/Point.js'; import Point from '../src/ol/geom/Point.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import View from '../src/ol/View.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js'; import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}) }),
], ],
target: 'map', target: 'map',
view: view view: view,
}); });
const geolocation = new Geolocation({ const geolocation = new Geolocation({
// enableHighAccuracy must be set to true to have the heading value. // enableHighAccuracy must be set to true to have the heading value.
trackingOptions: { trackingOptions: {
enableHighAccuracy: true enableHighAccuracy: true,
}, },
projection: view.getProjection() projection: view.getProjection(),
}); });
function el(id) { function el(id) {
@@ -60,28 +60,29 @@ geolocation.on('change:accuracyGeometry', function() {
}); });
const 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,
fill: new Fill({ fill: new Fill({
color: '#3399CC' color: '#3399CC',
}), }),
stroke: new Stroke({ stroke: new Stroke({
color: '#fff', color: '#fff',
width: 2 width: 2,
}),
}),
}) })
}) );
}));
geolocation.on('change:position', function () { geolocation.on('change:position', function () {
const coordinates = geolocation.getPosition(); const coordinates = geolocation.getPosition();
positionFeature.setGeometry(coordinates ? positionFeature.setGeometry(coordinates ? new Point(coordinates) : null);
new Point(coordinates) : null);
}); });
new VectorLayer({ new VectorLayer({
map: map, map: map,
source: new VectorSource({ source: new VectorSource({
features: [accuracyFeature, positionFeature] features: [accuracyFeature, positionFeature],
}) }),
}); });

View File

@@ -1,37 +1,39 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import ImageLayer from '../src/ol/layer/Image.js'; import ImageLayer from '../src/ol/layer/Image.js';
import ImageWMS from '../src/ol/source/ImageWMS.js'; import ImageWMS from '../src/ol/source/ImageWMS.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
const 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',
}); });
const wmsLayer = new ImageLayer({ const wmsLayer = new ImageLayer({
source: wmsSource source: wmsSource,
}); });
const view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1,
}); });
const map = new Map({ const map = new Map({
layers: [wmsLayer], layers: [wmsLayer],
target: 'map', target: 'map',
view: view view: view,
}); });
map.on('singleclick', function (evt) { map.on('singleclick', function (evt) {
document.getElementById('info').innerHTML = ''; document.getElementById('info').innerHTML = '';
const viewResolution = /** @type {number} */ (view.getResolution()); const viewResolution = /** @type {number} */ (view.getResolution());
const url = wmsSource.getFeatureInfoUrl( const url = wmsSource.getFeatureInfoUrl(
evt.coordinate, viewResolution, 'EPSG:3857', evt.coordinate,
{'INFO_FORMAT': 'text/html'}); viewResolution,
'EPSG:3857',
{'INFO_FORMAT': 'text/html'}
);
if (url) { if (url) {
fetch(url) fetch(url)
.then((response) => response.text()) .then((response) => response.text())

View File

@@ -1,9 +1,10 @@
import WMSGetFeatureInfo from '../src/ol/format/WMSGetFeatureInfo.js'; import WMSGetFeatureInfo from '../src/ol/format/WMSGetFeatureInfo.js';
fetch('data/wmsgetfeatureinfo/osm-restaurant-hotel.xml').then(function(response) { fetch('data/wmsgetfeatureinfo/osm-restaurant-hotel.xml')
.then(function (response) {
return response.text(); return response.text();
}).then(function(response) { })
.then(function (response) {
// this is the standard way to read the features // this is the standard way to read the features
const 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();
@@ -11,13 +12,16 @@ fetch('data/wmsgetfeatureinfo/osm-restaurant-hotel.xml').then(function(response)
// 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
const 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();
const 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

@@ -1,37 +1,39 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import TileWMS from '../src/ol/source/TileWMS.js'; import TileWMS from '../src/ol/source/TileWMS.js';
import View from '../src/ol/View.js';
const 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',
}); });
const wmsLayer = new TileLayer({ const wmsLayer = new TileLayer({
source: wmsSource source: wmsSource,
}); });
const view = new View({ const view = new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1,
}); });
const map = new Map({ const map = new Map({
layers: [wmsLayer], layers: [wmsLayer],
target: 'map', target: 'map',
view: view view: view,
}); });
map.on('singleclick', function (evt) { map.on('singleclick', function (evt) {
document.getElementById('info').innerHTML = ''; document.getElementById('info').innerHTML = '';
const viewResolution = /** @type {number} */ (view.getResolution()); const viewResolution = /** @type {number} */ (view.getResolution());
const url = wmsSource.getFeatureInfoUrl( const url = wmsSource.getFeatureInfoUrl(
evt.coordinate, viewResolution, 'EPSG:3857', evt.coordinate,
{'INFO_FORMAT': 'text/html'}); viewResolution,
'EPSG:3857',
{'INFO_FORMAT': 'text/html'}
);
if (url) { if (url) {
fetch(url) fetch(url)
.then((response) => response.text()) .then((response) => response.text())

View File

@@ -1,58 +1,59 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import GPX from '../src/ol/format/GPX.js'; import GPX from '../src/ol/format/GPX.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import Map from '../src/ol/Map.js';
import XYZ from '../src/ol/source/XYZ.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js';
import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js'; import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const raster = new TileLayer({ const raster = new TileLayer({
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
maxZoom: 20 maxZoom: 20,
}) }),
}); });
const style = { const style = {
'Point': new Style({ 'Point': new Style({
image: new CircleStyle({ image: new CircleStyle({
fill: new Fill({ fill: new Fill({
color: 'rgba(255,255,0,0.4)' color: 'rgba(255,255,0,0.4)',
}), }),
radius: 5, radius: 5,
stroke: new Stroke({ stroke: new Stroke({
color: '#ff0', color: '#ff0',
width: 1 width: 1,
}) }),
}) }),
}), }),
'LineString': new Style({ 'LineString': new Style({
stroke: new Stroke({ stroke: new Stroke({
color: '#f00', color: '#f00',
width: 3 width: 3,
}) }),
}), }),
'MultiLineString': new Style({ 'MultiLineString': new Style({
stroke: new Stroke({ stroke: new Stroke({
color: '#0f0', color: '#0f0',
width: 3 width: 3,
}) }),
}) }),
}; };
const 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(),
}), }),
style: function (feature) { style: function (feature) {
return style[feature.getGeometry().getType()]; return style[feature.getGeometry().getType()];
} },
}); });
const map = new Map({ const map = new Map({
@@ -60,8 +61,8 @@ const map = new Map({
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new View({
center: [-7916041.528716288, 5228379.045749711], center: [-7916041.528716288, 5228379.045749711],
zoom: 12 zoom: 12,
}) }),
}); });
const displayFeatureInfo = function (pixel) { const displayFeatureInfo = function (pixel) {

View File

@@ -1,33 +1,32 @@
import Graticule from '../src/ol/layer/Graticule.js'; import Graticule from '../src/ol/layer/Graticule.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js';
import {fromLonLat} from '../src/ol/proj.js';
import OSM from '../src/ol/source/OSM.js'; import OSM from '../src/ol/source/OSM.js';
import Stroke from '../src/ol/style/Stroke.js'; import Stroke from '../src/ol/style/Stroke.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {fromLonLat} from '../src/ol/proj.js';
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM({ source: new OSM({
wrapX: false wrapX: false,
}) }),
}), }),
new 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)',
width: 2, width: 2,
lineDash: [0.5, 4] lineDash: [0.5, 4],
}), }),
showLabels: true, showLabels: true,
wrapX: false wrapX: false,
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: fromLonLat([4.8, 47.75]), center: fromLonLat([4.8, 47.75]),
zoom: 5 zoom: 5,
}) }),
}); });

View File

@@ -1,9 +1,9 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import KML from '../src/ol/format/KML.js'; import KML from '../src/ol/format/KML.js';
import {Heatmap as HeatmapLayer, Tile as TileLayer} from '../src/ol/layer.js'; import Map from '../src/ol/Map.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';
import View from '../src/ol/View.js';
import {Heatmap as HeatmapLayer, Tile as TileLayer} from '../src/ol/layer.js';
const blur = document.getElementById('blur'); const blur = document.getElementById('blur');
const radius = document.getElementById('radius'); const radius = document.getElementById('radius');
@@ -12,8 +12,8 @@ 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({
extractStyles: false extractStyles: false,
}) }),
}), }),
blur: parseInt(blur.value, 10), blur: parseInt(blur.value, 10),
radius: parseInt(radius.value, 10), radius: parseInt(radius.value, 10),
@@ -24,13 +24,13 @@ const vector = new HeatmapLayer({
const name = feature.get('name'); const name = feature.get('name');
const magnitude = parseFloat(name.substr(2)); const magnitude = parseFloat(name.substr(2));
return magnitude - 5; return magnitude - 5;
} },
}); });
const raster = new TileLayer({ const raster = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner',
}) }),
}); });
new Map({ new Map({
@@ -38,8 +38,8 @@ new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const blurHandler = function () { const blurHandler = function () {

View File

@@ -1,6 +1,6 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js'; import XYZ from '../src/ol/source/XYZ.js';
const appId = 'kDm0Jq1K4Ak7Bwtn8uvk'; const appId = 'kDm0Jq1K4Ak7Bwtn8uvk';
@@ -11,60 +11,66 @@ const hereLayers = [
type: 'maptile', type: 'maptile',
scheme: 'normal.day', scheme: 'normal.day',
app_id: appId, app_id: appId,
app_code: appCode app_code: appCode,
}, },
{ {
base: 'base', base: 'base',
type: 'maptile', type: 'maptile',
scheme: 'normal.day.transit', scheme: 'normal.day.transit',
app_id: appId, app_id: appId,
app_code: appCode app_code: appCode,
}, },
{ {
base: 'base', base: 'base',
type: 'maptile', type: 'maptile',
scheme: 'pedestrian.day', scheme: 'pedestrian.day',
app_id: appId, app_id: appId,
app_code: appCode app_code: appCode,
}, },
{ {
base: 'aerial', base: 'aerial',
type: 'maptile', type: 'maptile',
scheme: 'terrain.day', scheme: 'terrain.day',
app_id: appId, app_id: appId,
app_code: appCode app_code: appCode,
}, },
{ {
base: 'aerial', base: 'aerial',
type: 'maptile', type: 'maptile',
scheme: 'satellite.day', scheme: 'satellite.day',
app_id: appId, app_id: appId,
app_code: appCode app_code: appCode,
}, },
{ {
base: 'aerial', base: 'aerial',
type: 'maptile', type: 'maptile',
scheme: 'hybrid.day', scheme: 'hybrid.day',
app_id: appId, app_id: appId,
app_code: appCode app_code: appCode,
} },
]; ];
const 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}';
const layers = []; const layers = [];
let i, ii; let i, ii;
for (i = 0, ii = hereLayers.length; i < ii; ++i) { for (i = 0, ii = hereLayers.length; i < ii; ++i) {
const layerDesc = hereLayers[i]; const layerDesc = hereLayers[i];
layers.push(new TileLayer({ layers.push(
new TileLayer({
visible: false, visible: false,
preload: Infinity, preload: Infinity,
source: new XYZ({ source: new XYZ({
url: createUrl(urlTpl, layerDesc), url: createUrl(urlTpl, layerDesc),
attributions: 'Map Tiles &copy; ' + new Date().getFullYear() + ' ' + attributions:
'<a href="http://developer.here.com">HERE</a>' 'Map Tiles &copy; ' +
new Date().getFullYear() +
' ' +
'<a href="http://developer.here.com">HERE</a>',
}),
}) })
})); );
} }
const map = new Map({ const map = new Map({
@@ -72,8 +78,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [921371.9389, 6358337.7609], center: [921371.9389, 6358337.7609],
zoom: 10 zoom: 10,
}) }),
}); });
function createUrl(tpl, layerDesc) { function createUrl(tpl, layerDesc) {

View File

@@ -1,29 +1,34 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import LineString from '../src/ol/geom/LineString.js'; import LineString from '../src/ol/geom/LineString.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Stroke, Style} from '../src/ol/style.js'; import {Stroke, Style} from '../src/ol/style.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const style = new Style({ const style = new Style({
stroke: new Stroke({ stroke: new Stroke({
color: 'black', color: 'black',
width: 1 width: 1,
}) }),
}); });
const feature = new Feature(new LineString([[-4000000, 0], [4000000, 0]])); const feature = new Feature(
new LineString([
[-4000000, 0],
[4000000, 0],
])
);
const vector = new VectorLayer({ const vector = new VectorLayer({
source: new VectorSource({ source: new VectorSource({
features: [feature] features: [feature],
}), }),
style: style style: style,
}); });
const map = new Map({ const map = new Map({
@@ -31,8 +36,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
let hitTolerance; let hitTolerance;
@@ -41,11 +46,15 @@ const statusElement = document.getElementById('status');
map.on('singleclick', function (e) { map.on('singleclick', function (e) {
let hit = false; let hit = false;
map.forEachFeatureAtPixel(e.pixel, function() { map.forEachFeatureAtPixel(
e.pixel,
function () {
hit = true; hit = true;
}, { },
hitTolerance: hitTolerance {
}); hitTolerance: hitTolerance,
}
);
if (hit) { if (hit) {
style.getStroke().setColor('green'); style.getStroke().setColor('green');
statusElement.innerHTML = '&nbsp;A feature got hit!'; statusElement.innerHTML = '&nbsp;A feature got hit!';
@@ -68,7 +77,13 @@ const changeHitTolerance = function() {
const 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
);
ctx.fill(); ctx.fill();
ctx.stroke(); ctx.stroke();
}; };

View File

@@ -1,40 +1,39 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import GeoJSON from '../src/ol/format/GeoJSON.js'; import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.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';
import View from '../src/ol/View.js';
import {Fill, Stroke, Style, Text} from '../src/ol/style.js'; import {Fill, Stroke, Style, Text} from '../src/ol/style.js';
const 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)',
}), }),
stroke: new Stroke({ stroke: new Stroke({
color: '#319FD3', color: '#319FD3',
width: 1 width: 1,
}), }),
text: new Text({ text: new Text({
font: '12px Calibri,sans-serif', font: '12px Calibri,sans-serif',
fill: new Fill({ fill: new Fill({
color: '#000' color: '#000',
}), }),
stroke: new Stroke({ stroke: new Stroke({
color: '#fff', color: '#fff',
width: 3 width: 3,
}) }),
}) }),
}); });
const 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(),
}), }),
style: function (feature) { style: function (feature) {
style.getText().setText(feature.get('name')); style.getText().setText(feature.get('name'));
return style; return style;
} },
}); });
const map = new Map({ const map = new Map({
@@ -42,28 +41,28 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1,
}) }),
}); });
const highlightStyle = new Style({ const highlightStyle = new Style({
stroke: new Stroke({ stroke: new Stroke({
color: '#f00', color: '#f00',
width: 1 width: 1,
}), }),
fill: new Fill({ fill: new Fill({
color: 'rgba(255,0,0,0.1)' color: 'rgba(255,0,0,0.1)',
}), }),
text: new Text({ text: new Text({
font: '12px Calibri,sans-serif', font: '12px Calibri,sans-serif',
fill: new Fill({ fill: new Fill({
color: '#000' color: '#000',
}), }),
stroke: new Stroke({ stroke: new Stroke({
color: '#f00', color: '#f00',
width: 3 width: 3,
}) }),
}) }),
}); });
const featureOverlay = new VectorLayer({ const featureOverlay = new VectorLayer({
@@ -72,12 +71,11 @@ const featureOverlay = new VectorLayer({
style: function (feature) { style: function (feature) {
highlightStyle.getText().setText(feature.get('name')); highlightStyle.getText().setText(feature.get('name'));
return highlightStyle; return highlightStyle;
} },
}); });
let highlight; let highlight;
const displayFeatureInfo = function (pixel) { const displayFeatureInfo = function (pixel) {
vectorLayer.getFeatures(pixel).then(function (features) { vectorLayer.getFeatures(pixel).then(function (features) {
const feature = features.length ? features[0] : undefined; const feature = features.length ? features[0] : undefined;
const info = document.getElementById('info'); const info = document.getElementById('info');
@@ -97,7 +95,6 @@ const displayFeatureInfo = function(pixel) {
highlight = feature; highlight = feature;
} }
}); });
}; };
map.on('pointermove', function (evt) { map.on('pointermove', function (evt) {

View File

@@ -1,72 +1,76 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import Point from '../src/ol/geom/Point.js'; import Point from '../src/ol/geom/Point.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {fromLonLat} from '../src/ol/proj.js';
import TileJSON from '../src/ol/source/TileJSON.js'; import TileJSON from '../src/ol/source/TileJSON.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
import {Icon, Style} from '../src/ol/style.js'; import {Icon, Style} from '../src/ol/style.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {fromLonLat} from '../src/ol/proj.js';
const rome = new Feature({ const rome = new Feature({
geometry: new Point(fromLonLat([12.5, 41.9])) geometry: new Point(fromLonLat([12.5, 41.9])),
}); });
const london = new Feature({ const london = new Feature({
geometry: new Point(fromLonLat([-0.12755, 51.507222])) geometry: new Point(fromLonLat([-0.12755, 51.507222])),
}); });
const madrid = new Feature({ const madrid = new Feature({
geometry: new Point(fromLonLat([-3.683333, 40.4])) geometry: new Point(fromLonLat([-3.683333, 40.4])),
}); });
rome.setStyle(new Style({ rome.setStyle(
new Style({
image: new Icon({ image: new Icon({
color: '#8959A8', color: '#8959A8',
crossOrigin: 'anonymous', crossOrigin: 'anonymous',
imgSize: [20, 20], imgSize: [20, 20],
src: 'data/square.svg' src: 'data/square.svg',
}),
}) })
})); );
london.setStyle(new Style({ london.setStyle(
new Style({
image: new Icon({ image: new Icon({
color: '#4271AE', color: '#4271AE',
crossOrigin: 'anonymous', crossOrigin: 'anonymous',
src: 'data/dot.png' src: 'data/dot.png',
}),
}) })
})); );
madrid.setStyle(new Style({ madrid.setStyle(
new Style({
image: new Icon({ image: new Icon({
color: [113, 140, 0], color: [113, 140, 0],
crossOrigin: 'anonymous', crossOrigin: 'anonymous',
src: 'data/dot.png' src: 'data/dot.png',
}),
}) })
})); );
const vectorSource = new VectorSource({ const vectorSource = new VectorSource({
features: [rome, london, madrid] features: [rome, london, madrid],
}); });
const vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: vectorSource source: vectorSource,
}); });
const rasterLayer = new TileLayer({ const rasterLayer = new TileLayer({
source: new TileJSON({ source: new TileJSON({
url: 'https://a.tiles.mapbox.com/v3/aj.1x1-degrees.json', url: 'https://a.tiles.mapbox.com/v3/aj.1x1-degrees.json',
crossOrigin: '' crossOrigin: '',
}) }),
}); });
const 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({
center: fromLonLat([2.896372, 44.60240]), center: fromLonLat([2.896372, 44.6024]),
zoom: 3 zoom: 3,
}) }),
}); });

View File

@@ -1,13 +1,12 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import Point from '../src/ol/geom/Point.js'; import Point from '../src/ol/geom/Point.js';
import Select from '../src/ol/interaction/Select.js'; import Select from '../src/ol/interaction/Select.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.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';
import View from '../src/ol/View.js';
import {Icon, Style} from '../src/ol/style.js'; import {Icon, Style} from '../src/ol/style.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
function createStyle(src, img) { function createStyle(src, img) {
return new Style({ return new Style({
@@ -16,8 +15,8 @@ function createStyle(src, img) {
crossOrigin: 'anonymous', crossOrigin: 'anonymous',
src: src, src: src,
img: img, img: img,
imgSize: img ? [img.width, img.height] : undefined imgSize: img ? [img.width, img.height] : undefined,
}) }),
}); });
} }
@@ -27,20 +26,20 @@ iconFeature.set('style', createStyle('data/icon.png', undefined));
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new Stamen({layer: 'watercolor'}) source: new Stamen({layer: 'watercolor'}),
}), }),
new VectorLayer({ new VectorLayer({
style: function (feature) { style: function (feature) {
return feature.get('style'); return feature.get('style');
}, },
source: new VectorSource({features: [iconFeature]}) source: new VectorSource({features: [iconFeature]}),
}) }),
], ],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 3 zoom: 3,
}) }),
}); });
const selectStyle = {}; const selectStyle = {};
@@ -62,11 +61,12 @@ const select = new Select({
selectStyle[image.src] = createStyle(undefined, canvas); selectStyle[image.src] = createStyle(undefined, canvas);
} }
return selectStyle[image.src]; return selectStyle[image.src];
} },
}); });
map.addInteraction(select); map.addInteraction(select);
map.on('pointermove', function (evt) { map.on('pointermove', function (evt) {
map.getTargetElement().style.cursor = map.getTargetElement().style.cursor = map.hasFeatureAtPixel(evt.pixel)
map.hasFeatureAtPixel(evt.pixel) ? 'pointer' : ''; ? 'pointer'
: '';
}); });

View File

@@ -1,34 +1,37 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js';
import TileJSON from '../src/ol/source/TileJSON.js';
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js';
import Point from '../src/ol/geom/Point.js'; import Point from '../src/ol/geom/Point.js';
import TileJSON from '../src/ol/source/TileJSON.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import WebGLPointsLayer from '../src/ol/layer/WebGLPoints.js';
import {Vector} from '../src/ol/source.js'; import {Vector} from '../src/ol/source.js';
import {fromLonLat} from '../src/ol/proj.js'; import {fromLonLat} from '../src/ol/proj.js';
import WebGLPointsLayer from '../src/ol/layer/WebGLPoints.js';
const key = 'pk.eyJ1IjoidHNjaGF1YiIsImEiOiJjaW5zYW5lNHkxMTNmdWttM3JyOHZtMmNtIn0.CDIBD8H-G2Gf-cPkIuWtRg'; const key =
'pk.eyJ1IjoidHNjaGF1YiIsImEiOiJjaW5zYW5lNHkxMTNmdWttM3JyOHZtMmNtIn0.CDIBD8H-G2Gf-cPkIuWtRg';
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new TileJSON({ source: new TileJSON({
url: 'https://api.tiles.mapbox.com/v4/mapbox.world-dark.json?secure&access_token=' + key, url:
crossOrigin: 'anonymous' 'https://api.tiles.mapbox.com/v4/mapbox.world-dark.json?secure&access_token=' +
}) key,
}) crossOrigin: 'anonymous',
}),
}),
], ],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new View({
center: [0, 4000000], center: [0, 4000000],
zoom: 2 zoom: 2,
}) }),
}); });
const vectorSource = new Vector({ const vectorSource = new Vector({
features: [], features: [],
attributions: 'National UFO Reporting Center' attributions: 'National UFO Reporting Center',
}); });
const oldColor = [255, 160, 110]; const oldColor = [255, 160, 110];
@@ -37,13 +40,13 @@ const size = 16;
const style = { const style = {
variables: { variables: {
filterShape: 'all' filterShape: 'all',
}, },
filter: [ filter: [
'case', 'case',
['!=', ['var', 'filterShape'], 'all'], ['!=', ['var', 'filterShape'], 'all'],
['==', ['get', 'shape'], ['var', 'filterShape']], ['==', ['get', 'shape'], ['var', 'filterShape']],
true true,
], ],
symbol: { symbol: {
symbolType: 'image', symbolType: 'image',
@@ -53,36 +56,43 @@ const style = {
'interpolate', 'interpolate',
['linear'], ['linear'],
['get', 'year'], ['get', 'year'],
1950, oldColor, 1950,
2013, newColor oldColor,
2013,
newColor,
], ],
rotateWithView: false, rotateWithView: false,
offset: [ offset: [0, 0],
0,
0
],
textureCoord: [ textureCoord: [
'match', 'match',
['get', 'shape'], ['get', 'shape'],
'light', [0, 0, 0.25, 0.5], 'light',
'sphere', [0.25, 0, 0.5, 0.5], [0, 0, 0.25, 0.5],
'circle', [0.25, 0, 0.5, 0.5], 'sphere',
'disc', [0.5, 0, 0.75, 0.5], [0.25, 0, 0.5, 0.5],
'oval', [0.5, 0, 0.75, 0.5], 'circle',
'triangle', [0.75, 0, 1, 0.5], [0.25, 0, 0.5, 0.5],
'fireball', [0, 0.5, 0.25, 1], 'disc',
[0.75, 0.5, 1, 1] [0.5, 0, 0.75, 0.5],
] 'oval',
} [0.5, 0, 0.75, 0.5],
'triangle',
[0.75, 0, 1, 0.5],
'fireball',
[0, 0.5, 0.25, 1],
[0.75, 0.5, 1, 1],
],
},
}; };
// key is shape name, value is sightings count // key is shape name, value is sightings count
const shapeTypes = { const shapeTypes = {
all: 0 all: 0,
}; };
const shapeSelect = document.getElementById('shape-filter'); const shapeSelect = document.getElementById('shape-filter');
shapeSelect.addEventListener('input', function () { shapeSelect.addEventListener('input', function () {
style.variables.filterShape = shapeSelect.options[shapeSelect.selectedIndex].value; style.variables.filterShape =
shapeSelect.options[shapeSelect.selectedIndex].value;
map.render(); map.render();
}); });
function fillShapeSelect() { function fillShapeSelect() {
@@ -122,13 +132,15 @@ client.onload = function() {
shapeTypes[shape] = (shapeTypes[shape] ? shapeTypes[shape] : 0) + 1; shapeTypes[shape] = (shapeTypes[shape] ? shapeTypes[shape] : 0) + 1;
shapeTypes['all']++; shapeTypes['all']++;
features.push(new Feature({ features.push(
new Feature({
datetime: line[0], datetime: line[0],
year: parseInt(/[0-9]{4}/.exec(line[0])[0]), // extract the year as int year: parseInt(/[0-9]{4}/.exec(line[0])[0]), // extract the year as int
shape: shape, shape: shape,
duration: line[3], duration: line[3],
geometry: new Point(coords) geometry: new Point(coords),
})); })
);
} }
vectorSource.addFeatures(features); vectorSource.addFeatures(features);
fillShapeSelect(); fillShapeSelect();
@@ -138,7 +150,7 @@ client.send();
map.addLayer( map.addLayer(
new WebGLPointsLayer({ new WebGLPointsLayer({
source: vectorSource, source: vectorSource,
style: style style: style,
}) })
); );
@@ -153,6 +165,13 @@ map.on('pointermove', function(evt) {
const datetime = feature.get('datetime'); const datetime = feature.get('datetime');
const duration = feature.get('duration'); const duration = feature.get('duration');
const shape = feature.get('shape'); const shape = feature.get('shape');
info.innerText = 'On ' + datetime + ', lasted ' + duration + ' seconds and had a "' + shape + '" shape.'; info.innerText =
'On ' +
datetime +
', lasted ' +
duration +
' seconds and had a "' +
shape +
'" shape.';
}); });
}); });

View File

@@ -1,19 +1,18 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import Overlay from '../src/ol/Overlay.js'; import Overlay from '../src/ol/Overlay.js';
import View from '../src/ol/View.js';
import Point from '../src/ol/geom/Point.js'; import Point from '../src/ol/geom/Point.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import TileJSON from '../src/ol/source/TileJSON.js'; import TileJSON from '../src/ol/source/TileJSON.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
import {Icon, Style} from '../src/ol/style.js'; import {Icon, Style} from '../src/ol/style.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const 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,
}); });
const iconStyle = new Style({ const iconStyle = new Style({
@@ -21,25 +20,25 @@ const iconStyle = new Style({
anchor: [0.5, 46], anchor: [0.5, 46],
anchorXUnits: 'fraction', anchorXUnits: 'fraction',
anchorYUnits: 'pixels', anchorYUnits: 'pixels',
src: 'data/icon.png' src: 'data/icon.png',
}) }),
}); });
iconFeature.setStyle(iconStyle); iconFeature.setStyle(iconStyle);
const vectorSource = new VectorSource({ const vectorSource = new VectorSource({
features: [iconFeature] features: [iconFeature],
}); });
const vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: vectorSource source: vectorSource,
}); });
const rasterLayer = new TileLayer({ const rasterLayer = new TileLayer({
source: new TileJSON({ source: new TileJSON({
url: 'https://a.tiles.mapbox.com/v3/aj.1x1-degrees.json', url: 'https://a.tiles.mapbox.com/v3/aj.1x1-degrees.json',
crossOrigin: '' crossOrigin: '',
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -47,8 +46,8 @@ const map = new Map({
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 3 zoom: 3,
}) }),
}); });
const element = document.getElementById('popup'); const element = document.getElementById('popup');
@@ -57,14 +56,13 @@ const popup = new Overlay({
element: element, element: element,
positioning: 'bottom-center', positioning: 'bottom-center',
stopEvent: false, stopEvent: false,
offset: [0, -50] offset: [0, -50],
}); });
map.addOverlay(popup); map.addOverlay(popup);
// display popup on click // display popup on click
map.on('click', function (evt) { map.on('click', function (evt) {
const feature = map.forEachFeatureAtPixel(evt.pixel, const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
function(feature) {
return feature; return feature;
}); });
if (feature) { if (feature) {
@@ -73,7 +71,7 @@ map.on('click', function(evt) {
$(element).popover({ $(element).popover({
placement: 'top', placement: 'top',
html: true, html: true,
content: feature.get('name') content: feature.get('name'),
}); });
$(element).popover('show'); $(element).popover('show');
} else { } else {

View File

@@ -1,21 +1,20 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import IGC from '../src/ol/format/IGC.js'; import IGC from '../src/ol/format/IGC.js';
import {LineString, Point} from '../src/ol/geom.js'; import Map from '../src/ol/Map.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import OSM, {ATTRIBUTION} from '../src/ol/source/OSM.js'; import OSM, {ATTRIBUTION} from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js'; import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js';
import {LineString, Point} from '../src/ol/geom.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {getVectorContext} from '../src/ol/render.js'; import {getVectorContext} from '../src/ol/render.js';
const 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)',
'Tom Payne': 'rgba(0, 255, 255, 0.7)', 'Tom Payne': 'rgba(0, 255, 255, 0.7)',
'Ulrich Prinz': 'rgba(0, 215, 255, 0.7)' 'Ulrich Prinz': 'rgba(0, 215, 255, 0.7)',
}; };
const styleCache = {}; const styleCache = {};
@@ -26,8 +25,8 @@ const styleFunction = function(feature) {
style = new Style({ style = new Style({
stroke: new Stroke({ stroke: new Stroke({
color: color, color: color,
width: 3 width: 3,
}) }),
}); });
styleCache[color] = style; styleCache[color] = style;
} }
@@ -41,7 +40,7 @@ const igcUrls = [
'data/igc/Damien-de-Baenst.igc', 'data/igc/Damien-de-Baenst.igc',
'data/igc/Sylvain-Dhonneur.igc', 'data/igc/Sylvain-Dhonneur.igc',
'data/igc/Tom-Payne.igc', 'data/igc/Tom-Payne.igc',
'data/igc/Ulrich-Prinz.igc' 'data/igc/Ulrich-Prinz.igc',
]; ];
function get(url, callback) { function get(url, callback) {
@@ -56,8 +55,9 @@ function get(url, callback) {
const igcFormat = new IGC(); const igcFormat = new IGC();
for (let i = 0; i < igcUrls.length; ++i) { for (let i = 0; i < igcUrls.length; ++i) {
get(igcUrls[i], function (data) { get(igcUrls[i], function (data) {
const features = igcFormat.readFeatures(data, const features = igcFormat.readFeatures(data, {
{featureProjection: 'EPSG:3857'}); featureProjection: 'EPSG:3857',
});
vectorSource.addFeatures(features); vectorSource.addFeatures(features);
}); });
} }
@@ -65,7 +65,7 @@ for (let i = 0; i < igcUrls.length; ++i) {
const 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) {
const geometry = event.feature.getGeometry(); const geometry = event.feature.getGeometry();
@@ -76,7 +76,7 @@ vectorSource.on('addfeature', function(event) {
const vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: vectorSource, source: vectorSource,
style: styleFunction style: styleFunction,
}); });
const map = new Map({ const map = new Map({
@@ -85,22 +85,22 @@ const map = new Map({
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>',
ATTRIBUTION ATTRIBUTION,
], ],
url: 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' + url:
'?apikey=0e6fc415256d4fbb9b5166a718591d71' 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' +
}) '?apikey=0e6fc415256d4fbb9b5166a718591d71',
}), }),
vectorLayer }),
vectorLayer,
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [703365.7089403362, 5714629.865071137], center: [703365.7089403362, 5714629.865071137],
zoom: 9 zoom: 9,
}) }),
}); });
let point = null; let point = null;
let line = null; let line = null;
const displaySnap = function (coordinate) { const displaySnap = function (coordinate) {
@@ -145,15 +145,15 @@ map.on('click', function(evt) {
const 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,
}); });
const style = new Style({ const style = new Style({
stroke: stroke, stroke: stroke,
image: new CircleStyle({ image: new CircleStyle({
radius: 5, radius: 5,
fill: null, fill: null,
stroke: stroke stroke: stroke,
}) }),
}); });
vectorLayer.on('postrender', function (evt) { vectorLayer.on('postrender', function (evt) {
const vectorContext = getVectorContext(evt); const vectorContext = getVectorContext(evt);
@@ -173,15 +173,15 @@ const featureOverlay = new VectorLayer({
image: new CircleStyle({ image: new CircleStyle({
radius: 5, radius: 5,
fill: new Fill({ fill: new Fill({
color: 'rgba(255,0,0,0.9)' color: 'rgba(255,0,0,0.9)',
}) }),
}) }),
}) }),
}); });
document.getElementById('time').addEventListener('input', function () { document.getElementById('time').addEventListener('input', function () {
const value = parseInt(this.value, 10) / 100; const value = parseInt(this.value, 10) / 100;
const m = time.start + (time.duration * value); const m = time.start + time.duration * value;
vectorSource.forEachFeature(function (feature) { vectorSource.forEachFeature(function (feature) {
const geometry = /** @type {import("../src/ol/geom/LineString.js").default} */ (feature.getGeometry()); const geometry = /** @type {import("../src/ol/geom/LineString.js").default} */ (feature.getGeometry());
const coordinate = geometry.getCoordinateAtM(m, true); const coordinate = geometry.getCoordinateAtM(m, true);

View File

@@ -1,40 +1,48 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js';
import IIIF from '../src/ol/source/IIIF.js'; import IIIF from '../src/ol/source/IIIF.js';
import IIIFInfo from '../src/ol/format/IIIFInfo.js'; import IIIFInfo from '../src/ol/format/IIIFInfo.js';
import Map from '../src/ol/Map.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
const layer = new TileLayer(), const layer = new TileLayer(),
map = new Map({ map = new Map({
layers: [layer], layers: [layer],
target: 'map' target: 'map',
}), }),
notifyDiv = document.getElementById('iiif-notification'), notifyDiv = document.getElementById('iiif-notification'),
urlInput = document.getElementById('imageInfoUrl'), urlInput = document.getElementById('imageInfoUrl'),
displayButton = document.getElementById('display'); displayButton = document.getElementById('display');
function refreshMap(imageInfoUrl) { function refreshMap(imageInfoUrl) {
fetch(imageInfoUrl).then(function(response) { fetch(imageInfoUrl)
response.json().then(function(imageInfo) { .then(function (response) {
response
.json()
.then(function (imageInfo) {
const options = new IIIFInfo(imageInfo).getTileSourceOptions(); const options = new IIIFInfo(imageInfo).getTileSourceOptions();
if (options === undefined || options.version === undefined) { if (options === undefined || options.version === undefined) {
notifyDiv.textContent = 'Data seems to be no valid IIIF image information.'; notifyDiv.textContent =
'Data seems to be no valid IIIF image information.';
return; return;
} }
options.zDirection = -1; options.zDirection = -1;
const iiifTileSource = new IIIF(options); const iiifTileSource = new IIIF(options);
layer.setSource(iiifTileSource); layer.setSource(iiifTileSource);
map.setView(new View({ map.setView(
new View({
resolutions: iiifTileSource.getTileGrid().getResolutions(), resolutions: iiifTileSource.getTileGrid().getResolutions(),
extent: iiifTileSource.getTileGrid().getExtent(), extent: iiifTileSource.getTileGrid().getExtent(),
constrainOnlyCenter: true constrainOnlyCenter: true,
})); })
);
map.getView().fit(iiifTileSource.getTileGrid().getExtent()); map.getView().fit(iiifTileSource.getTileGrid().getExtent());
notifyDiv.textContent = ''; notifyDiv.textContent = '';
}).catch(function(body) { })
.catch(function (body) {
notifyDiv.textContent = 'Could not read image info json. ' + body; notifyDiv.textContent = 'Could not read image info json. ' + body;
}); });
}).catch(function() { })
.catch(function () {
notifyDiv.textContent = 'Could not read data from URL.'; notifyDiv.textContent = 'Could not read data from URL.';
}); });
} }

View File

@@ -1,11 +1,12 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import {fromLonLat} from '../src/ol/proj.js'; import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js'; import XYZ from '../src/ol/source/XYZ.js';
import {fromLonLat} from '../src/ol/proj.js';
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const imagery = new TileLayer({ const imagery = new TileLayer({
@@ -13,8 +14,8 @@ const imagery = new TileLayer({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
maxZoom: 20, maxZoom: 20,
crossOrigin: '' crossOrigin: '',
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -22,52 +23,25 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: fromLonLat([-120, 50]), center: fromLonLat([-120, 50]),
zoom: 6 zoom: 6,
}) }),
}); });
const kernels = { const kernels = {
none: [ none: [0, 0, 0, 0, 1, 0, 0, 0, 0],
0, 0, 0, sharpen: [0, -1, 0, -1, 5, -1, 0, -1, 0],
0, 1, 0, sharpenless: [0, -1, 0, -1, 10, -1, 0, -1, 0],
0, 0, 0 blur: [1, 1, 1, 1, 1, 1, 1, 1, 1],
], shadow: [1, 2, 1, 0, 1, 0, -1, -2, -1],
sharpen: [ emboss: [-2, 1, 0, -1, 1, 1, 0, 1, 2],
0, -1, 0, edge: [0, 1, 0, 1, -4, 1, 0, 1, 0],
-1, 5, -1,
0, -1, 0
],
sharpenless: [
0, -1, 0,
-1, 10, -1,
0, -1, 0
],
blur: [
1, 1, 1,
1, 1, 1,
1, 1, 1
],
shadow: [
1, 2, 1,
0, 1, 0,
-1, -2, -1
],
emboss: [
-2, 1, 0,
-1, 1, 1,
0, 1, 2
],
edge: [
0, 1, 0,
1, -4, 1,
0, 1, 0
]
}; };
function normalize(kernel) { function normalize(kernel) {
const len = kernel.length; const len = kernel.length;
const normal = new Array(len); const normal = new Array(len);
let 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];
} }
@@ -86,7 +60,6 @@ function normalize(kernel) {
const select = document.getElementById('kernel'); const select = document.getElementById('kernel');
let selectedKernel = normalize(kernels[select.value]); let selectedKernel = normalize(kernels[select.value]);
/** /**
* Update the kernel and re-render on change. * Update the kernel and re-render on change.
*/ */
@@ -95,7 +68,6 @@ select.onchange = function() {
map.render(); map.render();
}; };
/** /**
* Apply a filter on "postrender" events. * Apply a filter on "postrender" events.
*/ */
@@ -103,7 +75,6 @@ imagery.on('postrender', function(event) {
convolve(event.context, selectedKernel); convolve(event.context, selectedKernel);
}); });
/** /**
* Apply a convolution kernel to canvas. This works for any size kernel, but * Apply a convolution kernel to canvas. This works for any size kernel, but
* performance starts degrading above 3 x 3. * performance starts degrading above 3 x 3.
@@ -126,14 +97,21 @@ function convolve(context, kernel) {
for (let pixelY = 0; pixelY < height; ++pixelY) { for (let pixelY = 0; pixelY < height; ++pixelY) {
const pixelsAbove = pixelY * width; const pixelsAbove = pixelY * width;
for (let pixelX = 0; pixelX < width; ++pixelX) { for (let pixelX = 0; pixelX < width; ++pixelX) {
let r = 0, g = 0, b = 0, a = 0; let r = 0,
g = 0,
b = 0,
a = 0;
for (let kernelY = 0; kernelY < size; ++kernelY) { for (let kernelY = 0; kernelY < size; ++kernelY) {
for (let kernelX = 0; kernelX < size; ++kernelX) { for (let kernelX = 0; kernelX < size; ++kernelX) {
const weight = kernel[kernelY * size + kernelX]; const weight = kernel[kernelY * size + kernelX];
const neighborY = Math.min( const neighborY = Math.min(
height - 1, Math.max(0, pixelY + kernelY - half)); height - 1,
Math.max(0, pixelY + kernelY - half)
);
const neighborX = Math.min( const neighborX = Math.min(
width - 1, Math.max(0, pixelX + kernelX - half)); width - 1,
Math.max(0, pixelX + kernelX - half)
);
const 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;

View File

@@ -1,8 +1,7 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import ImageLayer from '../src/ol/layer/Image.js'; import ImageLayer from '../src/ol/layer/Image.js';
import ImageWMS from '../src/ol/source/ImageWMS.js'; import ImageWMS from '../src/ol/source/ImageWMS.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
/** /**
* Renders a progress bar. * Renders a progress bar.
@@ -15,7 +14,6 @@ function Progress(el) {
this.loaded = 0; this.loaded = 0;
} }
/** /**
* Increment the count of loading tiles. * Increment the count of loading tiles.
*/ */
@@ -27,7 +25,6 @@ Progress.prototype.addLoading = function() {
this.update(); this.update();
}; };
/** /**
* Increment the count of loaded tiles. * Increment the count of loaded tiles.
*/ */
@@ -39,12 +36,11 @@ Progress.prototype.addLoaded = function() {
}, 100); }, 100);
}; };
/** /**
* Update the progress bar. * Update the progress bar.
*/ */
Progress.prototype.update = function () { Progress.prototype.update = function () {
const 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;
@@ -56,7 +52,6 @@ Progress.prototype.update = function() {
} }
}; };
/** /**
* Show the progress bar. * Show the progress bar.
*/ */
@@ -64,7 +59,6 @@ Progress.prototype.show = function() {
this.el.style.visibility = 'visible'; this.el.style.visibility = 'visible';
}; };
/** /**
* Hide the progress bar. * Hide the progress bar.
*/ */
@@ -80,7 +74,7 @@ const progress = new Progress(document.getElementById('progress'));
const 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',
}); });
source.on('imageloadstart', function () { source.on('imageloadstart', function () {
@@ -95,12 +89,10 @@ source.on('imageloaderror', function() {
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [new ImageLayer({source: source})],
new ImageLayer({source: source})
],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-10997148, 4569099], center: [-10997148, 4569099],
zoom: 4 zoom: 4,
}) }),
}); });

View File

@@ -1,21 +1,20 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import GeoJSON from '../src/ol/format/GeoJSON.js'; import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import VectorImageLayer from '../src/ol/layer/VectorImage.js'; import VectorImageLayer from '../src/ol/layer/VectorImage.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';
import View from '../src/ol/View.js';
import {Fill, Stroke, Style, Text} from '../src/ol/style.js'; import {Fill, Stroke, Style, Text} from '../src/ol/style.js';
const 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)',
}), }),
stroke: new Stroke({ stroke: new Stroke({
color: '#319FD3', color: '#319FD3',
width: 1 width: 1,
}), }),
text: new Text() text: new Text(),
}); });
const map = new Map({ const map = new Map({
@@ -24,19 +23,19 @@ const map = new Map({
imageRatio: 2, imageRatio: 2,
source: new VectorSource({ source: new VectorSource({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new GeoJSON(),
}), }),
style: function (feature) { style: function (feature) {
style.getText().setText(feature.get('name')); style.getText().setText(feature.get('name'));
return style; return style;
} },
}) }),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1,
}) }),
}); });
const featureOverlay = new VectorLayer({ const featureOverlay = new VectorLayer({
@@ -45,18 +44,21 @@ const featureOverlay = new VectorLayer({
style: new Style({ style: new Style({
stroke: new Stroke({ stroke: new Stroke({
color: '#f00', color: '#f00',
width: 1 width: 1,
}), }),
fill: new Fill({ fill: new Fill({
color: 'rgba(255,0,0,0.1)' color: 'rgba(255,0,0,0.1)',
}) }),
}) }),
}); });
let highlight; let highlight;
const displayFeatureInfo = function (pixel) { const displayFeatureInfo = function (pixel) {
map
map.getLayers().item(0).getFeatures(pixel).then(function(features) { .getLayers()
.item(0)
.getFeatures(pixel)
.then(function (features) {
const feature = features.length > 0 ? features[0] : undefined; const feature = features.length > 0 ? features[0] : undefined;
const info = document.getElementById('info'); const info = document.getElementById('info');

View File

@@ -1,18 +1,18 @@
import Stamen from '../src/ol/source/Stamen.js';
import TileLayer from '../src/ol/layer/Tile.js';
import {Circle, Fill, Style} from '../src/ol/style.js';
import {Map, View} from '../src/ol/index.js'; import {Map, View} from '../src/ol/index.js';
import {Point} from '../src/ol/geom.js'; import {Point} from '../src/ol/geom.js';
import TileLayer from '../src/ol/layer/Tile.js';
import Stamen from '../src/ol/source/Stamen.js';
import {Circle, Fill, Style} from '../src/ol/style.js';
import {getVectorContext} from '../src/ol/render.js'; import {getVectorContext} from '../src/ol/render.js';
import {useGeographic} from '../src/ol/proj.js';
import {upAndDown} from '../src/ol/easing.js'; import {upAndDown} from '../src/ol/easing.js';
import {useGeographic} from '../src/ol/proj.js';
useGeographic(); useGeographic();
const layer = new TileLayer({ const layer = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner',
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -20,17 +20,17 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const image = new Circle({ const image = new Circle({
radius: 8, radius: 8,
fill: new Fill({color: 'rgb(255, 153, 0)'}) fill: new Fill({color: 'rgb(255, 153, 0)'}),
}); });
const style = new Style({ const style = new Style({
image: image image: image,
}); });
const n = 1000; const n = 1000;

View File

@@ -1,22 +1,41 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import GeoJSON from '../src/ol/format/GeoJSON.js'; import GeoJSON from '../src/ol/format/GeoJSON.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import LinearRing from '../src/ol/geom/LinearRing.js';
import {fromLonLat} from '../src/ol/proj.js'; import Map from '../src/ol/Map.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';
import LinearRing from '../src/ol/geom/LinearRing.js'; import View from '../src/ol/View.js';
import {Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon} from '../src/ol/geom.js'; import {
LineString,
MultiLineString,
MultiPoint,
MultiPolygon,
Point,
Polygon,
} from '../src/ol/geom.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {fromLonLat} from '../src/ol/proj.js';
const 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) {
const format = new GeoJSON(); const format = new GeoJSON();
const features = format.readFeatures(json, {featureProjection: 'EPSG:3857'}); const features = format.readFeatures(json, {
featureProjection: 'EPSG:3857',
});
const parser = new jsts.io.OL3Parser(); const parser = new jsts.io.OL3Parser();
parser.inject(Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon); parser.inject(
Point,
LineString,
LinearRing,
Polygon,
MultiPoint,
MultiLineString,
MultiPolygon
);
for (let i = 0; i < features.length; i++) { for (let i = 0; i < features.length; i++) {
const feature = features[i]; const feature = features[i];
@@ -33,11 +52,11 @@ fetch('data/geojson/roads-seoul.geojson').then(function(response) {
source.addFeatures(features); source.addFeatures(features);
}); });
const vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: source source: source,
}); });
const rasterLayer = new TileLayer({ const rasterLayer = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const map = new Map({ const map = new Map({
@@ -45,6 +64,6 @@ const map = new Map({
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new View({
center: fromLonLat([126.979293, 37.528787]), center: fromLonLat([126.979293, 37.528787]),
zoom: 15 zoom: 15,
}) }),
}); });

View File

@@ -1,11 +1,10 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import KML from '../src/ol/format/KML.js'; import KML from '../src/ol/format/KML.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import Map from '../src/ol/Map.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';
import View from '../src/ol/View.js';
import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js'; import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const styleCache = {}; const styleCache = {};
const styleFunction = function (feature) { const styleFunction = function (feature) {
@@ -21,13 +20,13 @@ const styleFunction = function(feature) {
image: new CircleStyle({ image: new CircleStyle({
radius: radius, radius: radius,
fill: new Fill({ fill: new Fill({
color: 'rgba(255, 153, 0, 0.4)' color: 'rgba(255, 153, 0, 0.4)',
}), }),
stroke: new Stroke({ stroke: new Stroke({
color: 'rgba(255, 204, 0, 0.2)', color: 'rgba(255, 204, 0, 0.2)',
width: 1 width: 1,
}) }),
}) }),
}); });
styleCache[radius] = style; styleCache[radius] = style;
} }
@@ -38,16 +37,16 @@ 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({
extractStyles: false extractStyles: false,
})
}), }),
style: styleFunction }),
style: styleFunction,
}); });
const raster = new TileLayer({ const raster = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner',
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -55,26 +54,27 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const info = $('#info'); const info = $('#info');
info.tooltip({ info.tooltip({
animation: false, animation: false,
trigger: 'manual' trigger: 'manual',
}); });
const 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',
}); });
const 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');

View File

@@ -1,11 +1,10 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import KML from '../src/ol/format/KML.js'; import KML from '../src/ol/format/KML.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import Map from '../src/ol/Map.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';
import View from '../src/ol/View.js';
import {Fill, Stroke, Style} from '../src/ol/style.js'; import {Fill, Stroke, Style} from '../src/ol/style.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
/* /*
* Compute the style of the feature. Here we want the opacity of polygons to * Compute the style of the feature. Here we want the opacity of polygons to
@@ -24,21 +23,22 @@ const styleFunction = function(feature) {
offset = 60 * hours + minutes; offset = 60 * hours + minutes;
} }
const date = new Date(); const date = new Date();
const local = new Date(date.getTime() + const local = new Date(
(date.getTimezoneOffset() + offset) * 60000); date.getTime() + (date.getTimezoneOffset() + offset) * 60000
);
// offset from local noon (in hours) // offset from local noon (in hours)
let 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;
} }
const 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],
}), }),
stroke: new Stroke({ stroke: new Stroke({
color: '#ffffff' color: '#ffffff',
}) }),
}); });
}; };
@@ -46,16 +46,16 @@ 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({
extractStyles: false extractStyles: false,
})
}), }),
style: styleFunction }),
style: styleFunction,
}); });
const raster = new TileLayer({ const raster = new TileLayer({
source: new Stamen({ source: new Stamen({
layer: 'toner' layer: 'toner',
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -63,26 +63,27 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const info = $('#info'); const info = $('#info');
info.tooltip({ info.tooltip({
animation: false, animation: false,
trigger: 'manual' trigger: 'manual',
}); });
const 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',
}); });
const 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');

View File

@@ -1,27 +1,28 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import KML from '../src/ol/format/KML.js'; import KML from '../src/ol/format/KML.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import Map from '../src/ol/Map.js';
import XYZ from '../src/ol/source/XYZ.js';
import VectorSource from '../src/ol/source/Vector.js'; import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const raster = new TileLayer({ const raster = new TileLayer({
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
maxZoom: 20 maxZoom: 20,
}) }),
}); });
const 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(),
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -30,8 +31,8 @@ const map = new Map({
view: new View({ view: new View({
center: [876970.8463461736, 5859807.853963373], center: [876970.8463461736, 5859807.853963373],
projection: 'EPSG:3857', projection: 'EPSG:3857',
zoom: 10 zoom: 10,
}) }),
}); });
const displayFeatureInfo = function (pixel) { const displayFeatureInfo = function (pixel) {

View File

@@ -1,30 +1,29 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import VectorSource from '../src/ol/source/Vector.js';
import GeoJSON from '../src/ol/format/GeoJSON.js'; import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.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 View from '../src/ol/View.js';
import {Fill, Style} from '../src/ol/style.js'; import {Fill, Style} from '../src/ol/style.js';
import {getVectorContext} from '../src/ol/render.js'; import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {fromLonLat} from '../src/ol/proj.js'; import {fromLonLat} from '../src/ol/proj.js';
import {getVectorContext} from '../src/ol/render.js';
const base = new TileLayer({ const base = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const clipLayer = new VectorLayer({ const clipLayer = new VectorLayer({
style: null, style: null,
source: new VectorSource({ source: new VectorSource({
url: url: './data/geojson/switzerland.geojson',
'./data/geojson/switzerland.geojson', format: new GeoJSON(),
format: new GeoJSON() }),
})
}); });
const style = new Style({ const style = new Style({
fill: new Fill({ fill: new Fill({
color: 'black' color: 'black',
}) }),
}); });
base.on('postrender', function (e) { base.on('postrender', function (e) {
@@ -41,6 +40,6 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: fromLonLat([8.23, 46.86]), center: fromLonLat([8.23, 46.86]),
zoom: 7 zoom: 7,
}) }),
}); });

View File

@@ -1,10 +1,10 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
const osm = new TileLayer({ const osm = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const map = new Map({ const map = new Map({
@@ -12,8 +12,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
osm.on('prerender', function (event) { osm.on('prerender', function (event) {
@@ -21,7 +21,9 @@ osm.on('prerender', function(event) {
// calculate the pixel ratio and rotation of the canvas // calculate the pixel ratio and rotation of the canvas
const matrix = event.inversePixelTransform; const matrix = event.inversePixelTransform;
const canvasPixelRatio = Math.sqrt(matrix[0] * matrix[0] + matrix[1] * matrix[1]); const canvasPixelRatio = Math.sqrt(
matrix[0] * matrix[0] + matrix[1] * matrix[1]
);
const canvasRotation = -Math.atan2(matrix[1], matrix[0]); const canvasRotation = -Math.atan2(matrix[1], matrix[0]);
ctx.save(); ctx.save();
// center the canvas and remove rotation to position clipping // center the canvas and remove rotation to position clipping

View File

@@ -1,8 +1,8 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js';
import {transformExtent} from '../src/ol/proj.js';
import TileJSON from '../src/ol/source/TileJSON.js'; import TileJSON from '../src/ol/source/TileJSON.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {transformExtent} from '../src/ol/proj.js';
function transform(extent) { function transform(extent) {
return transformExtent(extent, 'EPSG:4326', 'EPSG:3857'); return transformExtent(extent, 'EPSG:4326', 'EPSG:3857');
@@ -12,24 +12,29 @@ 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]),
}; };
const key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q'; const key =
'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q';
const base = new TileLayer({ const base = new TileLayer({
source: new TileJSON({ source: new TileJSON({
url: 'https://api.tiles.mapbox.com/v4/mapbox.world-light.json?secure&access_token=' + key, url:
crossOrigin: 'anonymous' 'https://api.tiles.mapbox.com/v4/mapbox.world-light.json?secure&access_token=' +
}) key,
crossOrigin: 'anonymous',
}),
}); });
const 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/v4/mapbox.world-black.json?secure&access_token=' + key, url:
crossOrigin: 'anonymous' 'https://api.tiles.mapbox.com/v4/mapbox.world-black.json?secure&access_token=' +
}) key,
crossOrigin: 'anonymous',
}),
}); });
const map = new Map({ const map = new Map({
@@ -37,8 +42,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1,
}) }),
}); });
for (const key in extents) { for (const key in extents) {

View File

@@ -1,38 +1,44 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import OSM from '../src/ol/source/OSM.js';
import TileJSON from '../src/ol/source/TileJSON.js';
import View from '../src/ol/View.js'; import View from '../src/ol/View.js';
import {Group as LayerGroup, Tile as TileLayer} from '../src/ol/layer.js'; import {Group as LayerGroup, Tile as TileLayer} from '../src/ol/layer.js';
import {fromLonLat} from '../src/ol/proj.js'; import {fromLonLat} from '../src/ol/proj.js';
import OSM from '../src/ol/source/OSM.js';
import TileJSON from '../src/ol/source/TileJSON.js';
const key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q'; const key =
'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q';
const map = new Map({ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new OSM() source: new OSM(),
}), new LayerGroup({ }),
new LayerGroup({
layers: [ layers: [
new TileLayer({ new TileLayer({
source: new TileJSON({ source: new TileJSON({
url: 'https://api.tiles.mapbox.com/v4/mapbox.20110804-hoa-foodinsecurity-3month.json?secure&access_token=' + key, url:
crossOrigin: 'anonymous' 'https://api.tiles.mapbox.com/v4/mapbox.20110804-hoa-foodinsecurity-3month.json?secure&access_token=' +
}) key,
crossOrigin: 'anonymous',
}),
}), }),
new TileLayer({ new TileLayer({
source: new TileJSON({ source: new TileJSON({
url: 'https://api.tiles.mapbox.com/v4/mapbox.world-borders-light.json?secure&access_token=' + key, url:
crossOrigin: 'anonymous' 'https://api.tiles.mapbox.com/v4/mapbox.world-borders-light.json?secure&access_token=' +
}) key,
}) crossOrigin: 'anonymous',
] }),
}) }),
],
}),
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: fromLonLat([37.40570, 8.81566]), center: fromLonLat([37.4057, 8.81566]),
zoom: 4 zoom: 4,
}) }),
}); });
function bindInputs(layerid, layer) { function bindInputs(layerid, layer) {
@@ -57,6 +63,9 @@ map.getLayers().forEach(function(layer, i) {
} }
}); });
$('#layertree li > span').click(function() { $('#layertree li > span')
.click(function () {
$(this).siblings('fieldset').toggle(); $(this).siblings('fieldset').toggle();
}).siblings('fieldset').hide(); })
.siblings('fieldset')
.hide();

View File

@@ -1,12 +1,13 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import {fromLonLat} from '../src/ol/proj.js'; import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js'; import XYZ from '../src/ol/source/XYZ.js';
import {fromLonLat} from '../src/ol/proj.js';
import {getRenderPixel} from '../src/ol/render.js'; import {getRenderPixel} from '../src/ol/render.js';
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const roads = new TileLayer({ const roads = new TileLayer({
@@ -14,16 +15,16 @@ const roads = new TileLayer({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=' + key, url: 'https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=' + key,
tileSize: 512, tileSize: 512,
maxZoom: 22 maxZoom: 22,
}) }),
}); });
const imagery = new TileLayer({ const imagery = new TileLayer({
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
maxZoom: 20 maxZoom: 20,
}) }),
}); });
const container = document.getElementById('map'); const container = document.getElementById('map');
@@ -33,8 +34,8 @@ const map = new Map({
target: container, target: container,
view: new View({ view: new View({
center: fromLonLat([-109, 46.5]), center: fromLonLat([-109, 46.5]),
zoom: 6 zoom: 6,
}) }),
}); });
let radius = 75; let radius = 75;
@@ -71,10 +72,15 @@ imagery.on('prerender', function(event) {
if (mousePosition) { if (mousePosition) {
// only show a circle around the mouse // only show a circle around the mouse
const pixel = getRenderPixel(event, mousePosition); const pixel = getRenderPixel(event, mousePosition);
const offset = getRenderPixel(event, [mousePosition[0] + radius, mousePosition[1]]); const offset = getRenderPixel(event, [
const canvasRadius = Math.sqrt(Math.pow(offset[0] - pixel[0], 2) + Math.pow(offset[1] - pixel[1], 2)); mousePosition[0] + radius,
mousePosition[1],
]);
const canvasRadius = Math.sqrt(
Math.pow(offset[0] - pixel[0], 2) + Math.pow(offset[1] - pixel[1], 2)
);
ctx.arc(pixel[0], pixel[1], canvasRadius, 0, 2 * Math.PI); ctx.arc(pixel[0], pixel[1], canvasRadius, 0, 2 * Math.PI);
ctx.lineWidth = 5 * canvasRadius / radius; ctx.lineWidth = (5 * canvasRadius) / radius;
ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.stroke(); ctx.stroke();
} }

View File

@@ -1,24 +1,25 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js'; import XYZ from '../src/ol/source/XYZ.js';
import {getRenderPixel} from '../src/ol/render.js'; import {getRenderPixel} from '../src/ol/render.js';
const osm = new TileLayer({ const osm = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const aerial = new TileLayer({ const aerial = new TileLayer({
source: new XYZ({ source: new XYZ({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
maxZoom: 20 maxZoom: 20,
}) }),
}); });
const map = new Map({ const map = new Map({
@@ -26,8 +27,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
const swipe = document.getElementById('swipe'); const swipe = document.getElementById('swipe');
@@ -56,6 +57,10 @@ aerial.on('postrender', function(event) {
ctx.restore(); ctx.restore();
}); });
swipe.addEventListener('input', function() { swipe.addEventListener(
'input',
function () {
map.render(); map.render();
}, false); },
false
);

View File

@@ -1,12 +1,11 @@
import Feature from '../src/ol/Feature.js'; import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import Point from '../src/ol/geom/Point.js'; import Point from '../src/ol/geom/Point.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';
import View from '../src/ol/View.js';
import {Fill, RegularShape, Stroke, Style} from '../src/ol/style.js'; import {Fill, RegularShape, Stroke, Style} from '../src/ol/style.js';
const stroke = new Stroke({color: 'black', width: 1}); const stroke = new Stroke({color: 'black', width: 1});
const styles = { const styles = {
@@ -16,8 +15,8 @@ const styles = {
stroke: stroke, stroke: stroke,
points: 4, points: 4,
radius: 80, radius: 80,
angle: Math.PI / 4 angle: Math.PI / 4,
}) }),
}), }),
'triangle': new Style({ 'triangle': new Style({
image: new RegularShape({ image: new RegularShape({
@@ -26,8 +25,8 @@ const styles = {
points: 3, points: 3,
radius: 80, radius: 80,
rotation: Math.PI / 4, rotation: Math.PI / 4,
angle: 0 angle: 0,
}) }),
}), }),
'star': new Style({ 'star': new Style({
image: new RegularShape({ image: new RegularShape({
@@ -36,22 +35,21 @@ const styles = {
points: 5, points: 5,
radius: 80, radius: 80,
radius2: 4, radius2: 4,
angle: 0 angle: 0,
}) }),
}) }),
}; };
function createLayer(coordinates, style, zIndex) { function createLayer(coordinates, style, zIndex) {
const feature = new Feature(new Point(coordinates)); const feature = new Feature(new Point(coordinates));
feature.setStyle(style); feature.setStyle(style);
const source = new VectorSource({ const source = new VectorSource({
features: [feature] features: [feature],
}); });
const vectorLayer = new VectorLayer({ const vectorLayer = new VectorLayer({
source: source source: source,
}); });
vectorLayer.setZIndex(zIndex); vectorLayer.setZIndex(zIndex);
@@ -71,13 +69,12 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 18 zoom: 18,
}) }),
}); });
layer0.setMap(map); layer0.setMap(map);
function bindInputs(id, layer) { function bindInputs(id, layer) {
const idxInput = document.getElementById('idx' + id); const idxInput = document.getElementById('idx' + id);
idxInput.onchange = function () { idxInput.onchange = function () {

View File

@@ -1,9 +1,9 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js'; import XYZ from '../src/ol/source/XYZ.js';
import {transformExtent, fromLonLat} from '../src/ol/proj.js'; import {fromLonLat, transformExtent} from '../src/ol/proj.js';
const mapExtent = [-112.261791, 35.983744, -112.113981, 36.132062]; const mapExtent = [-112.261791, 35.983744, -112.113981, 36.132062];
@@ -12,22 +12,23 @@ const map = new Map({
layers: [ layers: [
new TileLayer({ new TileLayer({
maxZoom: 14, // visible at zoom levels 14 and below maxZoom: 14, // visible at zoom levels 14 and below
source: new OSM() source: new OSM(),
}), }),
new TileLayer({ new TileLayer({
minZoom: 14, // visible at zoom levels above 14 minZoom: 14, // visible at zoom levels above 14
source: new XYZ({ source: new XYZ({
attributions: 'Tiles © USGS, rendered with ' + attributions:
'Tiles © USGS, rendered with ' +
'<a href="http://www.maptiler.com/">MapTiler</a>', '<a href="http://www.maptiler.com/">MapTiler</a>',
url: 'https://tileserver.maptiler.com/grandcanyon/{z}/{x}/{y}.png' url: 'https://tileserver.maptiler.com/grandcanyon/{z}/{x}/{y}.png',
}) }),
}) }),
], ],
view: new View({ view: new View({
center: fromLonLat([-112.18688965, 36.057944835]), center: fromLonLat([-112.18688965, 36.057944835]),
zoom: 15, zoom: 15,
maxZoom: 18, maxZoom: 18,
extent: transformExtent(mapExtent, 'EPSG:4326', 'EPSG:3857'), extent: transformExtent(mapExtent, 'EPSG:4326', 'EPSG:3857'),
constrainOnlyCenter: true constrainOnlyCenter: true,
}) }),
}); });

View File

@@ -1,7 +1,7 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.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';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
const source = new OSM(); const source = new OSM();
@@ -12,8 +12,8 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });
document.getElementById('set-source').onclick = function () { document.getElementById('set-source').onclick = function () {

View File

@@ -1,13 +1,13 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import Point from '../src/ol/geom/Point.js';
import Draw from '../src/ol/interaction/Draw.js'; import Draw from '../src/ol/interaction/Draw.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import Map from '../src/ol/Map.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js'; import Point from '../src/ol/geom/Point.js';
import View from '../src/ol/View.js';
import {Icon, Stroke, Style} from '../src/ol/style.js'; import {Icon, Stroke, Style} from '../src/ol/style.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const raster = new TileLayer({ const raster = new TileLayer({
source: new OSM() source: new OSM(),
}); });
const source = new VectorSource(); const source = new VectorSource();
@@ -19,9 +19,9 @@ const styleFunction = function(feature) {
new Style({ new Style({
stroke: new Stroke({ stroke: new Stroke({
color: '#ffcc33', color: '#ffcc33',
width: 2 width: 2,
}) }),
}) }),
]; ];
geometry.forEachSegment(function (start, end) { geometry.forEachSegment(function (start, end) {
@@ -29,22 +29,24 @@ const styleFunction = function(feature) {
const dy = end[1] - start[1]; const dy = end[1] - start[1];
const 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),
image: new Icon({ image: new Icon({
src: 'data/arrow.png', src: 'data/arrow.png',
anchor: [0.75, 0.5], anchor: [0.75, 0.5],
rotateWithView: true, rotateWithView: true,
rotation: -rotation rotation: -rotation,
}),
}) })
})); );
}); });
return styles; return styles;
}; };
const vector = new VectorLayer({ const vector = new VectorLayer({
source: source, source: source,
style: styleFunction style: styleFunction,
}); });
const map = new Map({ const map = new Map({
@@ -52,11 +54,13 @@ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: [-11000000, 4600000], center: [-11000000, 4600000],
zoom: 4 zoom: 4,
}) }),
}); });
map.addInteraction(new Draw({ map.addInteraction(
new Draw({
source: source, source: source,
type: 'LineString' type: 'LineString',
})); })
);

View File

@@ -1,41 +1,37 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js';
import OSM, {ATTRIBUTION} from '../src/ol/source/OSM.js'; import OSM, {ATTRIBUTION} from '../src/ol/source/OSM.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
const 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>',
ATTRIBUTION ATTRIBUTION,
], ],
url: 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' + url:
'?apikey=0e6fc415256d4fbb9b5166a718591d71' 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' +
}) '?apikey=0e6fc415256d4fbb9b5166a718591d71',
}),
}); });
const 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>',
ATTRIBUTION ATTRIBUTION,
], ],
opaque: false, opaque: false,
url: 'https://tiles.openseamap.org/seamark/{z}/{x}/{y}.png' url: 'https://tiles.openseamap.org/seamark/{z}/{x}/{y}.png',
}) }),
}); });
const map = new Map({ const map = new Map({
layers: [ layers: [openCycleMapLayer, openSeaMapLayer],
openCycleMapLayer,
openSeaMapLayer
],
target: 'map', target: 'map',
view: new View({ view: new View({
maxZoom: 18, maxZoom: 18,
center: [-244780.24508882355, 5986452.183179816], center: [-244780.24508882355, 5986452.183179816],
zoom: 15 zoom: 15,
}) }),
}); });

View File

@@ -1,12 +1,13 @@
import Map from '../src/ol/Map.js'; import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js'; import TileLayer from '../src/ol/layer/Tile.js';
import {fromLonLat} from '../src/ol/proj.js'; import View from '../src/ol/View.js';
import XYZ from '../src/ol/source/XYZ.js'; import XYZ from '../src/ol/source/XYZ.js';
import {fromLonLat} from '../src/ol/proj.js';
import {getRenderPixel} from '../src/ol/render.js'; import {getRenderPixel} from '../src/ol/render.js';
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' + const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'; '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';
const imagery = new TileLayer({ const imagery = new TileLayer({
@@ -14,8 +15,8 @@ const imagery = new TileLayer({
attributions: attributions, attributions: attributions,
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key, url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
maxZoom: 20, maxZoom: 20,
crossOrigin: '' crossOrigin: '',
}) }),
}); });
const container = document.getElementById('map'); const container = document.getElementById('map');
@@ -25,8 +26,8 @@ const map = new Map({
target: container, target: container,
view: new View({ view: new View({
center: fromLonLat([-109, 46.5]), center: fromLonLat([-109, 46.5]),
zoom: 6 zoom: 6,
}) }),
}); });
let radius = 75; let radius = 75;
@@ -59,8 +60,13 @@ container.addEventListener('mouseout', function() {
imagery.on('postrender', function (event) { imagery.on('postrender', function (event) {
if (mousePosition) { if (mousePosition) {
const pixel = getRenderPixel(event, mousePosition); const pixel = getRenderPixel(event, mousePosition);
const offset = getRenderPixel(event, [mousePosition[0] + radius, mousePosition[1]]); const offset = getRenderPixel(event, [
const half = Math.sqrt(Math.pow(offset[0] - pixel[0], 2) + Math.pow(offset[1] - pixel[1], 2)); mousePosition[0] + radius,
mousePosition[1],
]);
const half = Math.sqrt(
Math.pow(offset[0] - pixel[0], 2) + Math.pow(offset[1] - pixel[1], 2)
);
const context = event.context; const context = event.context;
const centerX = pixel[0]; const centerX = pixel[0];
const centerY = pixel[1]; const centerY = pixel[1];
@@ -91,7 +97,7 @@ imagery.on('postrender', function(event) {
} }
context.beginPath(); context.beginPath();
context.arc(centerX, centerY, half, 0, 2 * Math.PI); context.arc(centerX, centerY, half, 0, 2 * Math.PI);
context.lineWidth = 3 * half / radius; context.lineWidth = (3 * half) / radius;
context.strokeStyle = 'rgba(255,255,255,0.5)'; context.strokeStyle = 'rgba(255,255,255,0.5)';
context.putImageData(dest, originX, originY); context.putImageData(dest, originX, originY);
context.stroke(); context.stroke();

View File

@@ -1,11 +1,11 @@
import Map from '../src/ol/Map.js'; import GeoJSON from '../src/ol/format/GeoJSON.js';
import View from '../src/ol/View.js';
import Layer from '../src/ol/layer/Layer.js'; import Layer from '../src/ol/layer/Layer.js';
import {toLonLat, fromLonLat} from '../src/ol/proj.js'; import Map from '../src/ol/Map.js';
import {Stroke, Style} from '../src/ol/style.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';
import GeoJSON from '../src/ol/format/GeoJSON.js'; import View from '../src/ol/View.js';
import {Stroke, Style} from '../src/ol/style.js';
import {fromLonLat, toLonLat} from '../src/ol/proj.js';
const center = [-98.8, 37.9]; const center = [-98.8, 37.9];
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
@@ -23,7 +23,7 @@ const mbMap = new mapboxgl.Map({
keyboard: false, keyboard: false,
pitchWithRotate: false, pitchWithRotate: false,
scrollZoom: false, scrollZoom: false,
touchZoomRotate: false touchZoomRotate: false,
}); });
const mbLayer = new Layer({ const mbLayer = new Layer({
@@ -40,14 +40,14 @@ const mbLayer = new Layer({
// adjust view parameters in mapbox // adjust view parameters in mapbox
const rotation = viewState.rotation; const rotation = viewState.rotation;
if (rotation) { if (rotation) {
mbMap.rotateTo(-rotation * 180 / Math.PI, { mbMap.rotateTo((-rotation * 180) / Math.PI, {
animate: false animate: false,
}); });
} }
mbMap.jumpTo({ mbMap.jumpTo({
center: toLonLat(viewState.center), center: toLonLat(viewState.center),
zoom: viewState.zoom - 1, zoom: viewState.zoom - 1,
animate: false animate: false,
}); });
// cancel the scheduled update & trigger synchronous redraw // cancel the scheduled update & trigger synchronous redraw
@@ -60,29 +60,29 @@ const mbLayer = new Layer({
mbMap._render(); mbMap._render();
return canvas; return canvas;
} },
}); });
const style = new Style({ const style = new Style({
stroke: new Stroke({ stroke: new Stroke({
color: '#319FD3', color: '#319FD3',
width: 2 width: 2,
}) }),
}); });
const 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(),
}), }),
style: style style: style,
}); });
const map = new Map({ const map = new Map({
target: 'map', target: 'map',
view: new View({ view: new View({
center: fromLonLat(center), center: fromLonLat(center),
zoom: 4 zoom: 4,
}), }),
layers: [mbLayer, vectorLayer] layers: [mbLayer, vectorLayer],
}); });

View File

@@ -1,6 +1,9 @@
import apply from 'ol-mapbox-style';
import FullScreen from '../src/ol/control/FullScreen.js'; import FullScreen from '../src/ol/control/FullScreen.js';
import apply from 'ol-mapbox-style';
apply('map', 'https://api.maptiler.com/maps/topo/style.json?key=get_your_own_D6rA4zTHduk6KOKTXzGB').then(function(map) { apply(
'map',
'https://api.maptiler.com/maps/topo/style.json?key=get_your_own_D6rA4zTHduk6KOKTXzGB'
).then(function (map) {
map.addControl(new FullScreen()); map.addControl(new FullScreen());
}); });

View File

@@ -1,14 +1,14 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import MVT from '../src/ol/format/MVT.js'; import MVT from '../src/ol/format/MVT.js';
import VectorTileLayer from '../src/ol/layer/VectorTile.js'; import Map from '../src/ol/Map.js';
import {get as getProjection} from '../src/ol/proj.js';
import VectorTileSource from '../src/ol/source/VectorTile.js';
import {Fill, Icon, Stroke, Style, Text} from '../src/ol/style.js';
import TileGrid from '../src/ol/tilegrid/TileGrid.js'; import TileGrid from '../src/ol/tilegrid/TileGrid.js';
import VectorTileLayer from '../src/ol/layer/VectorTile.js';
import VectorTileSource from '../src/ol/source/VectorTile.js';
import View from '../src/ol/View.js';
import {Fill, Icon, Stroke, Style, Text} from '../src/ol/style.js';
import {get as getProjection} from '../src/ol/proj.js';
const key =
const key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q'; 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q';
// 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.
const resolutions = []; const resolutions = [];
@@ -17,37 +17,43 @@ for (let i = 0; i <= 8; ++i) {
} }
// 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 (
'{z}/{x}/{y}.vector.pbf?access_token=' + key) 'https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' +
'{z}/{x}/{y}.vector.pbf?access_token=' +
key
)
.replace('{z}', String(tileCoord[0] * 2 - 1)) .replace('{z}', String(tileCoord[0] * 2 - 1))
.replace('{x}', String(tileCoord[1])) .replace('{x}', String(tileCoord[1]))
.replace('{y}', String(tileCoord[2])) .replace('{y}', String(tileCoord[2]))
.replace('{a-d}', 'abcd'.substr( .replace(
((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1)); '{a-d}',
'abcd'.substr(((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1)
);
} }
const map = new Map({ const map = new Map({
layers: [ layers: [
new VectorTileLayer({ new VectorTileLayer({
source: new VectorTileSource({ source: new VectorTileSource({
attributions: '© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> ' + attributions:
'© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> ' +
'© <a href="https://www.openstreetmap.org/copyright">' + '© <a href="https://www.openstreetmap.org/copyright">' +
'OpenStreetMap contributors</a>', 'OpenStreetMap contributors</a>',
format: new MVT(), format: new MVT(),
tileGrid: new TileGrid({ tileGrid: new TileGrid({
extent: getProjection('EPSG:3857').getExtent(), extent: getProjection('EPSG:3857').getExtent(),
resolutions: resolutions, resolutions: resolutions,
tileSize: 512 tileSize: 512,
}), }),
tileUrlFunction: tileUrlFunction tileUrlFunction: tileUrlFunction,
}),
style: createMapboxStreetsV6Style(Style, Fill, Stroke, Icon, Text),
}), }),
style: createMapboxStreetsV6Style(Style, Fill, Stroke, Icon, Text)
})
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
minZoom: 1, minZoom: 1,
zoom: 2 zoom: 2,
}) }),
}); });

View File

@@ -1,31 +1,34 @@
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import MVT from '../src/ol/format/MVT.js'; import MVT from '../src/ol/format/MVT.js';
import Map from '../src/ol/Map.js';
import VectorTileLayer from '../src/ol/layer/VectorTile.js'; import VectorTileLayer from '../src/ol/layer/VectorTile.js';
import VectorTileSource from '../src/ol/source/VectorTile.js'; import VectorTileSource from '../src/ol/source/VectorTile.js';
import View from '../src/ol/View.js';
import {Fill, Icon, Stroke, Style, Text} from '../src/ol/style.js'; import {Fill, Icon, Stroke, Style, Text} from '../src/ol/style.js';
const key =
const key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q'; 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q';
const map = new Map({ const map = new Map({
layers: [ layers: [
new VectorTileLayer({ new VectorTileLayer({
declutter: true, declutter: true,
source: new VectorTileSource({ source: new VectorTileSource({
attributions: '© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> ' + attributions:
'© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> ' +
'© <a href="https://www.openstreetmap.org/copyright">' + '© <a href="https://www.openstreetmap.org/copyright">' +
'OpenStreetMap contributors</a>', 'OpenStreetMap contributors</a>',
format: new MVT(), format: new MVT(),
url: 'https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' + url:
'{z}/{x}/{y}.vector.pbf?access_token=' + key 'https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' +
'{z}/{x}/{y}.vector.pbf?access_token=' +
key,
}),
style: createMapboxStreetsV6Style(Style, Fill, Stroke, Icon, Text),
}), }),
style: createMapboxStreetsV6Style(Style, Fill, Stroke, Icon, Text)
})
], ],
target: 'map', target: 'map',
view: new View({ view: new View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2,
}) }),
}); });

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