Compare commits

..

3 Commits

Author SHA1 Message Date
Andreas Hocevar e065c851de Add dist for backport 2017-12-28 12:31:11 +01:00
Andreas Hocevar ed29dde552 Clone backgroundFill and backgroundStroke 2017-12-27 11:51:34 +01:00
Andreas Hocevar 8a73db9331 Apply fill and stroke only when set 2017-12-27 09:31:41 +01:00
994 changed files with 183841 additions and 74499 deletions
-9
View File
@@ -1,9 +0,0 @@
{
"plugins": ["jsdoc-closure"],
"parserOpts": {
"parser": "recast"
},
"generatorOpts": {
"generator": "recast"
}
}
+1
View File
@@ -6,3 +6,4 @@ In order to get your proposed changes merged into the master branch, we ask you
- [ ] It contains one or more small, incremental, logically separate commits, with no merge commits. - [ ] It contains one or more small, incremental, logically separate commits, with no merge commits.
- [ ] I have used clear commit messages. - [ ] I have used clear commit messages.
- [ ] Existing tests pass for me locally & I have added or updated tests for new or changed functionality. - [ ] Existing tests pass for me locally & I have added or updated tests for new or changed functionality.
- [ ] The work herein is covered by a valid [Contributor License Agreement (CLA)](https://github.com/openlayers/cla).
-1
View File
@@ -2,4 +2,3 @@
/coverage/ /coverage/
/dist/ /dist/
/node_modules/ /node_modules/
src/index.js
+1
View File
@@ -0,0 +1 @@
/build/
+5
View File
@@ -1,9 +1,14 @@
sudo: false
language: node_js language: node_js
node_js: node_js:
- '8' - '8'
cache: cache:
directories: directories:
- node_modules - node_modules
before_script:
- rm src/ol/renderer/webgl/*shader.js
- rm src/ol/renderer/webgl/*shader/locations.js
script: make ci
after_success: after_success:
- cat coverage/lcov.info | coveralls - cat coverage/lcov.info | coveralls
branches: branches:
+96 -1
View File
@@ -31,7 +31,12 @@ This page describes what you need to know to contribute code to OpenLayers as a
## Contributor License Agreement ## Contributor License Agreement
Your contribution will be under our [license](https://raw.githubusercontent.com/openlayers/openlayers/master/LICENSE.md) as per [GitHub's terms of service](https://help.github.com/articles/github-terms-of-service/#6-contributions-under-repository-license). Before accepting a contribution, we ask that you provide us a Contributor
License Agreement. If you are making your contribution as part of work for
your employer, please follow the guidelines on submitting a [Corporate
Contributor License Agreement](https://raw.github.com/openlayers/cla/master/ccla.txt). If you are
making your contribution as an individual, you can submit a digital [Individual
Contributor License Agreement](https://docs.google.com/spreadsheet/viewform?formkey=dGNNVUJEMXF2dERTU0FXM3JjNVBQblE6MQ).
## Pull request guidelines ## Pull request guidelines
@@ -55,6 +60,66 @@ Your pull request must:
* Be possible to merge automatically. * Be possible to merge automatically.
### The `check` build target
It is strongly recommended that you run
$ make check
before every commit. This will catch many problems quickly, and it is much
faster than waiting for the Travis CI integration tests to run.
The `check` build target runs a number of quick tests on your code. These
include:
* Lint
* Compile
* Tests
### Follow OpenLayers's coding style
OpenLayers follows [Google's JavaScript Style
Guide](https://google.github.io/styleguide/javascriptguide.xml).
This is checked using [ESLint](http://eslint.org/), you
can run the linter locally on your machine before committing using the `lint`
target:
$ make lint
In addition to fixing problems identified by the linter, please also follow the
style of the existing OpenLayers code, which includes:
* Always wrap the body of `for`, `if`, and `while` statements in braces.
* Class methods should be in alphabetical order.
* `var` declarations should not span multiple lines. If you cannot fit all
the declarations in a single line, then start a new `var` declaration on a
new line. Within a single line, variables should be declared in
alphabetical order.
* Do not use assignments inside expressions.
* Use uppercase for `@const` variables.
### Configure your editor
If possible, configure your editor to follow the coding conventions of the
library. A `.editorconfig` file is included at the root of the repository that
can be used to configure whitespace and charset handling in your editor. See
that file for a description of the conventions. The [EditorConfig](
http://editorconfig.org/#download) site links to plugins for various editors.
### Pass the integration tests run automatically by the Travis CI system
The integration tests contain a number of automated checks to ensure that the
code follows the OpenLayers style and does not break tests or examples. You
can run the integration tests locally using the `ci` target:
$ make ci
### Address a single issue or add a single item of functionality ### Address a single issue or add a single item of functionality
Please submit separate pull requests for separate issues. This allows each to Please submit separate pull requests for separate issues. This allows each to
@@ -108,3 +173,33 @@ Occasionally other changes to `master` might mean that your pull request cannot
be merged automatically. In this case you may need to rebase your branch on a be merged automatically. In this case you may need to rebase your branch on a
more recent `master`, resolve any conflicts, and `git push --force` to update more recent `master`, resolve any conflicts, and `git push --force` to update
your branch so that it can be merged automatically. your branch so that it can be merged automatically.
## Building on Windows
Most developers build on Linux. Building on Windows is possible under Cygwin.
When installing Cygwin from https://www.cygwin.com/, include the developer
tools to get GNU make.
First (before npm install), to avoid file permission problems between Windows
and Cygwin, edit Cygwin's /etc/fstab file to disable ACLs like this
`none /cygdrive cygdrive binary,noacl,posix=0,user 0 0`
Python is normally installed with Cygwin so need not be installed separately.
By default Cygwin will use its own version of Python rather than Window's,
so the Python modules should be installed for Cygwin's Python.
The build targets `check-deps`, `serve`, `lint`, `build`, `test`, `check` and
`host-examples` described above should all work. `host-examples` takes quite a
while to run. If a target does not run properly first time, try it again.
Currently, Firefox fails to run http://localhost:3000/build/examples
from make serve, but Chrome and Internet Explorer will.
Microsoft Visual Studio's javascript debugger may be used to debug the
build/hosted/your-branch/examples. It will be convenient to set
build/hosted/your-branch/examples/index.html as the startup page.
Your OpenLayers source tree need not be under the Cygwin root.
if you checkout to c:/openlayers then you can build under Cygwin at /cygdrive/c/openlayers .
However, keep the path to the OpenLayers files short otherwise you may see
`ENAMETOOLONG` errors.
+89 -7
View File
@@ -15,32 +15,103 @@ pull requests will not be merged.
The minimum requirements are: The minimum requirements are:
* GNU Make
* Git * Git
* [Node.js](http://nodejs.org/) (version 8 and above) * [Node.js](http://nodejs.org/) (version 8 and above)
* Python 2.6 or 2.7
* Java 7 (JRE and JDK)
The executables `git` and `node` should be in your `PATH`. The executables `git`, `node`, and `java` should be in your `PATH`.
You can check your configuration by running:
$ make check-deps
To install the Node.js dependencies run To install the Node.js dependencies run
$ npm install $ npm install
## Working with the build tool
As an OpenLayers developer you will use `make` to run build targets defined in the
`Makefile` located at the root of the repository. The `Makefile` includes
targets for running the linter, the compiler, the tests, etc.
The usage of `make` is as follows:
$ make <target>
where `<target>` is the name of the build target you want to execute. For
example:
$ make test
The main build targets are `serve`, `lint`, `build`, `test`, and `check`. The
latter is a meta-target that basically runs `lint`, `build`, and `test`.
The `serve` target starts a node-based web server, which we will refer to as the *dev server*. You'll need to start that server for running the examples and the tests in a browser. More information on that further down.
Other targets include `apidoc` and `ci`. The latter is the target used on Travis CI. See OpenLayers's [Travis configuration file](https://github.com/openlayers/openlayers/blob/master/.travis.yml).
## Running the `check` target
The `check` target is to be run before pushing code to GitHub and opening pull
requests. Branches that don't pass `check` won't pass the integration tests,
and have therefore no chance of being merged into `master`.
To run the `check` target:
$ make check
If you want to run the full suite of integration tests, see "Running the integration
tests" below.
## Running examples ## Running examples
To run the examples you first need to start the dev server: To run the examples you first need to start the dev server:
$ npm run serve-examples $ make serve
Then, load <http://localhost:5000/> in your browser. Then, just point your browser <http://localhost:3000/build/examples> in your browser. For example <http://localhost:3000/build/examples/side-by-side.html>.
Run examples against the `ol.js` standalone build:
The examples can also be run against the `ol.js` standalone build, just like
the examples [hosted](https://openlayers.org/en/master/examples/) on GitHub.
Start by executing the `host-examples` build target:
$ make host-examples
After running `host-examples` you can now open the examples index page in the browser: <http://localhost:3000/build/hosted/master/examples/>. (This assumes that you still have the dev server running.)
Append `?mode=raw` to make the example work in full debug mode. In raw mode the OpenLayers and Closure Library scripts are loaded individually by the Closure Library's `base.js` script (which the example page loads and executes before any other script).
## Running tests ## Running tests
To run the tests once: To run the tests in a browser start the dev server (`make serve`) and open <http://localhost:3000/test/index.html> in the browser.
$ npm test To run the tests on the console (headless testing with PhantomJS) use the `test` target:
To run the tests continuously during development: $ make test
$ npm run karma See also the test-specific [README](../master/test/README.md).
## Running the integration tests
When you submit a pull request the [Travis continuous integration
server](https://travis-ci.org/) will run a full suite of tests, including
building all versions of the library and checking that all of the examples
work. You will receive an email with the results, and the status will be
displayed in the pull request.
To run the full suite of integration tests use the `ci` target:
$ make ci
Running the full suite of integration tests currently takes 5-10 minutes.
This makes sure that your commit won't break the build. It also runs JSDoc3 to
make sure that there are no invalid API doc directives.
## Adding examples ## Adding examples
@@ -52,3 +123,14 @@ implies creating two or three files in this directory, an `.html` file, a `.js`
file, and, optionally, a `.css` file. file, and, optionally, a `.css` file.
You can use `simple.js` and `simple.html` as templates for new examples. You can use `simple.js` and `simple.html` as templates for new examples.
### Use of the `goog` namespace in examples
Short story: the OpenLayers examples should not use the `goog` namespace, except
for `goog.require`.
Longer story: we want that the OpenLayers examples work in multiple modes, with the
standalone lib (which has implications of the symbols and properties we
export), and compiled together with the OpenLayers library.
Compiling the examples together with the library makes it mandatory to declare dependencies with `goog.require` statements.
+271 -4
View File
@@ -1,13 +1,280 @@
OS := $(shell uname)
BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
SRC_GLSL := $(shell find src -type f -name '*.glsl') SRC_GLSL := $(shell find src -type f -name '*.glsl')
SRC_SHADER_JS := $(patsubst %shader.glsl,%shader.js,$(SRC_GLSL)) SRC_SHADER_JS := $(patsubst %shader.glsl,%shader.js,$(SRC_GLSL))
SRC_SHADERLOCATIONS_JS := $(patsubst %shader.glsl,%shader/Locations.js,$(SRC_GLSL)) SRC_SHADERLOCATIONS_JS := $(patsubst %shader.glsl,%shader/locations.js,$(SRC_GLSL))
SRC_JS := $(filter-out $(SRC_SHADER_JS) $(SRC_SHADERLOCATIONS_JS),$(shell find src -name '*.js'))
SRC_JSDOC = $(shell find src -type f -name '*.jsdoc')
EXAMPLES := $(shell find examples -type f)
EXAMPLES_HTML := $(filter-out examples/index.html,$(shell find examples -maxdepth 1 -type f -name '*.html'))
EXAMPLES_JS := $(patsubst %.html,%.js,$(EXAMPLES_HTML))
BUILD_EXAMPLES := $(subst examples,build/examples,$(EXAMPLES)) build/examples/index.js
BUILD_HOSTED := build/hosted/$(BRANCH)
BUILD_HOSTED_EXAMPLES := $(addprefix $(BUILD_HOSTED)/,$(EXAMPLES))
BUILD_HOSTED_EXAMPLES_JS := $(addprefix $(BUILD_HOSTED)/,$(EXAMPLES_JS))
UNPHANTOMABLE_EXAMPLES = examples/shaded-relief.html examples/raster.html examples/region-growing.html examples/color-manipulation.html
CHECK_EXAMPLE_TIMESTAMPS = $(patsubst examples/%.html,build/timestamps/check-%-timestamp,$(filter-out $(UNPHANTOMABLE_EXAMPLES),$(EXAMPLES_HTML)))
TASKS_JS := $(shell find tasks -name '*.js')
ifeq (CYGWIN,$(findstring CYGWIN,$(OS)))
CLOSURE_LIB = $(shell cygpath -u $(shell node -e 'process.stdout.write(require("closure-util").getLibraryPath())'))
else
CLOSURE_LIB = $(shell node -e 'process.stdout.write(require("closure-util").getLibraryPath())')
endif
ifeq ($(OS),Darwin)
STAT_COMPRESSED = stat -f ' compressed: %z bytes'
STAT_UNCOMPRESSED = stat -f 'uncompressed: %z bytes'
else
STAT_COMPRESSED = stat -c ' compressed: %s bytes'
STAT_UNCOMPRESSED = stat -c 'uncompressed: %s bytes'
endif
.PHONY: default
default: help
.PHONY: help
help:
@echo
@echo "The most common targets are:"
@echo
@echo "- install Install node dependencies"
@echo "- serve Start dev server for running examples and tests"
@echo "- test Run unit tests in the console"
@echo "- check Perform a number of checks on the code"
@echo "- clean Remove generated files"
@echo "- help Display this help message"
@echo
@echo "Other less frequently used targets are:"
@echo
@echo "- build Build ol.js, ol-debug.js, ol.js.map and ol.css"
@echo "- ci Run the full continuous integration process"
@echo "- apidoc Build the API documentation using JSDoc"
@echo "- cleanall Remove all the build artefacts"
@echo "- check-deps Check if the required dependencies are installed"
@echo
.PHONY: apidoc
apidoc: build/timestamps/jsdoc-$(BRANCH)-timestamp
.PHONY: build
build: build/ol.css build/ol.js build/ol-debug.js build/ol.js.map
.PHONY: check
check: build/ol.js test
.PHONY: check-examples
check-examples: $(CHECK_EXAMPLE_TIMESTAMPS)
.PHONY: check-deps
check-deps: EXECUTABLES = git node python java
check-deps:
@for exe in $(EXECUTABLES) ;\
do \
which $${exe} > /dev/null && \
echo "Program $${exe} OK" || \
echo "Program $${exe} MISSING!" ;\
done ;\
.PHONY: ci
ci: build test package compile-examples check-examples apidoc
.PHONY: compile-examples
compile-examples: build/compiled-examples/all.combined.js
.PHONY: clean
clean:
rm -f build/timestamps/check-*-timestamp
rm -f build/ol.css
rm -f build/ol.js
rm -f build/ol.js.map
rm -f build/ol-debug.js
rm -rf build/examples
rm -rf build/compiled-examples
rm -rf build/package
rm -rf $(BUILD_HOSTED)
.PHONY: cleanall
cleanall:
rm -rf build
.PHONY: css
css: build/ol.css
.PHONY: examples
examples: $(BUILD_EXAMPLES)
.PHONY: install
install: build/timestamps/node-modules-timestamp
.PHONY: npm-install
npm-install: build/timestamps/node-modules-timestamp
.PHONY: shaders .PHONY: shaders
shaders: $(SRC_SHADER_JS) $(SRC_SHADERLOCATIONS_JS) shaders: $(SRC_SHADER_JS $(SRC_SHADERLOCATIONS_JS)
%shader.js: %shader.glsl src/ol/webgl/shader.mustache tasks/glslunit.js .PHONY: serve
serve:
node tasks/serve.js
.PHONY: test
test: build/timestamps/node-modules-timestamp
npm test
.PHONY: host-examples
host-examples: $(BUILD_HOSTED_EXAMPLES) \
$(BUILD_HOSTED)/build/ol.js \
$(BUILD_HOSTED)/build/ol-debug.js \
$(BUILD_HOSTED)/css/ol.css \
$(BUILD_HOSTED)/examples/loader.js \
$(BUILD_HOSTED)/examples/index.js \
$(BUILD_HOSTED)/build/ol-deps.js
.PHONY: host-libraries
host-libraries: build/timestamps/node-modules-timestamp
@rm -rf $(BUILD_HOSTED)/closure-library
@mkdir -p $(BUILD_HOSTED)/closure-library
@cp -r $(CLOSURE_LIB)/* $(BUILD_HOSTED)/closure-library/
@rm -rf $(BUILD_HOSTED)/ol/ol
@mkdir -p $(BUILD_HOSTED)/ol/ol
@cp -r src/ol/* $(BUILD_HOSTED)/ol/ol/
@rm -rf $(BUILD_HOSTED)/ol.ext
@mkdir -p $(BUILD_HOSTED)/ol.ext
@cp -r build/ol.ext/* $(BUILD_HOSTED)/ol.ext/
$(BUILD_EXAMPLES): $(EXAMPLES) package.json
@mkdir -p $(@D)
@node tasks/build-examples.js
build/timestamps/check-%-timestamp: $(BUILD_HOSTED)/examples/%.html \
$(BUILD_HOSTED)/examples/%.js \
$(filter $(BUILD_HOSTED)/examples/resources/%,$(BUILD_HOSTED_EXAMPLES)) \
$(filter $(BUILD_HOSTED)/examples/data/%,$(BUILD_HOSTED_EXAMPLES)) \
$(BUILD_HOSTED)/examples/loader.js \
$(BUILD_HOSTED)/build/ol.js \
$(BUILD_HOSTED)/css/ol.css
@mkdir -p $(@D)
node tasks/check-example.js $<
@touch $@
build/compiled-examples/all.js: $(EXAMPLES_JS)
@mkdir -p $(@D)
@python bin/combine-examples.py $^ > $@
build/compiled-examples/all.combined.js: config/examples-all.json build/compiled-examples/all.js \
$(SRC_JS) $(SRC_SHADER_JS) $(SRC_SHADERLOCATIONS_JS) \
build/timestamps/node-modules-timestamp
@mkdir -p $(@D)
node tasks/build.js $< $@
build/compiled-examples/%.json: config/example.json build/examples/%.js \
build/timestamps/node-modules-timestamp
@mkdir -p $(@D)
@sed -e 's|{{id}}|$*|' $< > $@
build/compiled-examples/%.combined.js: build/compiled-examples/%.json \
$(SRC_JS) $(SRC_SHADER_JS) $(SRC_SHADERLOCATIONS_JS)\
build/timestamps/node-modules-timestamp
@mkdir -p $(@D)
node tasks/build.js $< $@
build/timestamps/jsdoc-$(BRANCH)-timestamp: config/jsdoc/api/index.md \
config/jsdoc/api/conf.json $(SRC_JS) \
$(SRC_SHADER_JS) $(SRC_SHADERLOCATIONS_JS) \
$(shell find config/jsdoc/api/template -type f) \
build/timestamps/node-modules-timestamp
@mkdir -p $(@D)
@rm -rf $(BUILD_HOSTED)/apidoc
./node_modules/.bin/jsdoc config/jsdoc/api/index.md -c config/jsdoc/api/conf.json --package package.json -d $(BUILD_HOSTED)/apidoc
@touch $@
$(BUILD_HOSTED_EXAMPLES_JS): $(BUILD_HOSTED)/examples/%.js: build/examples/%.js
@mkdir -p $(@D)
@python bin/split-example.py $< $(@D)
$(BUILD_HOSTED)/examples/loader.js: bin/loader_hosted_examples.js
@mkdir -p $(@D)
@cp $< $@
$(BUILD_HOSTED)/examples/%: build/examples/%
@mkdir -p $(@D)
@cp $< $@
$(BUILD_HOSTED)/build/ol.js: build/ol.js
@mkdir -p $(@D)
@cp $< $@
$(BUILD_HOSTED)/build/ol-debug.js: build/ol-debug.js
@mkdir -p $(@D)
@cp $< $@
$(BUILD_HOSTED)/css/ol.css: build/ol.css
@mkdir -p $(@D)
@cp $< $@
$(BUILD_HOSTED)/build/ol-deps.js: host-libraries
@mkdir -p $(@D)
@python $(CLOSURE_LIB)/closure/bin/build/depswriter.py \
--root_with_prefix "src ../../../ol" \
--root_with_prefix "build/ol.ext ../../../ol.ext" \
--root $(BUILD_HOSTED)/closure-library/closure/goog \
--root_with_prefix "$(BUILD_HOSTED)/closure-library/third_party ../../third_party" \
--output_file $@
build/timestamps/node-modules-timestamp: package.json
@mkdir -p $(@D)
npm install
@touch $@
build/ol.css: css/ol.css build/timestamps/node-modules-timestamp
@mkdir -p $(@D)
@echo "Running cleancss..."
@./node_modules/.bin/cleancss $< > $@
build/ol.js: config/ol.json $(SRC_JS) $(SRC_SHADER_JS) $(SRC_SHADERLOCATIONS_JS) \
build/timestamps/node-modules-timestamp
@mkdir -p $(@D)
node tasks/build.js $< $@
@$(STAT_UNCOMPRESSED) $@
@cp $@ /tmp/
@gzip /tmp/ol.js
@$(STAT_COMPRESSED) /tmp/ol.js.gz
@rm /tmp/ol.js.gz
build/ol.js.map: config/ol.json $(SRC_JS) $(SRC_SHADER_JS) $(SRC_SHADERLOCATIONS_JS) \
build/timestamps/node-modules-timestamp
@mkdir -p $(@D)
node tasks/build.js $< $@
build/ol-debug.js: config/ol-debug.json $(SRC_JS) $(SRC_SHADER_JS) $(SRC_SHADERLOCATIONS_JS) \
build/timestamps/node-modules-timestamp
@mkdir -p $(@D)
node tasks/build.js $< $@
@$(STAT_UNCOMPRESSED) $@
@cp $@ /tmp/
@gzip /tmp/ol-debug.js
@$(STAT_COMPRESSED) /tmp/ol-debug.js.gz
@rm /tmp/ol-debug.js.gz
%shader.js: %shader.glsl src/ol/webgl/shader.mustache tasks/glslunit.js build/timestamps/node-modules-timestamp
@node tasks/glslunit.js --input $< | ./node_modules/.bin/mustache - src/ol/webgl/shader.mustache > $@ @node tasks/glslunit.js --input $< | ./node_modules/.bin/mustache - src/ol/webgl/shader.mustache > $@
%shader/Locations.js: %shader.glsl src/ol/webgl/shaderlocations.mustache tasks/glslunit.js %shader/locations.js: %shader.glsl src/ol/webgl/shaderlocations.mustache tasks/glslunit.js build/timestamps/node-modules-timestamp
@mkdir -p $(@D) @mkdir -p $(@D)
@node tasks/glslunit.js --input $< | ./node_modules/.bin/mustache - src/ol/webgl/shaderlocations.mustache > $@ @node tasks/glslunit.js --input $< | ./node_modules/.bin/mustache - src/ol/webgl/shaderlocations.mustache > $@
.PHONY: package
package:
@rm -rf build/package
@cp -r package build
@cd ./src && cp -r ol/* ../build/package
@rm build/package/typedefs.js
@cp css/ol.css build/package
./node_modules/.bin/jscodeshift --transform transforms/module.js build/package
npm run lint-package
-1
View File
@@ -4,7 +4,6 @@
[![Greenkeeper badge](https://badges.greenkeeper.io/openlayers/openlayers.svg)](https://greenkeeper.io/) [![Greenkeeper badge](https://badges.greenkeeper.io/openlayers/openlayers.svg)](https://greenkeeper.io/)
[![Coverage Status](https://coveralls.io/repos/github/openlayers/openlayers/badge.svg?branch=master)](https://coveralls.io/github/openlayers/openlayers?branch=master) [![Coverage Status](https://coveralls.io/repos/github/openlayers/openlayers/badge.svg?branch=master)](https://coveralls.io/github/openlayers/openlayers?branch=master)
[![OSGeo Project](https://img.shields.io/badge/OSGeo-Project-brightgreen.svg)](http://osgeo.org/) [![OSGeo Project](https://img.shields.io/badge/OSGeo-Project-brightgreen.svg)](http://osgeo.org/)
[![jsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/openlayers/badge?style=rounded)](https://www.jsdelivr.com/package/npm/openlayers)
[OpenLayers](https://openlayers.org/) is a high-performance, feature-packed library for creating interactive maps on the web. It can display map tiles, vector data and markers loaded from any source on any web page. OpenLayers has been developed to further the use of geographic information of all kinds. It is completely free, Open Source JavaScript, released under the 2-clause BSD License (also known as the FreeBSD). [OpenLayers](https://openlayers.org/) is a high-performance, feature-packed library for creating interactive maps on the web. It can display map tiles, vector data and markers loaded from any source on any web page. OpenLayers has been developed to further the use of geographic information of all kinds. It is completely free, Open Source JavaScript, released under the 2-clause BSD License (also known as the FreeBSD).
+33
View File
@@ -0,0 +1,33 @@
//
// A PhantomJS script used to check that the hosted examples load
// without errors. This script is executed by the build tool's
// check-examples target.
//
var args = require('system').args;
if (args.length != 2) {
phantom.exit(2);
}
var examplePath = args[1];
var page = require('webpage').create();
page.onError = function(msg, trace) {
var msgStack = ['JavaScript ERROR: ' + msg];
if (trace) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
phantom.exit(1);
};
page.open(examplePath, function(s) {
var exitCode = 0;
if (s != 'success') {
exitCode = 1;
console.error('PAGE LOAD ERROR');
}
phantom.exit(exitCode);
});
page.onConsoleMessage = function(msg) {
console.log('console:', msg);
};
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/python
import re
import sys
def main(argv):
examples = {}
requires = set()
for filename in argv[1:]:
lines = open(filename, 'rU').readlines()
if len(lines) > 0 and lines[0].startswith('// NOCOMPILE'):
continue
requires.update(line for line in lines if line.startswith('goog.require'))
examples[filename] = [line for line in lines if not line.startswith('goog.require')]
for require in sorted(requires):
sys.stdout.write(require)
for filename in sorted(examples.keys()):
sys.stdout.write('// ' + filename + '\n')
sys.stdout.write('(function(){\n')
for line in examples[filename]:
sys.stdout.write(line)
sys.stdout.write('})();\n')
if __name__ == '__main__':
sys.exit(main(sys.argv))
+180
View File
@@ -0,0 +1,180 @@
/**
* This script is supposed to be executed via phantomjs. It will generate
* screenshots of the html files in the directory specified by a commandline
* option when these files are served through a webserver which can also be
* specified. The screenshots will be in the current working directory.
*
* Example usage:
*
* user@host:~/openlayers/bin $ phantomjs example-screenshot.js \
* http://localhost:8000/openlayers/examples/ \
* ../examples
*
* The above command will generate `*.png` files in `examples/` for all html
* files that are served through `http://localhost:8000/openlayers/examples/`.
*
* So if there is a file `my-humpty-example.html` inside of the relative folder
* `../examples/` which is being served through the webserver so that
* `http://localhost:8000/openlayers/examples/my-humpty-example.html` is a valid and
* reachable URL, this script will generate a screenshot and store it as
* `my-humpty-example.html.png`.
*
* The query string `?mode=raw` will be appended to the generated URL.
*
* Known limitations:
*
* As phantomjs doesn't support WebGL (see e.g.
* https://github.com/ariya/phantomjs/wiki/Supported-Web-Standards and
* http://code.google.com/p/phantomjs/issues/detail?id=273) This won't render
* OpenLayers maps rendered through the webglrenderer.
*
* In parts based upon this gist: https://gist.github.com/crazy4groovy/3160121
*/
(function() { // global closure
var page = require('webpage').create(), // imports
fs = require('fs'),
system = require('system'),
// arguments
baseExamplesUrl = system.args[1],
exampleDir = system.args[2],
// various settings
ignoreFiles = [
'index.html'
],
intervalMillisecs = 25,
renderMillisecs = 2000,
// basic variables
curDir = fs.workingDirectory,
exampleDirList = fs.list(exampleDir),
pageindex = 0,
fileName = '',
htmlFiles = [],
lenHtmlFiles = 0,
loadInProgress = false;
// simple object with helper functions
var util = {
/**
* Returns the basename of a file given a path.
*/
baseName: function(path) {
var parts = path.split(fs.separator);
return parts[parts.length - 1];
},
/**
* Super basic test whether a file can be considered a HTML-file.
*/
isHtmlFile: function(filename) {
return (/\.html?$/).test(filename);
},
/**
* Appends a slash to given string if it isn't there already.
*/
appendSlash: function(str) {
return ((/\/$/).test(str)) ? str : str + '/';
},
/**
* Generates an URL out of given baseurl and path.
*/
buildUrl: function(baseurl, path) {
var name = util.baseName(path),
mode = 'raw';
return util.appendSlash(baseurl) + name + '?mode=' + mode;
},
/**
* Simple progressbar logger that uses our globals pageindex & lenHtmlFiles.
*/
logProgress: function() {
var doneSymbol = '-',
todoSymbol = ' ',
currentSymbol = '>',
barStrLeft = '[',
barStrRight = ']',
progresStep = 5, // one doneSymbol equals this percentage
totalSteps = Math.round(100 / progresStep),
ratio = (lenHtmlFiles === 0) ? 0 : (pageindex / lenHtmlFiles),
percent = (ratio === 0) ? 0 : ratio * 100,
normalizedNumDone = Math.floor(ratio * totalSteps),
normalizedNumTodo = totalSteps - normalizedNumDone,
progressLine = '',
i = 0;
// the progress bar
progressLine += barStrLeft;
for (; i < normalizedNumDone; i++) {
progressLine += doneSymbol;
}
for (i = 0; i < normalizedNumTodo; i++) {
progressLine += (i === 0) ? currentSymbol : todoSymbol;
}
progressLine += barStrRight;
// the percentage information
// pad if necessary
if (percent < 10) {
progressLine += ' ';
} else if (percent < 100) {
progressLine += ' ';
}
progressLine += ' ' + percent.toFixed(1) + ' % done';
// additional information
if (fileName !== '') {
progressLine += ', ' + util.baseName(fileName) + '';
}
console.log(progressLine);
}
};
// iterate over all files in examples directory
// and find the HTML files.
for (var i = 0; i < exampleDirList.length; i++) {
var fullpath = exampleDir + fs.separator + exampleDirList[i];
if (fs.isFile(fullpath) && util.isHtmlFile(fullpath) &&
ignoreFiles.indexOf(util.baseName(fullpath)) === -1) {
//TODO: make this more async (i.e. pop on/off stack WHILE rending pages)
htmlFiles.push(fullpath);
}
}
lenHtmlFiles = htmlFiles.length;
console.log('Capturing ' + lenHtmlFiles + ' example screenshots.');
// The main interval function that is executed regularly and renders a
// page to a file
var interval = setInterval(function() {
if (!loadInProgress && pageindex < lenHtmlFiles) {
util.logProgress();
fileName = htmlFiles[pageindex];
page.viewportSize = { width: 800, height: 600 };
page.clipRect = {
top: 0,
left: 0,
width: page.viewportSize.width,
height: page.viewportSize.height
};
page.open(util.buildUrl(baseExamplesUrl, htmlFiles[pageindex]));
}
if (pageindex == lenHtmlFiles) {
util.logProgress();
console.log(lenHtmlFiles + ' screenshots captured.');
phantom.exit();
}
}, intervalMillisecs);
// set loadInProgress flag so we only process one image at time.
page.onLoadStarted = function() {
loadInProgress = true;
};
// When the page is loaded, render it to an image
page.onLoadFinished = function() {
var dest = exampleDir + fs.separator + util.baseName(fileName) + '.png';
window.setTimeout(function() {
loadInProgress = false;
page.render(dest); // actually render the page.
pageindex++;
}, renderMillisecs);
};
})(); // eof global closure
+69
View File
@@ -0,0 +1,69 @@
/**
* This loader is used for the hosted examples. It is used in place of the
* development loader (examples/loader.js).
*
* The loader loads ol.js and the example's script in "production" mode; it
* loads Closure Library's base.js, ol-deps.js, the example's "goog.require"
* script, and the example's script in "development" mode.
*
* The ol.js and ol-deps.js scripts are built using OpenLayers's Makefile. They are
* located in the ../build/ directory, relative to this script.
*
* The script must be named loader.js.
*
* Usage:
*
* <script src="../loader.js?id=my-demo"></script>
*/
(function() {
var i, pair;
var href = window.location.href, start, end, paramsString, pairs,
pageParams = {};
if (href.indexOf('?') > 0) {
start = href.indexOf('?') + 1;
end = href.indexOf('#') > 0 ? href.indexOf('#') : href.length;
paramsString = href.substring(start, end);
pairs = paramsString.split(/[&;]/);
for (i = 0; i < pairs.length; ++i) {
pair = pairs[i].split('=');
if (pair[0]) {
pageParams[decodeURIComponent(pair[0])] =
decodeURIComponent(pair[1]);
}
}
}
var scripts = document.getElementsByTagName('script');
var src, index, search, chunks, scriptParams = {};
for (i = scripts.length - 1; i >= 0; --i) {
src = scripts[i].getAttribute('src');
if (~(index = src.indexOf('loader.js?'))) {
search = src.substr(index + 10);
chunks = search ? search.split('&') : [];
for (i = chunks.length - 1; i >= 0; --i) {
pair = chunks[i].split('=');
if (pair[0]) {
scriptParams[decodeURIComponent(pair[0])] =
decodeURIComponent(pair[1]);
}
}
break;
}
}
var raw = pageParams.mode && pageParams.mode.toLowerCase() === 'raw';
var scriptId = encodeURIComponent(scriptParams.id);
if (!raw) {
document.write('<scr' + 'ipt type="text/javascript" src="../build/ol.js"></scr' + 'ipt>');
} else {
window.CLOSURE_NO_DEPS = true; // we've got our own deps file
document.write('<scr' + 'ipt type="text/javascript" src="../closure-library/closure/goog/base.js"></scr' + 'ipt>');
document.write('<scr' + 'ipt type="text/javascript" src="../build/ol-deps.js"></scr' + 'ipt>');
document.write('<scr' + 'ipt type="text/javascript" src="' + scriptId + '-require.js"></scr' + 'ipt>');
}
document.write('<scr' + 'ipt type="text/javascript" src="' + scriptId + '.js"></scr' + 'ipt>');
}());
+39
View File
@@ -0,0 +1,39 @@
import os
import re
import sys
def split_example_file(example, dst_dir):
lines = open(example, 'rU').readlines()
target_lines = []
target_require_lines = []
found_requires = False
found_code = False
for line in lines:
m = re.match(r'goog.require\(\'(.*)\'\);', line)
if m:
found_requires = True
target_require_lines.append(line)
elif found_requires:
if found_code or line not in ('\n', '\r\n'):
found_code = True
target_lines.append(line)
target = open(
os.path.join(dst_dir, os.path.basename(example)), 'wb')
target_require = open(
os.path.join(dst_dir, os.path.basename(example)
.replace('.js', '-require.js')),
'wb')
target.writelines(target_lines)
target.close()
target_require.writelines(target_require_lines)
target_require.close()
if __name__ == '__main__':
split_example_file(*sys.argv[1:])
-118
View File
@@ -1,123 +1,5 @@
## Upgrade notes ## Upgrade notes
### Next release
#### Removal of ol.FeatureStyleFunction
The signature of the vector style function passed to the feature has changed. The function now always takes the `feature` and the `resolution` as arguments, the `feature` is no longer bound to `this`.
Old code:
```js
feature.setStyle(function(resolution) {
var text = this.get('name');
...
});
```
New code:
```js
feature.setStyle(function(feature, resolution) {
var text = feature.get('name');
...
});
```
#### Changed behavior of the `Draw` interaction
For better drawing experience, two changes were made to the behavior of the Draw interaction:
1. On long press, the current vertex can be dragged to its desired position.
2. On touch move (e.g. when panning the map on a mobile device), no draw cursor is shown, and the geometry being drawn is not updated. But because of 1., the draw cursor will appear on long press. Mouse moves are not affected by this change.
#### Changes in proj4 integration
Because relying on a globally available proj4 is not practical with ES modules, we have made a change to the way we integrate proj4:
* The `setProj4()` function from the `ol/proj` module was removed.
* A new `ol/proj/proj4` module with a `register()` function was added. Regardless of whether the application imports `proj4` or uses a global `proj4`, this function needs to be called with the proj4 instance as argument whenever projection definitions were added to proj4's registry with (`proj4.defs`).
It is also recommended to no longer use a global `proj4`. Instead,
npm install proj4
and import it:
```js
import proj4 from 'proj4';
```
Applications can be updated by importing the `register` function from the `ol/proj/proj4` module
```js
import {register} from 'ol/proj/proj4'
```
and calling it before using projections, and any time the proj4 registry was changed by `proj4.defs()` calls:
```js
register(proj4);
```
#### Removal of logos
The map and sources no longer accept a `logo` option. Instead, if you wish to append a logo to your map, add the desired markup directly in your HTML. In addition, you can use the `attributions` property of a source to display arbitrary markup per-source with the attribution control.
#### Replacement of `ol/Sphere` constructor with `ol/sphere` functions
The `ol/Sphere` constructor has been removed. If you were using the `getGeodesicArea` method, use the `getArea` function instead. If you were using the `haversineDistance` method, use the `getDistance` function instead.
Examples before:
```js
// using ol@4
import Sphere from 'ol/sphere';
var sphere = new Sphere(Sphere.DEFAULT_RADIUS);
var area = sphere.getGeodesicArea(polygon);
var distance = sphere.haversineDistance(g1, g2);
```
Examples after:
```js
// using ol@5
import {circular as circularPolygon} from 'ol/geom/Polygon';
import {getArea, getDistance} from 'ol/sphere';
var area = getArea(polygon);
var distance = getDistance(g1, g2);
var circle = circularPolygon(center, radius);
```
#### New signature for the `circular` function for creating polygons
The `circular` function exported from `ol/geom/Polygon` no longer requires a `Sphere` as the first argument.
Example before:
```js
// using ol@4
import Polygon from 'ol/geom/polygon';
import Sphere from 'ol/sphere';
var poly = Polygon.circular(new Sphere(Sphere.DEFAULT_RADIUS), center, radius);
```
Example after:
```js
// using ol@5
import {circular as circularPolygon} from 'ol/geom/Polygon';
var poly = circularPolygon(center, radius);
```
#### Removal of optional this arguments.
The following methods did get the optional this (i.e. opt_this) arguments removed. Please use closures, the es6 arrow function or the bind method to achieve this effect (Bind is explained here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
* Collection#forEach
* geom/LineString#forEachSegment
* Observable#on, #once, #un
* source/TileUTFGrid#forDataAtCoordinateAndResolution
* source/Vector#forEachFeature, #forEachFeatureInExtent, #forEachFeatureIntersectingExtent
### v4.6.0 ### v4.6.0
#### Renamed `exceedLength` option of `ol.style.Text` to `overflow` #### Renamed `exceedLength` option of `ol.style.Text` to `overflow`
-7
View File
@@ -1,7 +0,0 @@
# 4.6.5
The v4.6.5 release fixes a hit detection issue when `declutter: true` is set on an `ol.layer.VectorTile`.
## Fixes
* [#7669](https://github.com/openlayers/openlayers/pull/7559) - Use declutter tree only for text and image replays ([@ahocevar](https://github.com/ahocevar))
+45
View File
@@ -0,0 +1,45 @@
{
"exports": [],
"src": [
"src/**/*.js",
"build/ol.ext/*.js",
"build/examples/{{id}}.js"
],
"compile": {
"js": [
"externs/olx.js",
"externs/oli.js"
],
"externs": [
"externs/bingmaps.js",
"externs/cartodb.js",
"externs/bootstrap.js",
"externs/closure-compiler.js",
"externs/esrijson.js",
"externs/example.js",
"externs/geojson.js",
"externs/jquery-1.9.js",
"externs/proj4js.js",
"externs/tilejson.js",
"externs/topojson.js"
],
"jscomp_error": [
"*"
],
"jscomp_off": [
"lintChecks",
"analyzerChecks",
"missingProvide",
"unknownDefines"
],
"extra_annotation_name": [
"api", "observable"
],
"rewrite_polyfills": "false",
"compilation_level": "ADVANCED",
"warning_level": "VERBOSE",
"output_wrapper": "(function(){%output%})();",
"use_types_for_optimization": true,
"manage_closure_dependencies": true
}
}
+45
View File
@@ -0,0 +1,45 @@
{
"exports": [],
"src": [
"src/**/*.js",
"build/ol.ext/*.js",
"build/compiled-examples/all.js"
],
"compile": {
"js": [
"externs/olx.js",
"externs/oli.js"
],
"externs": [
"externs/bingmaps.js",
"externs/bootstrap.js",
"externs/cartodb.js",
"externs/closure-compiler.js",
"externs/esrijson.js",
"externs/example.js",
"externs/geojson.js",
"externs/jquery-1.9.js",
"externs/proj4js.js",
"externs/tilejson.js",
"externs/topojson.js"
],
"jscomp_error": [
"*"
],
"jscomp_off": [
"lintChecks",
"analyzerChecks",
"unusedLocalVariables"
],
"extra_annotation_name": [
"api", "observable"
],
"rewrite_polyfills": "false",
"compilation_level": "ADVANCED",
"warning_level": "VERBOSE",
"output_wrapper": "(function(){%output%})();",
"use_types_for_optimization": true,
"manage_closure_dependencies": true
}
}
@@ -12,7 +12,7 @@
{{{ extraHead.local }}} {{{ extraHead.local }}}
{{{ css.tag }}} {{{ css.tag }}}
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,URL"></script> <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.7.1/clipboard.min.js"></script> <script src="./resources/zeroclipboard/ZeroClipboard.min.js"></script>
<title>{{ title }}</title> <title>{{ title }}</title>
</head> </head>
<body> <body>
@@ -52,12 +52,13 @@
<div class="span12"> <div class="span12">
<p id="shortdesc">{{ shortdesc }}</p> <p id="shortdesc">{{ shortdesc }}</p>
<div id="docs">{{ md docs }}</div> <div id="docs">{{ md docs }}</div>
<div id="api-links">Related API documentation: {{{ js.apiHtml }}}</div>
</div> </div>
</div> </div>
<div class="row-fluid"> <div class="row-fluid">
<div id="source-controls"> <div id="source-controls">
<a id="copy-button" data-clipboard-target="#example-source"><i class="fa fa-clipboard"></i> Copy</a> <a id="copy-button"><i class="fa fa-clipboard"></i> Copy</a>
<a id="codepen-button"><i class="fa fa-codepen"></i> Edit</a> <a id="codepen-button"><i class="fa fa-codepen"></i> Edit</a>
</div> </div>
<form method="POST" id="codepen-form" target="_blank" action="https://codepen.io/pen/define/"> <form method="POST" id="codepen-form" target="_blank" action="https://codepen.io/pen/define/">
@@ -104,7 +105,7 @@
var branchSearch = url.match(/\/([^\/]*)\/examples\//); var branchSearch = url.match(/\/([^\/]*)\/examples\//);
var cookieText = 'dismissed=-' + latestVersion + '-'; var cookieText = 'dismissed=-' + latestVersion + '-';
var dismissed = document.cookie.indexOf(cookieText) != -1; var dismissed = document.cookie.indexOf(cookieText) != -1;
if (branchSearch && !dismissed && /^v[0-9\.]*$/.test(branchSearch[1]) && '{{ olVersion }}' != latestVersion) { if (!dismissed && /^v[0-9\.]*$/.test(branchSearch[1]) && '{{ olVersion }}' != latestVersion) {
var link = url.replace(branchSearch[0], '/latest/examples/'); var link = url.replace(branchSearch[0], '/latest/examples/');
fetch(link, {method: 'head'}).then(function(response) { fetch(link, {method: 'head'}).then(function(response) {
var a = document.getElementById('latest-link'); var a = document.getElementById('latest-link');
+1 -1
View File
@@ -8,7 +8,7 @@ exports.defineTags = function(dictionary) {
dictionary.defineTag('api', { dictionary.defineTag('api', {
onTagged: function(doclet, tag) { onTagged: function(doclet, tag) {
doclet.api = true; doclet.api = tag.text || 'experimental';
} }
}); });
+48 -50
View File
@@ -2,8 +2,8 @@
* @fileoverview Generates JSON output based on exportable symbols (those with * @fileoverview Generates JSON output based on exportable symbols (those with
* an api tag) and boolean defines (with a define tag and a default value). * an api tag) and boolean defines (with a define tag and a default value).
*/ */
const assert = require('assert'); var assert = require('assert');
const path = require('path'); var path = require('path');
/** /**
@@ -15,7 +15,7 @@ const path = require('path');
exports.publish = function(data, opts) { exports.publish = function(data, opts) {
function getTypes(data) { function getTypes(data) {
const types = []; var types = [];
data.forEach(function(name) { data.forEach(function(name) {
types.push(name.replace(/^function$/, 'Function')); types.push(name.replace(/^function$/, 'Function'));
}); });
@@ -24,43 +24,43 @@ exports.publish = function(data, opts) {
// get all doclets with the "api" property or define (excluding events) or // get all doclets with the "api" property or define (excluding events) or
// with olx namespace // with olx namespace
const classes = {}; var classes = {};
const docs = data( var docs = data(
[ [
{define: {isObject: true}}, {define: {isObject: true}},
function() { function() {
if (this.kind == 'class') { if (this.kind == 'class') {
if (!('extends' in this) || typeof this.api == 'boolean') { if (!('extends' in this) || typeof this.api == 'string') {
classes[this.longname] = this; classes[this.longname] = this;
return true; return true;
}
} }
} return (typeof this.api == 'string' ||
return (typeof this.api == 'boolean' ||
this.meta && (/[\\\/]externs$/).test(this.meta.path)); 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 = []; var symbols = [];
const defines = []; var defines = [];
const typedefs = []; var typedefs = [];
const externs = []; var externs = [];
let base = []; var base = [];
const augments = {}; var augments = {};
const symbolsByName = {}; var symbolsByName = {};
docs.filter(function(doc) { docs.filter(function(doc) {
let include = true; var include = true;
const constructor = doc.memberof; var constructor = doc.memberof;
if (constructor && constructor.substr(-1) === '_' && constructor.indexOf('module:') === -1) { if (constructor && constructor.substr(-1) === '_') {
assert.strictEqual(doc.inherited, true, assert.strictEqual(doc.inherited, true,
'Unexpected export on private class: ' + doc.longname); 'Unexpected export on private class: ' + doc.longname);
include = false; include = false;
} }
return include; return include;
}).forEach(function(doc) { }).forEach(function(doc) {
const isExterns = (/[\\\/]externs$/).test(doc.meta.path); var isExterns = (/[\\\/]externs$/).test(doc.meta.path);
if (isExterns && doc.longname.indexOf('olx.') === 0) { if (isExterns && doc.longname.indexOf('olx.') === 0) {
if (doc.kind == 'typedef') { if (doc.kind == 'typedef') {
typedefs.push({ typedefs.push({
@@ -68,15 +68,12 @@ exports.publish = function(data, opts) {
types: ['{}'] types: ['{}']
}); });
} else { } else {
const typedef = typedefs[typedefs.length - 1]; var typedef = typedefs[typedefs.length - 1];
if (!typedef) { var type = typedef.types[0];
throw new Error(`Expected to see a typedef before ${doc.longname} at ${doc.meta.filename}:${doc.meta.lineno}`);
}
const type = typedef.types[0];
typedef.types[0] = type typedef.types[0] = type
.replace(/\}$/, ', ' + doc.longname.split('#')[1] + .replace(/\}$/, ', ' + doc.longname.split('#')[1] +
': (' + getTypes(doc.type.names).join('|') + ')}') ': (' + getTypes(doc.type.names).join('|') + ')}')
.replace('{, ', '{'); .replace('{, ', '{');
} }
} else if (doc.define) { } else if (doc.define) {
defines.push({ defines.push({
@@ -91,10 +88,11 @@ exports.publish = function(data, opts) {
types: getTypes(doc.type.names) types: getTypes(doc.type.names)
}); });
} else { } else {
const symbol = { var symbol = {
name: doc.longname, name: doc.longname,
kind: doc.kind, kind: doc.kind,
description: doc.classdesc || doc.description, description: doc.classdesc || doc.description,
stability: doc.api,
path: path.join(doc.meta.path, doc.meta.filename) path: path.join(doc.meta.path, doc.meta.filename)
}; };
if (doc.augments) { if (doc.augments) {
@@ -107,9 +105,9 @@ exports.publish = function(data, opts) {
symbol.types = getTypes(doc.type.names); symbol.types = getTypes(doc.type.names);
} }
if (doc.params) { if (doc.params) {
const params = []; var params = [];
doc.params.forEach(function(param) { doc.params.forEach(function(param) {
const paramInfo = { var paramInfo = {
name: param.name name: param.name
}; };
params.push(paramInfo); params.push(paramInfo);
@@ -144,10 +142,10 @@ exports.publish = function(data, opts) {
}); });
} }
const target = isExterns ? externs : (doc.api ? symbols : base); var target = isExterns ? externs : (doc.api ? symbols : base);
const existingSymbol = symbolsByName[symbol.name]; var existingSymbol = symbolsByName[symbol.name];
if (existingSymbol) { if (existingSymbol) {
const idx = target.indexOf(existingSymbol); var idx = target.indexOf(existingSymbol);
target.splice(idx, 1); target.splice(idx, 1);
} }
target.push(symbol); target.push(symbol);
@@ -171,13 +169,13 @@ exports.publish = function(data, opts) {
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));
}); });
}; };
+4
View File
@@ -0,0 +1,4 @@
{
"exports": ["*"],
"umd": true
}
+38
View File
@@ -0,0 +1,38 @@
{
"exports": ["*"],
"umd": true,
"compile": {
"externs": [
"externs/bingmaps.js",
"externs/cartodb.js",
"externs/closure-compiler.js",
"externs/esrijson.js",
"externs/geojson.js",
"externs/oli.js",
"externs/olx.js",
"externs/proj4js.js",
"externs/tilejson.js",
"externs/topojson.js"
],
"define": [
"ol.DEBUG_WEBGL=false"
],
"jscomp_error": [
"*"
],
"jscomp_off": [
"lintChecks",
"analyzerChecks"
],
"extra_annotation_name": [
"api", "observable"
],
"rewrite_polyfills": "false",
"compilation_level": "ADVANCED",
"warning_level": "VERBOSE",
"use_types_for_optimization": true,
"manage_closure_dependencies": true,
"create_source_map": "build/ol.js.map",
"source_map_format": "V3"
}
}
+3
View File
@@ -0,0 +1,3 @@
# Configuration Files
This directory includes configuration files for the build scripts in and documentation templates.
-14
View File
@@ -1,14 +0,0 @@
const webpack = require('webpack');
const MinifyPlugin = require('babel-minify-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'build/ol.js'
},
devtool: 'source-map',
plugins: [
new webpack.optimize.ModuleConcatenationPlugin(),
new MinifyPlugin()
]
};
+14 -4
View File
@@ -44,10 +44,10 @@
} }
.ol-selectable { .ol-selectable {
-webkit-touch-callout: default; -webkit-touch-callout: default;
-webkit-user-select: text; -webkit-user-select: auto;
-moz-user-select: text; -moz-user-select: auto;
-ms-user-select: text; -ms-user-select: auto;
user-select: text; user-select: auto;
} }
.ol-grabbing { .ol-grabbing {
cursor: -webkit-grabbing; cursor: -webkit-grabbing;
@@ -179,6 +179,9 @@
.ol-attribution.ol-collapsed ul { .ol-attribution.ol-collapsed ul {
display: none; display: none;
} }
.ol-attribution.ol-logo-only ul {
display: block;
}
.ol-attribution:not(.ol-collapsed) { .ol-attribution:not(.ol-collapsed) {
background: rgba(255,255,255,0.8); background: rgba(255,255,255,0.8);
} }
@@ -189,10 +192,17 @@
height: 1.1em; height: 1.1em;
line-height: 1em; line-height: 1em;
} }
.ol-attribution.ol-logo-only {
background: transparent;
bottom: .4em;
height: 1.1em;
line-height: 1em;
}
.ol-attribution.ol-uncollapsible img { .ol-attribution.ol-uncollapsible img {
margin-top: -.2em; margin-top: -.2em;
max-height: 1.6em; max-height: 1.6em;
} }
.ol-attribution.ol-logo-only button,
.ol-attribution.ol-uncollapsible button { .ol-attribution.ol-uncollapsible button {
display: none; display: none;
} }
+14 -4
View File
@@ -44,10 +44,10 @@
} }
.ol-selectable { .ol-selectable {
-webkit-touch-callout: default; -webkit-touch-callout: default;
-webkit-user-select: text; -webkit-user-select: auto;
-moz-user-select: text; -moz-user-select: auto;
-ms-user-select: text; -ms-user-select: auto;
user-select: text; user-select: auto;
} }
.ol-grabbing { .ol-grabbing {
cursor: -webkit-grabbing; cursor: -webkit-grabbing;
@@ -179,6 +179,9 @@
.ol-attribution.ol-collapsed ul { .ol-attribution.ol-collapsed ul {
display: none; display: none;
} }
.ol-attribution.ol-logo-only ul {
display: block;
}
.ol-attribution:not(.ol-collapsed) { .ol-attribution:not(.ol-collapsed) {
background: rgba(255,255,255,0.8); background: rgba(255,255,255,0.8);
} }
@@ -189,10 +192,17 @@
height: 1.1em; height: 1.1em;
line-height: 1em; line-height: 1em;
} }
.ol-attribution.ol-logo-only {
background: transparent;
bottom: .4em;
height: 1.1em;
line-height: 1em;
}
.ol-attribution.ol-uncollapsible img { .ol-attribution.ol-uncollapsible img {
margin-top: -.2em; margin-top: -.2em;
max-height: 1.6em; max-height: 1.6em;
} }
.ol-attribution.ol-logo-only button,
.ol-attribution.ol-uncollapsible button { .ol-attribution.ol-uncollapsible button {
display: none; display: none;
} }
+96462
View File
File diff suppressed because one or more lines are too long
Vendored
+1
View File
@@ -0,0 +1 @@
.ol-box{box-sizing:border-box;border-radius:2px;border:2px solid #00f}.ol-mouse-position{top:8px;right:8px;position:absolute}.ol-scale-line{background:rgba(0,60,136,.3);border-radius:4px;bottom:8px;left:8px;padding:2px;position:absolute}.ol-scale-line-inner{border:1px solid #eee;border-top:none;color:#eee;font-size:10px;text-align:center;margin:1px;will-change:contents,width}.ol-overlay-container{will-change:left,right,top,bottom}.ol-unsupported{display:none}.ol-unselectable,.ol-viewport{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}.ol-selectable{-webkit-touch-callout:default;-webkit-user-select:auto;-moz-user-select:auto;-ms-user-select:auto;user-select:auto}.ol-grabbing{cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:grabbing}.ol-grab{cursor:move;cursor:-webkit-grab;cursor:-moz-grab;cursor:grab}.ol-control{position:absolute;background-color:rgba(255,255,255,.4);border-radius:4px;padding:2px}.ol-control:hover{background-color:rgba(255,255,255,.6)}.ol-zoom{top:.5em;left:.5em}.ol-rotate{top:.5em;right:.5em;transition:opacity .25s linear,visibility 0s linear}.ol-rotate.ol-hidden{opacity:0;visibility:hidden;transition:opacity .25s linear,visibility 0s linear .25s}.ol-zoom-extent{top:4.643em;left:.5em}.ol-full-screen{right:.5em;top:.5em}@media print{.ol-control{display:none}}.ol-control button{display:block;margin:1px;padding:0;color:#fff;font-size:1.14em;font-weight:700;text-decoration:none;text-align:center;height:1.375em;width:1.375em;line-height:.4em;background-color:rgba(0,60,136,.5);border:none;border-radius:2px}.ol-control button::-moz-focus-inner{border:none;padding:0}.ol-zoom-extent button{line-height:1.4em}.ol-compass{display:block;font-weight:400;font-size:1.2em;will-change:transform}.ol-touch .ol-control button{font-size:1.5em}.ol-touch .ol-zoom-extent{top:5.5em}.ol-control button:focus,.ol-control button:hover{text-decoration:none;background-color:rgba(0,60,136,.7)}.ol-zoom .ol-zoom-in{border-radius:2px 2px 0 0}.ol-zoom .ol-zoom-out{border-radius:0 0 2px 2px}.ol-attribution{text-align:right;bottom:.5em;right:.5em;max-width:calc(100% - 1.3em)}.ol-attribution ul{margin:0;padding:0 .5em;font-size:.7rem;line-height:1.375em;color:#000;text-shadow:0 0 2px #fff}.ol-attribution li{display:inline;list-style:none;line-height:inherit}.ol-attribution li:not(:last-child):after{content:" "}.ol-attribution img{max-height:2em;max-width:inherit;vertical-align:middle}.ol-attribution button,.ol-attribution ul{display:inline-block}.ol-attribution.ol-collapsed ul{display:none}.ol-attribution.ol-logo-only ul{display:block}.ol-attribution:not(.ol-collapsed){background:rgba(255,255,255,.8)}.ol-attribution.ol-uncollapsible{bottom:0;right:0;border-radius:4px 0 0;height:1.1em;line-height:1em}.ol-attribution.ol-logo-only{background:0 0;bottom:.4em;height:1.1em;line-height:1em}.ol-attribution.ol-uncollapsible img{margin-top:-.2em;max-height:1.6em}.ol-attribution.ol-logo-only button,.ol-attribution.ol-uncollapsible button{display:none}.ol-zoomslider{top:4.5em;left:.5em;height:200px}.ol-zoomslider button{position:relative;height:10px}.ol-touch .ol-zoomslider{top:5.5em}.ol-overviewmap{left:.5em;bottom:.5em}.ol-overviewmap.ol-uncollapsible{bottom:0;left:0;border-radius:0 4px 0 0}.ol-overviewmap .ol-overviewmap-map,.ol-overviewmap button{display:inline-block}.ol-overviewmap .ol-overviewmap-map{border:1px solid #7b98bc;height:150px;margin:2px;width:150px}.ol-overviewmap:not(.ol-collapsed) button{bottom:1px;left:2px;position:absolute}.ol-overviewmap.ol-collapsed .ol-overviewmap-map,.ol-overviewmap.ol-uncollapsible button{display:none}.ol-overviewmap:not(.ol-collapsed){background:rgba(255,255,255,.8)}.ol-overviewmap-box{border:2px dotted rgba(0,60,136,.7)}.ol-overviewmap .ol-overviewmap-box:hover{cursor:move}
Vendored
+1073
View File
File diff suppressed because one or more lines are too long
+9 -1
View File
@@ -43,7 +43,7 @@ Unknown `serverType` configured.
### 10 ### 10
The default `geometryFunction` can only handle `ol/geom/Point` geometries. The default `geometryFunction` can only handle `ol.geom.Point` geometries.
### 11 ### 11
@@ -165,6 +165,14 @@ Expected an `ol.style.Style` or an array of `ol.style.Style`.
Expected `layers` to be an array or an `ol.Collection`. Expected `layers` to be an array or an `ol.Collection`.
### 44
`logo.href` should be a string.
### 45
`logo.src` should be a string.
### 46 ### 46
Incorrect format for `renderer` option. Incorrect format for `renderer` option.
+1 -1
View File
@@ -107,7 +107,7 @@ In case you are creating a custom build of OpenLayers and do not need the reproj
See [Custom builds](custom-builds.html#defines) tutorial on how to do this. See [Custom builds](custom-builds.html#defines) tutorial on how to do this.
### Triangulation precision threshold ### Triangulation precision threshold
The default [triangulation error threshold](#dynamic-triangulation) in pixels is given by `ERROR_THRESHOLD` (0.5 pixel). The default [triangulation error threshold](#dynamic-triangulation) in pixels is given by `ol.DEFAULT_RASTER_REPROJECTION_ERROR_THRESHOLD` (0.5 pixel).
In case a different threshold needs to be defined for different sources, the `reprojectionErrorThreshold` option can be passed when constructing the tile image source. In case a different threshold needs to be defined for different sources, the `reprojectionErrorThreshold` option can be passed when constructing the tile image source.
###Limiting visibility of reprojected map by extent ###Limiting visibility of reprojected map by extent
-7
View File
@@ -1,10 +1,3 @@
/*
* Jugl.js -- JavaScript Template Library
*
* Copyright 2007-2010 Tim Schaub
* Released under the MIT license. Please see
* http://github.com/tschaub/jugl/blob/master/license.txt for the full license.
*/
/* /*
* Jugl.js -- JavaScript Template Library * Jugl.js -- JavaScript Template Library
* *
+14 -14
View File
@@ -1,36 +1,36 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
target: 'map', target: 'map',
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
}), }),
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
}); });
document.getElementById('zoom-out').onclick = function() { document.getElementById('zoom-out').onclick = function() {
const view = map.getView(); var view = map.getView();
const zoom = view.getZoom(); var zoom = view.getZoom();
view.setZoom(zoom - 1); view.setZoom(zoom - 1);
}; };
document.getElementById('zoom-in').onclick = function() { document.getElementById('zoom-in').onclick = function() {
const view = map.getView(); var view = map.getView();
const zoom = view.getZoom(); var zoom = view.getZoom();
view.setZoom(zoom + 1); view.setZoom(zoom + 1);
}; };
+29 -31
View File
@@ -1,27 +1,27 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {easeIn, easeOut} from '../src/ol/easing.js'; goog.require('ol.easing');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import {fromLonLat} from '../src/ol/proj.js'; goog.require('ol.proj');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
const london = fromLonLat([-0.12755, 51.507222]); var london = ol.proj.fromLonLat([-0.12755, 51.507222]);
const moscow = fromLonLat([37.6178, 55.7517]); var moscow = ol.proj.fromLonLat([37.6178, 55.7517]);
const istanbul = fromLonLat([28.9744, 41.0128]); var istanbul = ol.proj.fromLonLat([28.9744, 41.0128]);
const rome = fromLonLat([12.5, 41.9]); var rome = ol.proj.fromLonLat([12.5, 41.9]);
const bern = fromLonLat([7.4458, 46.95]); var bern = ol.proj.fromLonLat([7.4458, 46.95]);
const view = new View({ var view = new ol.View({
center: istanbul, center: istanbul,
zoom: 6 zoom: 6
}); });
const map = new Map({ var map = new ol.Map({
target: 'map', target: 'map',
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
preload: 4, preload: 4,
source: new OSM() source: new ol.source.OSM()
}) })
], ],
// Improve user experience by loading tiles while animating. Will make // Improve user experience by loading tiles while animating. Will make
@@ -32,9 +32,7 @@ const map = new Map({
// A bounce easing method (from https://github.com/DmitryBaranovskiy/raphael). // A bounce easing method (from https://github.com/DmitryBaranovskiy/raphael).
function bounce(t) { function bounce(t) {
const s = 7.5625; var s = 7.5625, p = 2.75, l;
const p = 2.75;
let l;
if (t < (1 / p)) { if (t < (1 / p)) {
l = s * t * t; l = s * t * t;
} else { } else {
@@ -77,15 +75,15 @@ onClick('rotate-right', function() {
onClick('rotate-around-rome', function() { onClick('rotate-around-rome', function() {
// Rotation animation takes the shortest arc, so animate in two parts // Rotation animation takes the shortest arc, so animate in two parts
const rotation = view.getRotation(); var rotation = view.getRotation();
view.animate({ view.animate({
rotation: rotation + Math.PI, rotation: rotation + Math.PI,
anchor: rome, anchor: rome,
easing: easeIn easing: ol.easing.easeIn
}, { }, {
rotation: rotation + 2 * Math.PI, rotation: rotation + 2 * Math.PI,
anchor: rome, anchor: rome,
easing: easeOut easing: ol.easing.easeOut
}); });
}); });
@@ -114,26 +112,26 @@ onClick('bounce-to-istanbul', function() {
onClick('spin-to-rome', function() { onClick('spin-to-rome', function() {
// Rotation animation takes the shortest arc, so animate in two parts // Rotation animation takes the shortest arc, so animate in two parts
const center = view.getCenter(); var 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: ol.easing.easeIn
}, { }, {
center: rome, center: rome,
rotation: 2 * Math.PI, rotation: 2 * Math.PI,
easing: easeOut easing: ol.easing.easeOut
}); });
}); });
function flyTo(location, done) { function flyTo(location, done) {
const duration = 2000; var duration = 2000;
const zoom = view.getZoom(); var zoom = view.getZoom();
let parts = 2; var parts = 2;
let called = false; var called = false;
function callback(complete) { function callback(complete) {
--parts; --parts;
if (called) { if (called) {
@@ -162,13 +160,13 @@ onClick('fly-to-bern', function() {
}); });
function tour() { function tour() {
const locations = [london, bern, rome, moscow, istanbul]; var locations = [london, bern, rome, moscow, istanbul];
let index = -1; var index = -1;
function next(more) { function next(more) {
if (more) { if (more) {
++index; ++index;
if (index < locations.length) { if (index < locations.length) {
const delay = index === 0 ? 0 : 750; var delay = index === 0 ? 0 : 750;
setTimeout(function() { setTimeout(function() {
flyTo(locations[index], next); flyTo(locations[index], next);
}, delay); }, delay);
+14 -14
View File
@@ -1,29 +1,29 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import ImageLayer from '../src/ol/layer/Image.js'; goog.require('ol.layer.Image');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import ImageArcGISRest from '../src/ol/source/ImageArcGISRest.js'; goog.require('ol.source.ImageArcGISRest');
const url = 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' + var url = 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' +
'Specialty/ESRI_StateCityHighway_USA/MapServer'; 'Specialty/ESRI_StateCityHighway_USA/MapServer';
const layers = [ var layers = [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}), }),
new ImageLayer({ new ol.layer.Image({
source: new ImageArcGISRest({ source: new ol.source.ImageArcGISRest({
ratio: 1, ratio: 1,
params: {}, params: {},
url: url url: url
}) })
}) })
]; ];
const map = new Map({ var map = new ol.Map({
layers: layers, layers: layers,
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [-10997148, 4569099], center: [-10997148, 4569099],
zoom: 4 zoom: 4
}) })
+13 -13
View File
@@ -1,27 +1,27 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import TileArcGISRest from '../src/ol/source/TileArcGISRest.js'; goog.require('ol.source.TileArcGISRest');
const url = 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' + var url = 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' +
'Specialty/ESRI_StateCityHighway_USA/MapServer'; 'Specialty/ESRI_StateCityHighway_USA/MapServer';
const layers = [ var layers = [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}), }),
new TileLayer({ new ol.layer.Tile({
extent: [-13884991, 2870341, -7455066, 6338219], extent: [-13884991, 2870341, -7455066, 6338219],
source: new TileArcGISRest({ source: new ol.source.TileArcGISRest({
url: url url: url
}) })
}) })
]; ];
const map = new Map({ var map = new ol.Map({
layers: layers, layers: layers,
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [-10997148, 4569099], center: [-10997148, 4569099],
zoom: 4 zoom: 4
}) })
+13 -13
View File
@@ -1,29 +1,29 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import Attribution from '../src/ol/control/Attribution.js'; goog.require('ol.control.Attribution');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
const attribution = new Attribution({ var attribution = new ol.control.Attribution({
collapsible: false collapsible: false
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
controls: defaultControls({attribution: false}).extend([attribution]), controls: ol.control.defaults({attribution: false}).extend([attribution]),
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
}); });
function checkSize() { function checkSize() {
const small = map.getSize()[0] < 600; var small = map.getSize()[0] < 600;
attribution.setCollapsible(small); attribution.setCollapsible(small);
attribution.setCollapsed(small); attribution.setCollapsed(small);
} }
+14 -14
View File
@@ -1,10 +1,10 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import BingMaps from '../src/ol/source/BingMaps.js'; goog.require('ol.source.BingMaps');
const styles = [ var styles = [
'Road', 'Road',
'RoadOnDemand', 'RoadOnDemand',
'Aerial', 'Aerial',
@@ -12,13 +12,13 @@ const styles = [
'collinsBart', 'collinsBart',
'ordnanceSurvey' 'ordnanceSurvey'
]; ];
const layers = []; var layers = [];
let i, ii; var 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 ol.layer.Tile({
visible: false, visible: false,
preload: Infinity, preload: Infinity,
source: new BingMaps({ source: new ol.source.BingMaps({
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5', key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5',
imagerySet: styles[i] 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
@@ -27,22 +27,22 @@ for (i = 0, ii = styles.length; i < ii; ++i) {
}) })
})); }));
} }
const map = new Map({ var map = new ol.Map({
layers: layers, layers: layers,
// Improve user experience by loading tiles while dragging/zooming. Will make // Improve user experience by loading tiles while dragging/zooming. Will make
// zooming choppy on mobile or slow devices. // zooming choppy on mobile or slow devices.
loadTilesWhileInteracting: true, loadTilesWhileInteracting: true,
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [-6655.5402445057125, 6709968.258934638], center: [-6655.5402445057125, 6709968.258934638],
zoom: 13 zoom: 13
}) })
}); });
const select = document.getElementById('layer-select'); var select = document.getElementById('layer-select');
function onChange() { function onChange() {
const style = select.value; var style = select.value;
for (let i = 0, ii = layers.length; i < ii; ++i) { for (var i = 0, ii = layers.length; i < ii; ++i) {
layers[i].setVisible(styles[i] === style); layers[i].setVisible(styles[i] === style);
} }
} }
+43 -43
View File
@@ -1,29 +1,29 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
// Create separate layers for red, green an blue circles. // Create separate layers for red, green an blue circles.
// //
// Every layer has one feature that is styled with a circle, together the // Every layer has one feature that is styled with a circle, together the
// features form the corners of an equilateral triangle and their styles overlap // features form the corners of an equilateral triangle and their styles overlap
const redLayer = new VectorLayer({ var redLayer = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
features: [new Feature(new Point([0, 0]))] features: [new ol.Feature(new ol.geom.Point([0, 0]))]
}), }),
style: new Style({ style: new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.8)' color: 'rgba(255,0,0,0.8)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'rgb(255,0,0)', color: 'rgb(255,0,0)',
width: 15 width: 15
}), }),
@@ -31,17 +31,17 @@ const redLayer = new VectorLayer({
}) })
}) })
}); });
const greenLayer = new VectorLayer({ var greenLayer = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
// 433.013 is roughly 250 * Math.sqrt(3) // 433.013 is roughly 250 * Math.sqrt(3)
features: [new Feature(new Point([250, 433.013]))] features: [new ol.Feature(new ol.geom.Point([250, 433.013]))]
}), }),
style: new Style({ style: new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(0,255,0,0.8)' color: 'rgba(0,255,0,0.8)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'rgb(0,255,0)', color: 'rgb(0,255,0)',
width: 15 width: 15
}), }),
@@ -49,16 +49,16 @@ const greenLayer = new VectorLayer({
}) })
}) })
}); });
const blueLayer = new VectorLayer({ var blueLayer = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
features: [new Feature(new Point([500, 0]))] features: [new ol.Feature(new ol.geom.Point([500, 0]))]
}), }),
style: new Style({ style: new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(0,0,255,0.8)' color: 'rgba(0,0,255,0.8)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'rgb(0,0,255)', color: 'rgb(0,0,255)',
width: 15 width: 15
}), }),
@@ -69,14 +69,14 @@ const blueLayer = new VectorLayer({
// Create the map, the view is centered on the triangle. Zooming and panning is // Create the map, the view is centered on the triangle. Zooming and panning is
// restricted to a sane area // restricted to a sane area
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
redLayer, redLayer,
greenLayer, greenLayer,
blueLayer blueLayer
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [250, 220], center: [250, 220],
extent: [0, 0, 500, 500], extent: [0, 0, 500, 500],
resolution: 4, resolution: 4,
@@ -86,10 +86,10 @@ const map = new Map({
}); });
// Get the form elements and bind the listeners // Get the form elements and bind the listeners
const select = document.getElementById('blend-mode'); var select = document.getElementById('blend-mode');
const affectRed = document.getElementById('affect-red'); var affectRed = document.getElementById('affect-red');
const affectGreen = document.getElementById('affect-green'); var affectGreen = document.getElementById('affect-green');
const affectBlue = document.getElementById('affect-blue'); var affectBlue = document.getElementById('affect-blue');
/** /**
@@ -98,7 +98,7 @@ const affectBlue = document.getElementById('affect-blue');
* *
* @param {ol.render.Event} evt The render event. * @param {ol.render.Event} evt The render event.
*/ */
const setBlendModeFromSelect = function(evt) { var setBlendModeFromSelect = function(evt) {
evt.context.globalCompositeOperation = select.value; evt.context.globalCompositeOperation = select.value;
}; };
@@ -109,7 +109,7 @@ const setBlendModeFromSelect = function(evt) {
* *
* @param {ol.render.Event} evt The render event. * @param {ol.render.Event} evt The render event.
*/ */
const resetBlendModeFromSelect = function(evt) { var resetBlendModeFromSelect = function(evt) {
evt.context.globalCompositeOperation = 'source-over'; evt.context.globalCompositeOperation = 'source-over';
}; };
@@ -119,7 +119,7 @@ const resetBlendModeFromSelect = function(evt) {
* *
* @param {ol.layer.Vector} layer The layer to bind the handlers to. * @param {ol.layer.Vector} layer The layer to bind the handlers to.
*/ */
const bindLayerListeners = function(layer) { var bindLayerListeners = function(layer) {
layer.on('precompose', setBlendModeFromSelect); layer.on('precompose', setBlendModeFromSelect);
layer.on('postcompose', resetBlendModeFromSelect); layer.on('postcompose', resetBlendModeFromSelect);
}; };
@@ -130,7 +130,7 @@ const bindLayerListeners = function(layer) {
* *
* @param {ol.layer.Vector} layer The layer to unbind the handlers from. * @param {ol.layer.Vector} layer The layer to unbind the handlers from.
*/ */
const unbindLayerListeners = function(layer) { var unbindLayerListeners = function(layer) {
layer.un('precompose', setBlendModeFromSelect); layer.un('precompose', setBlendModeFromSelect);
layer.un('postcompose', resetBlendModeFromSelect); layer.un('postcompose', resetBlendModeFromSelect);
}; };
@@ -141,8 +141,8 @@ const unbindLayerListeners = function(layer) {
* *
* @this {HTMLInputElement} * @this {HTMLInputElement}
*/ */
const affectLayerClicked = function() { var affectLayerClicked = function() {
let layer; var layer;
if (this.id == 'affect-red') { if (this.id == 'affect-red') {
layer = redLayer; layer = redLayer;
} else if (this.id == 'affect-green') { } else if (this.id == 'affect-green') {
+24 -24
View File
@@ -1,46 +1,46 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {platformModifierKeyOnly} from '../src/ol/events/condition.js'; goog.require('ol.events.condition');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import DragBox from '../src/ol/interaction/DragBox.js'; goog.require('ol.interaction.DragBox');
import Select from '../src/ol/interaction/Select.js'; goog.require('ol.interaction.Select');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
const vectorSource = new VectorSource({ var vectorSource = new ol.source.Vector({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new ol.format.GeoJSON()
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}), }),
new VectorLayer({ new ol.layer.Vector({
source: vectorSource source: vectorSource
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
}); });
// a normal select interaction to handle click // a normal select interaction to handle click
const select = new Select(); var select = new ol.interaction.Select();
map.addInteraction(select); map.addInteraction(select);
const selectedFeatures = select.getFeatures(); var 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({ var dragBox = new ol.interaction.DragBox({
condition: platformModifierKeyOnly condition: ol.events.condition.platformModifierKeyOnly
}); });
map.addInteraction(dragBox); map.addInteraction(dragBox);
@@ -48,7 +48,7 @@ map.addInteraction(dragBox);
dragBox.on('boxend', function() { dragBox.on('boxend', function() {
// features that intersect the box are added to the collection of // features that intersect the box are added to the collection of
// selected features // selected features
const extent = dragBox.getGeometry().getExtent(); var extent = dragBox.getGeometry().getExtent();
vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) { vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {
selectedFeatures.push(feature); selectedFeatures.push(feature);
}); });
@@ -59,10 +59,10 @@ dragBox.on('boxstart', function() {
selectedFeatures.clear(); selectedFeatures.clear();
}); });
const infoBox = document.getElementById('info'); var infoBox = document.getElementById('info');
selectedFeatures.on(['add', 'remove'], function() { selectedFeatures.on(['add', 'remove'], function() {
const names = selectedFeatures.getArray().map(function(feature) { var names = selectedFeatures.getArray().map(function(feature) {
return feature.get('name'); return feature.get('name');
}); });
if (names.length > 0) { if (names.length > 0) {
+8 -8
View File
@@ -1,16 +1,16 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [-8730000, 5930000], center: [-8730000, 5930000],
rotation: Math.PI / 5, rotation: Math.PI / 5,
zoom: 8 zoom: 8
+30 -30
View File
@@ -1,31 +1,31 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {getWidth} from '../src/ol/extent.js'; goog.require('ol.extent');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import {DEVICE_PIXEL_RATIO} from '../src/ol/has.js'; goog.require('ol.has');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import {fromLonLat} from '../src/ol/proj.js'; goog.require('ol.proj');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const canvas = document.createElement('canvas'); var canvas = document.createElement('canvas');
const context = canvas.getContext('2d'); var context = canvas.getContext('2d');
// Gradient and pattern are in canvas pixel space, so we adjust for the // Gradient and pattern are in canvas pixel space, so we adjust for the
// renderer's pixel ratio // renderer's pixel ratio
const pixelRatio = DEVICE_PIXEL_RATIO; var pixelRatio = ol.has.DEVICE_PIXEL_RATIO;
// Generate a rainbow gradient // Generate a rainbow gradient
function gradient(feature, resolution) { function gradient(feature, resolution) {
const extent = feature.getGeometry().getExtent(); var extent = feature.getGeometry().getExtent();
// Gradient starts on the left edge of each feature, and ends on the right. // Gradient starts on the left edge of each feature, and ends on the right.
// Coordinate origin is the top-left corner of the extent of the geometry, so // Coordinate origin is the top-left corner of the extent of the geometry, so
// we just divide the geometry's extent width by resolution and multiply with // we just divide the geometry's extent width by resolution and multiply with
// pixelRatio to match the renderer's pixel coordinate system. // pixelRatio to match the renderer's pixel coordinate system.
const grad = context.createLinearGradient(0, 0, var grad = context.createLinearGradient(0, 0,
getWidth(extent) / resolution * pixelRatio, 0); ol.extent.getWidth(extent) / resolution * pixelRatio, 0);
grad.addColorStop(0, 'red'); grad.addColorStop(0, 'red');
grad.addColorStop(1 / 6, 'orange'); grad.addColorStop(1 / 6, 'orange');
grad.addColorStop(2 / 6, 'yellow'); grad.addColorStop(2 / 6, 'yellow');
@@ -37,7 +37,7 @@ function gradient(feature, resolution) {
} }
// Generate a canvasPattern with two circles on white background // Generate a canvasPattern with two circles on white background
const pattern = (function() { var pattern = (function() {
canvas.width = 11 * pixelRatio; canvas.width = 11 * pixelRatio;
canvas.height = 11 * pixelRatio; canvas.height = 11 * pixelRatio;
// white background // white background
@@ -57,10 +57,10 @@ const pattern = (function() {
}()); }());
// Generate style for gradient or pattern fill // Generate style for gradient or pattern fill
const fill = new Fill(); var fill = new ol.style.Fill();
const style = new Style({ var style = new ol.style.Style({
fill: fill, fill: fill,
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#333', color: '#333',
width: 2 width: 2
}) })
@@ -70,33 +70,33 @@ const style = new Style({
* The styling function for the vector layer, will return an array of styles * The styling function for the vector layer, will return an array of styles
* which either contains the aboove gradient or pattern. * which either contains the aboove gradient or pattern.
* *
* @param {module:ol/Feature~Feature} feature The feature to style. * @param {ol.Feature} feature The feature to style.
* @param {number} resolution Resolution. * @param {number} resolution Resolution.
* @return {ol.style.Style} The style to use for the feature. * @return {ol.style.Style} The style to use for the feature.
*/ */
const getStackedStyle = function(feature, resolution) { var getStackedStyle = function(feature, resolution) {
const id = feature.getId(); var id = feature.getId();
fill.setColor(id > 'J' ? gradient(feature, resolution) : pattern); fill.setColor(id > 'J' ? gradient(feature, resolution) : pattern);
return style; return style;
}; };
// Create a vector layer that makes use of the style function above… // Create a vector layer that makes use of the style function above…
const vectorLayer = new VectorLayer({ var vectorLayer = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new ol.format.GeoJSON()
}), }),
style: getStackedStyle style: getStackedStyle
}); });
// … finally create a map with that layer. // … finally create a map with that layer.
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
vectorLayer vectorLayer
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: fromLonLat([7, 52]), center: ol.proj.fromLonLat([7, 52]),
zoom: 3 zoom: 3
}) })
}); });
+16 -15
View File
@@ -1,33 +1,34 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import {fromLonLat} from '../src/ol/proj.js'; goog.require('ol.proj');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import TileDebug from '../src/ol/source/TileDebug.js'; goog.require('ol.source.TileDebug');
const osmSource = new OSM(); var osmSource = new ol.source.OSM();
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: osmSource source: osmSource
}), }),
new TileLayer({ new ol.layer.Tile({
source: new TileDebug({ source: new ol.source.TileDebug({
projection: 'EPSG:3857', projection: 'EPSG:3857',
tileGrid: osmSource.getTileGrid() tileGrid: osmSource.getTileGrid()
}) })
}) })
], ],
target: 'map', target: 'map',
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
}), }),
view: new View({ view: new ol.View({
center: fromLonLat([-0.1275, 51.507222]), center: ol.proj.transform(
[-0.1275, 51.507222], 'EPSG:4326', 'EPSG:3857'),
zoom: 10 zoom: 10
}) })
}); });
+12 -12
View File
@@ -1,10 +1,10 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import CartoDB from '../src/ol/source/CartoDB.js'; goog.require('ol.source.CartoDB');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
const mapConfig = { var mapConfig = {
'layers': [{ 'layers': [{
'type': 'cartodb', 'type': 'cartodb',
'options': { 'options': {
@@ -15,22 +15,22 @@ const mapConfig = {
}] }]
}; };
const cartoDBSource = new CartoDB({ var cartoDBSource = new ol.source.CartoDB({
account: 'documentation', account: 'documentation',
config: mapConfig config: mapConfig
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}), }),
new TileLayer({ new ol.layer.Tile({
source: cartoDBSource source: cartoDBSource
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
+42 -42
View File
@@ -1,56 +1,56 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const source = new VectorSource({ var source = new ol.source.Vector({
url: 'data/geojson/switzerland.geojson', url: 'data/geojson/switzerland.geojson',
format: new GeoJSON() format: new ol.format.GeoJSON()
}); });
const style = new Style({ var style = new ol.style.Style({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.6)' color: 'rgba(255, 255, 255, 0.6)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#319FD3', color: '#319FD3',
width: 1 width: 1
}), }),
image: new CircleStyle({ image: new ol.style.Circle({
radius: 5, radius: 5,
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.6)' color: 'rgba(255, 255, 255, 0.6)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#319FD3', color: '#319FD3',
width: 1 width: 1
}) })
}) })
}); });
const vectorLayer = new VectorLayer({ var vectorLayer = new ol.layer.Vector({
source: source, source: source,
style: style style: style
}); });
const view = new View({ var view = new ol.View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}), }),
vectorLayer vectorLayer
], ],
target: 'map', target: 'map',
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
@@ -58,40 +58,40 @@ const map = new Map({
view: view view: view
}); });
const zoomtoswitzerlandbest = document.getElementById('zoomtoswitzerlandbest'); var zoomtoswitzerlandbest = document.getElementById('zoomtoswitzerlandbest');
zoomtoswitzerlandbest.addEventListener('click', function() { zoomtoswitzerlandbest.addEventListener('click', function() {
const feature = source.getFeatures()[0]; var feature = source.getFeatures()[0];
const polygon = /** @type {module:ol/geom/SimpleGeometry~SimpleGeometry} */ (feature.getGeometry()); var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
view.fit(polygon, {padding: [170, 50, 30, 150], constrainResolution: false}); view.fit(polygon, {padding: [170, 50, 30, 150], constrainResolution: false});
}, false); }, false);
const zoomtoswitzerlandconstrained = var zoomtoswitzerlandconstrained =
document.getElementById('zoomtoswitzerlandconstrained'); document.getElementById('zoomtoswitzerlandconstrained');
zoomtoswitzerlandconstrained.addEventListener('click', function() { zoomtoswitzerlandconstrained.addEventListener('click', function() {
const feature = source.getFeatures()[0]; var feature = source.getFeatures()[0];
const polygon = /** @type {module:ol/geom/SimpleGeometry~SimpleGeometry} */ (feature.getGeometry()); var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
view.fit(polygon, {padding: [170, 50, 30, 150]}); view.fit(polygon, {padding: [170, 50, 30, 150]});
}, false); }, false);
const zoomtoswitzerlandnearest = var zoomtoswitzerlandnearest =
document.getElementById('zoomtoswitzerlandnearest'); document.getElementById('zoomtoswitzerlandnearest');
zoomtoswitzerlandnearest.addEventListener('click', function() { zoomtoswitzerlandnearest.addEventListener('click', function() {
const feature = source.getFeatures()[0]; var feature = source.getFeatures()[0];
const polygon = /** @type {module:ol/geom/SimpleGeometry~SimpleGeometry} */ (feature.getGeometry()); var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
view.fit(polygon, {padding: [170, 50, 30, 150], nearest: true}); view.fit(polygon, {padding: [170, 50, 30, 150], nearest: true});
}, false); }, false);
const zoomtolausanne = document.getElementById('zoomtolausanne'); var zoomtolausanne = document.getElementById('zoomtolausanne');
zoomtolausanne.addEventListener('click', function() { zoomtolausanne.addEventListener('click', function() {
const feature = source.getFeatures()[1]; var feature = source.getFeatures()[1];
const point = /** @type {module:ol/geom/SimpleGeometry~SimpleGeometry} */ (feature.getGeometry()); var point = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
view.fit(point, {padding: [170, 50, 30, 150], minResolution: 50}); view.fit(point, {padding: [170, 50, 30, 150], minResolution: 50});
}, false); }, false);
const centerlausanne = document.getElementById('centerlausanne'); var centerlausanne = document.getElementById('centerlausanne');
centerlausanne.addEventListener('click', function() { centerlausanne.addEventListener('click', function() {
const feature = source.getFeatures()[1]; var feature = source.getFeatures()[1];
const point = /** @type {module:ol/geom/Point~Point} */ (feature.getGeometry()); var point = /** @type {ol.geom.Point} */ (feature.getGeometry());
const size = /** @type {ol.Size} */ (map.getSize()); var size = /** @type {ol.Size} */ (map.getSize());
view.centerOn(point.getCoordinates(), size, [570, 500]); view.centerOn(point.getCoordinates(), size, [570, 500]);
}, false); }, false);
+37 -37
View File
@@ -1,58 +1,58 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import Cluster from '../src/ol/source/Cluster.js'; goog.require('ol.source.Cluster');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
import Text from '../src/ol/style/Text.js'; goog.require('ol.style.Text');
const distance = document.getElementById('distance'); var distance = document.getElementById('distance');
const count = 20000; var count = 20000;
const features = new Array(count); var features = new Array(count);
const e = 4500000; var e = 4500000;
for (let i = 0; i < count; ++i) { for (var i = 0; i < count; ++i) {
const coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
features[i] = new Feature(new Point(coordinates)); features[i] = new ol.Feature(new ol.geom.Point(coordinates));
} }
const source = new VectorSource({ var source = new ol.source.Vector({
features: features features: features
}); });
const clusterSource = new Cluster({ var clusterSource = new ol.source.Cluster({
distance: parseInt(distance.value, 10), distance: parseInt(distance.value, 10),
source: source source: source
}); });
const styleCache = {}; var styleCache = {};
const clusters = new VectorLayer({ var clusters = new ol.layer.Vector({
source: clusterSource, source: clusterSource,
style: function(feature) { style: function(feature) {
const size = feature.get('features').length; var size = feature.get('features').length;
let style = styleCache[size]; var style = styleCache[size];
if (!style) { if (!style) {
style = new Style({ style = new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: 10, radius: 10,
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#fff' color: '#fff'
}), }),
fill: new Fill({ fill: new ol.style.Fill({
color: '#3399CC' color: '#3399CC'
}) })
}), }),
text: new Text({ text: new ol.style.Text({
text: size.toString(), text: size.toString(),
fill: new Fill({ fill: new ol.style.Fill({
color: '#fff' color: '#fff'
}) })
}) })
@@ -63,14 +63,14 @@ const clusters = new VectorLayer({
} }
}); });
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, clusters], layers: [raster, clusters],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
+48 -48
View File
@@ -1,23 +1,23 @@
// NOCOMPILE // NOCOMPILE
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import ImageLayer from '../src/ol/layer/Image.js'; goog.require('ol.layer.Image');
import RasterSource from '../src/ol/source/Raster.js'; goog.require('ol.source.Raster');
import Stamen from '../src/ol/source/Stamen.js'; goog.require('ol.source.Stamen');
/** /**
* 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; var Xn = 0.950470;
const Yn = 1; var Yn = 1;
const Zn = 1.088830; var Zn = 1.088830;
const t0 = 4 / 29; var t0 = 4 / 29;
const t1 = 6 / 29; var t1 = 6 / 29;
const t2 = 3 * t1 * t1; var t2 = 3 * t1 * t1;
const t3 = t1 * t1 * t1; var t3 = t1 * t1 * t1;
const twoPi = 2 * Math.PI; var twoPi = 2 * Math.PI;
/** /**
@@ -26,23 +26,23 @@ const twoPi = 2 * Math.PI;
* @return {Array.<number>} A pixel in HCL space. * @return {Array.<number>} A pixel in HCL space.
*/ */
function rgb2hcl(pixel) { function rgb2hcl(pixel) {
const red = rgb2xyz(pixel[0]); var red = rgb2xyz(pixel[0]);
const green = rgb2xyz(pixel[1]); var green = rgb2xyz(pixel[1]);
const blue = rgb2xyz(pixel[2]); var blue = rgb2xyz(pixel[2]);
const x = xyz2lab( var 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( var y = xyz2lab(
(0.2126729 * red + 0.7151522 * green + 0.0721750 * blue) / Yn); (0.2126729 * red + 0.7151522 * green + 0.0721750 * blue) / Yn);
const z = xyz2lab( var z = xyz2lab(
(0.0193339 * red + 0.1191920 * green + 0.9503041 * blue) / Zn); (0.0193339 * red + 0.1191920 * green + 0.9503041 * blue) / Zn);
const l = 116 * y - 16; var l = 116 * y - 16;
const a = 500 * (x - y); var a = 500 * (x - y);
const b = 200 * (y - z); var b = 200 * (y - z);
const c = Math.sqrt(a * a + b * b); var c = Math.sqrt(a * a + b * b);
let h = Math.atan2(b, a); var h = Math.atan2(b, a);
if (h < 0) { if (h < 0) {
h += twoPi; h += twoPi;
} }
@@ -61,16 +61,16 @@ function rgb2hcl(pixel) {
* @return {Array.<number>} A pixel in RGB space. * @return {Array.<number>} A pixel in RGB space.
*/ */
function hcl2rgb(pixel) { function hcl2rgb(pixel) {
const h = pixel[0]; var h = pixel[0];
const c = pixel[1]; var c = pixel[1];
const l = pixel[2]; var l = pixel[2];
const a = Math.cos(h) * c; var a = Math.cos(h) * c;
const b = Math.sin(h) * c; var b = Math.sin(h) * c;
let y = (l + 16) / 116; var y = (l + 16) / 116;
let x = isNaN(a) ? y : y + a / 500; var x = isNaN(a) ? y : y + a / 500;
let z = isNaN(b) ? y : y - b / 200; var z = isNaN(b) ? y : y - b / 200;
y = Yn * lab2xyz(y); y = Yn * lab2xyz(y);
x = Xn * lab2xyz(x); x = Xn * lab2xyz(x);
@@ -100,15 +100,15 @@ function xyz2rgb(x) {
12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
} }
const raster = new RasterSource({ var raster = new ol.source.Raster({
sources: [new Stamen({ sources: [new ol.source.Stamen({
layer: 'watercolor', layer: 'watercolor',
transition: 0 transition: 0
})], })],
operation: function(pixels, data) { operation: function(pixels, data) {
const hcl = rgb2hcl(pixels[0]); var hcl = rgb2hcl(pixels[0]);
let h = hcl[0] + Math.PI * data.hue / 180; var h = hcl[0] + Math.PI * data.hue / 180;
if (h < 0) { if (h < 0) {
h += twoPi; h += twoPi;
} else if (h > twoPi) { } else if (h > twoPi) {
@@ -139,33 +139,33 @@ const raster = new RasterSource({
} }
}); });
const controls = {}; var controls = {};
raster.on('beforeoperations', function(event) { raster.on('beforeoperations', function(event) {
const data = event.data; var data = event.data;
for (const id in controls) { for (var id in controls) {
data[id] = Number(controls[id].value); data[id] = Number(controls[id].value);
} }
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new ImageLayer({ new ol.layer.Image({
source: raster source: raster
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 2500000], center: [0, 2500000],
zoom: 2, zoom: 2,
maxZoom: 18 maxZoom: 18
}) })
}); });
const controlIds = ['hue', 'chroma', 'lightness']; var controlIds = ['hue', 'chroma', 'lightness'];
controlIds.forEach(function(id) { controlIds.forEach(function(id) {
const control = document.getElementById(id); var control = document.getElementById(id);
const output = document.getElementById(id + 'Out'); var output = document.getElementById(id + 'Out');
control.addEventListener('input', function() { control.addEventListener('input', function() {
output.innerText = control.value; output.innerText = control.value;
raster.changed(); raster.changed();
+21 -21
View File
@@ -1,17 +1,17 @@
import {inherits} from '../src/ol/index.js'; goog.require('ol');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import Control from '../src/ol/control/Control.js'; goog.require('ol.control.Control');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
/** /**
* Define a namespace for the application. * Define a namespace for the application.
*/ */
window.app = {}; window.app = {};
const app = window.app; var app = window.app;
// //
@@ -21,35 +21,35 @@ const app = window.app;
/** /**
* @constructor * @constructor
* @extends {module:ol/control/Control~Control} * @extends {ol.control.Control}
* @param {Object=} opt_options Control options. * @param {Object=} opt_options Control options.
*/ */
app.RotateNorthControl = function(opt_options) { app.RotateNorthControl = function(opt_options) {
const options = opt_options || {}; var options = opt_options || {};
const button = document.createElement('button'); var button = document.createElement('button');
button.innerHTML = 'N'; button.innerHTML = 'N';
const this_ = this; var this_ = this;
const handleRotateNorth = function() { var handleRotateNorth = function() {
this_.getMap().getView().setRotation(0); this_.getMap().getView().setRotation(0);
}; };
button.addEventListener('click', handleRotateNorth, false); button.addEventListener('click', handleRotateNorth, false);
button.addEventListener('touchstart', handleRotateNorth, false); button.addEventListener('touchstart', handleRotateNorth, false);
const element = document.createElement('div'); var element = document.createElement('div');
element.className = 'rotate-north ol-unselectable ol-control'; element.className = 'rotate-north ol-unselectable ol-control';
element.appendChild(button); element.appendChild(button);
Control.call(this, { ol.control.Control.call(this, {
element: element, element: element,
target: options.target target: options.target
}); });
}; };
inherits(app.RotateNorthControl, Control); ol.inherits(app.RotateNorthControl, ol.control.Control);
// //
@@ -57,8 +57,8 @@ inherits(app.RotateNorthControl, Control);
// //
const map = new Map({ var map = new ol.Map({
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
@@ -66,12 +66,12 @@ const map = new Map({
new app.RotateNorthControl() new app.RotateNorthControl()
]), ]),
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 3, zoom: 3,
rotation: 1 rotation: 1
+9
View File
@@ -0,0 +1,9 @@
---
layout: example.html
title: Custom Icon
shortdesc: Example using a custom attribution icon object
docs: >
This example creates a custom element for the attribution icon
tags: "icon, element"
---
<div id="map" class="map"><div id="popup"></div></div>
+27
View File
@@ -0,0 +1,27 @@
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.layer.Tile');
goog.require('ol.source.OSM');
var logoElement = document.createElement('a');
logoElement.href = 'https://www.osgeo.org/';
logoElement.target = '_blank';
var logoImage = document.createElement('img');
logoImage.src = 'https://www.osgeo.org/sites/all/themes/osgeo/logo.png';
logoElement.appendChild(logoImage);
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
}),
logo: logoElement
});
+55 -55
View File
@@ -1,26 +1,26 @@
import {inherits} from '../src/ol/index.js'; goog.require('ol');
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import LineString from '../src/ol/geom/LineString.js'; goog.require('ol.geom.LineString');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import Polygon from '../src/ol/geom/Polygon.js'; goog.require('ol.geom.Polygon');
import {defaults as defaultInteractions} from '../src/ol/interaction.js'; goog.require('ol.interaction');
import PointerInteraction from '../src/ol/interaction/Pointer.js'; goog.require('ol.interaction.Pointer');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import TileJSON from '../src/ol/source/TileJSON.js'; goog.require('ol.source.TileJSON');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Icon from '../src/ol/style/Icon.js'; goog.require('ol.style.Icon');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
/** /**
* Define a namespace for the application. * Define a namespace for the application.
*/ */
const app = {}; var app = {};
/** /**
@@ -29,7 +29,7 @@ const app = {};
*/ */
app.Drag = function() { app.Drag = function() {
PointerInteraction.call(this, { ol.interaction.Pointer.call(this, {
handleDownEvent: app.Drag.prototype.handleDownEvent, handleDownEvent: app.Drag.prototype.handleDownEvent,
handleDragEvent: app.Drag.prototype.handleDragEvent, handleDragEvent: app.Drag.prototype.handleDragEvent,
handleMoveEvent: app.Drag.prototype.handleMoveEvent, handleMoveEvent: app.Drag.prototype.handleMoveEvent,
@@ -49,7 +49,7 @@ app.Drag = function() {
this.cursor_ = 'pointer'; this.cursor_ = 'pointer';
/** /**
* @type {module:ol/Feature~Feature} * @type {ol.Feature}
* @private * @private
*/ */
this.feature_ = null; this.feature_ = null;
@@ -61,20 +61,20 @@ app.Drag = function() {
this.previousCursor_ = undefined; this.previousCursor_ = undefined;
}; };
inherits(app.Drag, PointerInteraction); ol.inherits(app.Drag, ol.interaction.Pointer);
/** /**
* @param {module:ol/MapBrowserEvent~MapBrowserEvent} evt Map browser event. * @param {ol.MapBrowserEvent} evt Map browser event.
* @return {boolean} `true` to start the drag sequence. * @return {boolean} `true` to start the drag sequence.
*/ */
app.Drag.prototype.handleDownEvent = function(evt) { app.Drag.prototype.handleDownEvent = function(evt) {
const map = evt.map; var map = evt.map;
const feature = map.forEachFeatureAtPixel(evt.pixel, var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) { function(feature) {
return feature; return feature;
}); });
if (feature) { if (feature) {
this.coordinate_ = evt.coordinate; this.coordinate_ = evt.coordinate;
@@ -86,13 +86,13 @@ app.Drag.prototype.handleDownEvent = function(evt) {
/** /**
* @param {module:ol/MapBrowserEvent~MapBrowserEvent} evt Map browser event. * @param {ol.MapBrowserEvent} evt Map browser event.
*/ */
app.Drag.prototype.handleDragEvent = function(evt) { app.Drag.prototype.handleDragEvent = function(evt) {
const deltaX = evt.coordinate[0] - this.coordinate_[0]; var deltaX = evt.coordinate[0] - this.coordinate_[0];
const deltaY = evt.coordinate[1] - this.coordinate_[1]; var deltaY = evt.coordinate[1] - this.coordinate_[1];
const geometry = this.feature_.getGeometry(); var geometry = this.feature_.getGeometry();
geometry.translate(deltaX, deltaY); geometry.translate(deltaX, deltaY);
this.coordinate_[0] = evt.coordinate[0]; this.coordinate_[0] = evt.coordinate[0];
@@ -101,16 +101,16 @@ app.Drag.prototype.handleDragEvent = function(evt) {
/** /**
* @param {module:ol/MapBrowserEvent~MapBrowserEvent} evt Event. * @param {ol.MapBrowserEvent} evt Event.
*/ */
app.Drag.prototype.handleMoveEvent = function(evt) { app.Drag.prototype.handleMoveEvent = function(evt) {
if (this.cursor_) { if (this.cursor_) {
const map = evt.map; var map = evt.map;
const feature = map.forEachFeatureAtPixel(evt.pixel, var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) { function(feature) {
return feature; return feature;
}); });
const element = evt.map.getTargetElement(); var element = evt.map.getTargetElement();
if (feature) { if (feature) {
if (element.style.cursor != this.cursor_) { if (element.style.cursor != this.cursor_) {
this.previousCursor_ = element.style.cursor; this.previousCursor_ = element.style.cursor;
@@ -134,48 +134,48 @@ app.Drag.prototype.handleUpEvent = function() {
}; };
const pointFeature = new Feature(new Point([0, 0])); var pointFeature = new ol.Feature(new ol.geom.Point([0, 0]));
const lineFeature = new Feature( var lineFeature = new ol.Feature(
new LineString([[-1e7, 1e6], [-1e6, 3e6]])); new ol.geom.LineString([[-1e7, 1e6], [-1e6, 3e6]]));
const polygonFeature = new Feature( var polygonFeature = new ol.Feature(
new Polygon([[[-3e6, -1e6], [-3e6, 1e6], new ol.geom.Polygon([[[-3e6, -1e6], [-3e6, 1e6],
[-1e6, 1e6], [-1e6, -1e6], [-3e6, -1e6]]])); [-1e6, 1e6], [-1e6, -1e6], [-3e6, -1e6]]]));
const map = new Map({ var map = new ol.Map({
interactions: defaultInteractions().extend([new app.Drag()]), interactions: ol.interaction.defaults().extend([new app.Drag()]),
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new TileJSON({ source: new ol.source.TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure' url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure'
}) })
}), }),
new VectorLayer({ new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
features: [pointFeature, lineFeature, polygonFeature] features: [pointFeature, lineFeature, polygonFeature]
}), }),
style: new Style({ style: new ol.style.Style({
image: new Icon(/** @type {olx.style.IconOptions} */ ({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 46], anchor: [0.5, 46],
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 ol.style.Stroke({
width: 3, width: 3,
color: [255, 0, 0, 1] color: [255, 0, 0, 1]
}), }),
fill: new Fill({ fill: new ol.style.Fill({
color: [0, 0, 255, 0.6] color: [0, 0, 255, 0.6]
}) })
}) })
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
+2 -2
View File
@@ -6,7 +6,7 @@ docs: >
<p>The example loads TopoJSON geometries and uses d3 (<code>d3.geo.path</code>) to render these geometries to a canvas element that is then used as the image of an OpenLayers image layer.</p> <p>The example loads TopoJSON geometries and uses d3 (<code>d3.geo.path</code>) to render these geometries to a canvas element that is then used as the image of an OpenLayers image layer.</p>
tags: "d3" tags: "d3"
resources: resources:
- https://unpkg.com/d3@4.12.0/build/d3.js - https://d3js.org/d3.v3.min.js
- https://unpkg.com/topojson@3.0.2/dist/topojson.js - https://d3js.org/topojson.v1.min.js
--- ---
<div id="map" class="map"></div> <div id="map" class="map"></div>
+44 -40
View File
@@ -1,25 +1,25 @@
// NOCOMPILE // NOCOMPILE
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {getWidth, getCenter} from '../src/ol/extent.js'; goog.require('ol.extent');
import ImageLayer from '../src/ol/layer/Image.js'; goog.require('ol.layer.Image');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import {fromLonLat, toLonLat} from '../src/ol/proj.js'; goog.require('ol.proj');
import ImageCanvasSource from '../src/ol/source/ImageCanvas.js'; goog.require('ol.source.ImageCanvas');
import Stamen from '../src/ol/source/Stamen.js'; goog.require('ol.source.Stamen');
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new Stamen({ source: new ol.source.Stamen({
layer: 'watercolor' layer: 'watercolor'
}) })
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: fromLonLat([-97, 38]), center: ol.proj.fromLonLat([-97, 38]),
zoom: 4 zoom: 4
}) })
}); });
@@ -29,7 +29,7 @@ const map = new Map({
* Load the topojson data and create an ol.layer.Image for that data. * Load the topojson data and create an ol.layer.Image for that data.
*/ */
d3.json('data/topojson/us.json', function(error, us) { d3.json('data/topojson/us.json', function(error, us) {
const features = topojson.feature(us, us.objects.counties); var features = topojson.feature(us, us.objects.counties);
/** /**
* This function uses d3 to render the topojson features to a canvas. * This function uses d3 to render the topojson features to a canvas.
@@ -37,51 +37,55 @@ d3.json('data/topojson/us.json', function(error, us) {
* @param {number} resolution Resolution. * @param {number} resolution Resolution.
* @param {number} pixelRatio Pixel ratio. * @param {number} pixelRatio Pixel ratio.
* @param {ol.Size} size Size. * @param {ol.Size} size Size.
* @param {module:ol/proj/Projection~Projection} projection Projection. * @param {ol.proj.Projection} projection Projection.
* @return {HTMLCanvasElement} A canvas element. * @return {HTMLCanvasElement} A canvas element.
*/ */
const canvasFunction = function(extent, resolution, pixelRatio, size, projection) { var canvasFunction = function(extent, resolution, pixelRatio,
const canvasWidth = size[0]; size, projection) {
const canvasHeight = size[1]; var canvasWidth = size[0];
var canvasHeight = size[1];
const canvas = d3.select(document.createElement('canvas')); var canvas = d3.select(document.createElement('canvas'));
canvas.attr('width', canvasWidth).attr('height', canvasHeight); canvas.attr('width', canvasWidth).attr('height', canvasHeight);
const context = canvas.node().getContext('2d'); var context = canvas.node().getContext('2d');
const d3Projection = d3.geoMercator().scale(1).translate([0, 0]); var d3Projection = d3.geo.mercator().scale(1).translate([0, 0]);
let d3Path = d3.geoPath().projection(d3Projection); var d3Path = d3.geo.path().projection(d3Projection);
const pixelBounds = d3Path.bounds(features); var pixelBounds = d3Path.bounds(features);
const pixelBoundsWidth = pixelBounds[1][0] - pixelBounds[0][0]; var pixelBoundsWidth = pixelBounds[1][0] - pixelBounds[0][0];
const pixelBoundsHeight = pixelBounds[1][1] - pixelBounds[0][1]; var pixelBoundsHeight = pixelBounds[1][1] - pixelBounds[0][1];
const geoBounds = d3.geoBounds(features); var geoBounds = d3.geo.bounds(features);
const geoBoundsLeftBottom = fromLonLat(geoBounds[0], projection); var geoBoundsLeftBottom = ol.proj.transform(
const geoBoundsRightTop = fromLonLat(geoBounds[1], projection); geoBounds[0], 'EPSG:4326', projection);
let geoBoundsWidth = geoBoundsRightTop[0] - geoBoundsLeftBottom[0]; var geoBoundsRightTop = ol.proj.transform(
geoBounds[1], 'EPSG:4326', projection);
var geoBoundsWidth = geoBoundsRightTop[0] - geoBoundsLeftBottom[0];
if (geoBoundsWidth < 0) { if (geoBoundsWidth < 0) {
geoBoundsWidth += getWidth(projection.getExtent()); geoBoundsWidth += ol.extent.getWidth(projection.getExtent());
} }
const geoBoundsHeight = geoBoundsRightTop[1] - geoBoundsLeftBottom[1]; var geoBoundsHeight = geoBoundsRightTop[1] - geoBoundsLeftBottom[1];
const widthResolution = geoBoundsWidth / pixelBoundsWidth; var widthResolution = geoBoundsWidth / pixelBoundsWidth;
const heightResolution = geoBoundsHeight / pixelBoundsHeight; var heightResolution = geoBoundsHeight / pixelBoundsHeight;
const r = Math.max(widthResolution, heightResolution); var r = Math.max(widthResolution, heightResolution);
const scale = r / (resolution / pixelRatio); var scale = r / (resolution / pixelRatio);
const center = toLonLat(getCenter(extent), projection); var center = ol.proj.transform(ol.extent.getCenter(extent),
projection, 'EPSG:4326');
d3Projection.scale(scale).center(center) d3Projection.scale(scale).center(center)
.translate([canvasWidth / 2, canvasHeight / 2]); .translate([canvasWidth / 2, canvasHeight / 2]);
d3Path = d3Path.projection(d3Projection).context(context); d3Path = d3Path.projection(d3Projection).context(context);
d3Path(features); d3Path(features);
context.stroke(); context.stroke();
return canvas.node(); return canvas[0][0];
}; };
const layer = new ImageLayer({ var layer = new ol.layer.Image({
source: new ImageCanvasSource({ source: new ol.source.ImageCanvas({
canvasFunction: canvasFunction, canvasFunction: canvasFunction,
projection: 'EPSG:3857' projection: 'EPSG:3857'
}) })
+21 -17
View File
@@ -1,23 +1,27 @@
// NOCOMPILE // NOCOMPILE
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import {toRadians} from '../src/ol/math.js'; goog.require('ol.math');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.proj');
goog.require('ol.source.OSM');
const view = new View({ var projection = ol.proj.get('EPSG:3857');
var view = new ol.View({
center: [0, 0], center: [0, 0],
projection: projection,
extent: projection.getExtent(),
zoom: 2 zoom: 2
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
target: 'map', target: 'map',
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
@@ -30,15 +34,15 @@ function el(id) {
} }
const gn = new GyroNorm(); var gn = new GyroNorm();
gn.init().then(function() { gn.init().then(function() {
gn.start(function(event) { gn.start(function(event) {
const center = view.getCenter(); var center = view.getCenter();
const resolution = view.getResolution(); var resolution = view.getResolution();
const alpha = toRadians(event.do.beta); var alpha = ol.math.toRadians(event.do.beta);
const beta = toRadians(event.do.beta); var beta = ol.math.toRadians(event.do.beta);
const gamma = toRadians(event.do.gamma); var gamma = ol.math.toRadians(event.do.gamma);
el('alpha').innerText = alpha + ' [rad]'; el('alpha').innerText = alpha + ' [rad]';
el('beta').innerText = beta + ' [rad]'; el('beta').innerText = beta + ' [rad]';
+56 -56
View File
@@ -1,81 +1,81 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import GPX from '../src/ol/format/GPX.js'; goog.require('ol.format.GPX');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import IGC from '../src/ol/format/IGC.js'; goog.require('ol.format.IGC');
import KML from '../src/ol/format/KML.js'; goog.require('ol.format.KML');
import TopoJSON from '../src/ol/format/TopoJSON.js'; goog.require('ol.format.TopoJSON');
import {defaults as defaultInteractions} from '../src/ol/interaction.js'; goog.require('ol.interaction');
import DragAndDrop from '../src/ol/interaction/DragAndDrop.js'; goog.require('ol.interaction.DragAndDrop');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import BingMaps from '../src/ol/source/BingMaps.js'; goog.require('ol.source.BingMaps');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const defaultStyle = { var defaultStyle = {
'Point': new Style({ 'Point': new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255,255,0,0.5)' color: 'rgba(255,255,0,0.5)'
}), }),
radius: 5, radius: 5,
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#ff0', color: '#ff0',
width: 1 width: 1
}) })
}) })
}), }),
'LineString': new Style({ 'LineString': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#f00', color: '#f00',
width: 3 width: 3
}) })
}), }),
'Polygon': new Style({ 'Polygon': new ol.style.Style({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(0,255,255,0.5)' color: 'rgba(0,255,255,0.5)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#0ff', color: '#0ff',
width: 1 width: 1
}) })
}), }),
'MultiPoint': new Style({ 'MultiPoint': new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255,0,255,0.5)' color: 'rgba(255,0,255,0.5)'
}), }),
radius: 5, radius: 5,
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#f0f', color: '#f0f',
width: 1 width: 1
}) })
}) })
}), }),
'MultiLineString': new Style({ 'MultiLineString': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#0f0', color: '#0f0',
width: 3 width: 3
}) })
}), }),
'MultiPolygon': new Style({ 'MultiPolygon': new ol.style.Style({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(0,0,255,0.5)' color: 'rgba(0,0,255,0.5)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#00f', color: '#00f',
width: 1 width: 1
}) })
}) })
}; };
const styleFunction = function(feature, resolution) { var styleFunction = function(feature, resolution) {
const featureStyleFunction = feature.getStyleFunction(); var featureStyleFunction = feature.getStyleFunction();
if (featureStyleFunction) { if (featureStyleFunction) {
return featureStyleFunction.call(feature, resolution); return featureStyleFunction.call(feature, resolution);
} else { } else {
@@ -83,38 +83,38 @@ const styleFunction = function(feature, resolution) {
} }
}; };
const dragAndDropInteraction = new DragAndDrop({ var dragAndDropInteraction = new ol.interaction.DragAndDrop({
formatConstructors: [ formatConstructors: [
GPX, ol.format.GPX,
GeoJSON, ol.format.GeoJSON,
IGC, ol.format.IGC,
KML, ol.format.KML,
TopoJSON ol.format.TopoJSON
] ]
}); });
const map = new Map({ var map = new ol.Map({
interactions: defaultInteractions().extend([dragAndDropInteraction]), interactions: ol.interaction.defaults().extend([dragAndDropInteraction]),
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new BingMaps({ source: new ol.source.BingMaps({
imagerySet: 'Aerial', imagerySet: 'Aerial',
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'
}) })
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.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({ var vectorSource = new ol.source.Vector({
features: event.features features: event.features
}); });
map.addLayer(new VectorLayer({ map.addLayer(new ol.layer.Vector({
renderMode: 'image', renderMode: 'image',
source: vectorSource, source: vectorSource,
style: styleFunction style: styleFunction
@@ -122,14 +122,14 @@ dragAndDropInteraction.on('addfeatures', function(event) {
map.getView().fit(vectorSource.getExtent()); map.getView().fit(vectorSource.getExtent());
}); });
const displayFeatureInfo = function(pixel) { var displayFeatureInfo = function(pixel) {
const features = []; var features = [];
map.forEachFeatureAtPixel(pixel, function(feature) { map.forEachFeatureAtPixel(pixel, function(feature) {
features.push(feature); features.push(feature);
}); });
if (features.length > 0) { if (features.length > 0) {
const info = []; var info = [];
let i, ii; var i, ii;
for (i = 0, ii = features.length; i < ii; ++i) { for (i = 0, ii = features.length; i < ii; ++i) {
info.push(features[i].get('name')); info.push(features[i].get('name'));
} }
@@ -143,7 +143,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
const pixel = map.getEventPixel(evt.originalEvent); var pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel); displayFeatureInfo(pixel);
}); });
+56 -56
View File
@@ -1,81 +1,81 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import GPX from '../src/ol/format/GPX.js'; goog.require('ol.format.GPX');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import IGC from '../src/ol/format/IGC.js'; goog.require('ol.format.IGC');
import KML from '../src/ol/format/KML.js'; goog.require('ol.format.KML');
import TopoJSON from '../src/ol/format/TopoJSON.js'; goog.require('ol.format.TopoJSON');
import {defaults as defaultInteractions} from '../src/ol/interaction.js'; goog.require('ol.interaction');
import DragAndDrop from '../src/ol/interaction/DragAndDrop.js'; goog.require('ol.interaction.DragAndDrop');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import BingMaps from '../src/ol/source/BingMaps.js'; goog.require('ol.source.BingMaps');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const defaultStyle = { var defaultStyle = {
'Point': new Style({ 'Point': new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255,255,0,0.5)' color: 'rgba(255,255,0,0.5)'
}), }),
radius: 5, radius: 5,
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#ff0', color: '#ff0',
width: 1 width: 1
}) })
}) })
}), }),
'LineString': new Style({ 'LineString': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#f00', color: '#f00',
width: 3 width: 3
}) })
}), }),
'Polygon': new Style({ 'Polygon': new ol.style.Style({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(0,255,255,0.5)' color: 'rgba(0,255,255,0.5)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#0ff', color: '#0ff',
width: 1 width: 1
}) })
}), }),
'MultiPoint': new Style({ 'MultiPoint': new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255,0,255,0.5)' color: 'rgba(255,0,255,0.5)'
}), }),
radius: 5, radius: 5,
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#f0f', color: '#f0f',
width: 1 width: 1
}) })
}) })
}), }),
'MultiLineString': new Style({ 'MultiLineString': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#0f0', color: '#0f0',
width: 3 width: 3
}) })
}), }),
'MultiPolygon': new Style({ 'MultiPolygon': new ol.style.Style({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(0,0,255,0.5)' color: 'rgba(0,0,255,0.5)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#00f', color: '#00f',
width: 1 width: 1
}) })
}) })
}; };
const styleFunction = function(feature, resolution) { var styleFunction = function(feature, resolution) {
const featureStyleFunction = feature.getStyleFunction(); var featureStyleFunction = feature.getStyleFunction();
if (featureStyleFunction) { if (featureStyleFunction) {
return featureStyleFunction.call(feature, resolution); return featureStyleFunction.call(feature, resolution);
} else { } else {
@@ -83,52 +83,52 @@ const styleFunction = function(feature, resolution) {
} }
}; };
const dragAndDropInteraction = new DragAndDrop({ var dragAndDropInteraction = new ol.interaction.DragAndDrop({
formatConstructors: [ formatConstructors: [
GPX, ol.format.GPX,
GeoJSON, ol.format.GeoJSON,
IGC, ol.format.IGC,
KML, ol.format.KML,
TopoJSON ol.format.TopoJSON
] ]
}); });
const map = new Map({ var map = new ol.Map({
interactions: defaultInteractions().extend([dragAndDropInteraction]), interactions: ol.interaction.defaults().extend([dragAndDropInteraction]),
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new BingMaps({ source: new ol.source.BingMaps({
imagerySet: 'Aerial', imagerySet: 'Aerial',
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'
}) })
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.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({ var vectorSource = new ol.source.Vector({
features: event.features features: event.features
}); });
map.addLayer(new VectorLayer({ map.addLayer(new ol.layer.Vector({
source: vectorSource, source: vectorSource,
style: styleFunction style: styleFunction
})); }));
map.getView().fit(vectorSource.getExtent()); map.getView().fit(vectorSource.getExtent());
}); });
const displayFeatureInfo = function(pixel) { var displayFeatureInfo = function(pixel) {
const features = []; var features = [];
map.forEachFeatureAtPixel(pixel, function(feature) { map.forEachFeatureAtPixel(pixel, function(feature) {
features.push(feature); features.push(feature);
}); });
if (features.length > 0) { if (features.length > 0) {
const info = []; var info = [];
let i, ii; var i, ii;
for (i = 0, ii = features.length; i < ii; ++i) { for (i = 0, ii = features.length; i < ii; ++i) {
info.push(features[i].get('name')); info.push(features[i].get('name'));
} }
@@ -142,7 +142,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
const pixel = map.getEventPixel(evt.originalEvent); var pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel); displayFeatureInfo(pixel);
}); });
+12 -12
View File
@@ -1,22 +1,22 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultInteractions} from '../src/ol/interaction.js'; goog.require('ol.interaction');
import DragRotateAndZoom from '../src/ol/interaction/DragRotateAndZoom.js'; goog.require('ol.interaction.DragRotateAndZoom');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
const map = new Map({ var map = new ol.Map({
interactions: defaultInteractions().extend([ interactions: ol.interaction.defaults().extend([
new DragRotateAndZoom() new ol.interaction.DragRotateAndZoom()
]), ]),
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
+29 -29
View File
@@ -1,63 +1,63 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Draw from '../src/ol/interaction/Draw.js'; goog.require('ol.interaction.Draw');
import Modify from '../src/ol/interaction/Modify.js'; goog.require('ol.interaction.Modify');
import Snap from '../src/ol/interaction/Snap.js'; goog.require('ol.interaction.Snap');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}); });
const source = new VectorSource(); var source = new ol.source.Vector();
const vector = new VectorLayer({ var vector = new ol.layer.Vector({
source: source, source: source,
style: new Style({ style: new ol.style.Style({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)' color: 'rgba(255, 255, 255, 0.2)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#ffcc33', color: '#ffcc33',
width: 2 width: 2
}), }),
image: new CircleStyle({ image: new ol.style.Circle({
radius: 7, radius: 7,
fill: new Fill({ fill: new ol.style.Fill({
color: '#ffcc33' color: '#ffcc33'
}) })
}) })
}) })
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [-11000000, 4600000], center: [-11000000, 4600000],
zoom: 4 zoom: 4
}) })
}); });
const modify = new Modify({source: source}); var modify = new ol.interaction.Modify({source: source});
map.addInteraction(modify); map.addInteraction(modify);
let draw, snap; // global so we can remove them later var draw, snap; // global so we can remove them later
const typeSelect = document.getElementById('type'); var typeSelect = document.getElementById('type');
function addInteractions() { function addInteractions() {
draw = new Draw({ draw = new ol.interaction.Draw({
source: source, source: source,
type: typeSelect.value type: typeSelect.value
}); });
map.addInteraction(draw); map.addInteraction(draw);
snap = new Snap({source: source}); snap = new ol.interaction.Snap({source: source});
map.addInteraction(snap); map.addInteraction(snap);
} }
+17 -17
View File
@@ -1,37 +1,37 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Draw from '../src/ol/interaction/Draw.js'; goog.require('ol.interaction.Draw');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}); });
const source = new VectorSource({wrapX: false}); var source = new ol.source.Vector({wrapX: false});
const vector = new VectorLayer({ var vector = new ol.layer.Vector({
source: source source: source
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [-11000000, 4600000], center: [-11000000, 4600000],
zoom: 4 zoom: 4
}) })
}); });
const typeSelect = document.getElementById('type'); var typeSelect = document.getElementById('type');
let draw; // global so we can remove it later var draw; // global so we can remove it later
function addInteraction() { function addInteraction() {
const value = typeSelect.value; var value = typeSelect.value;
if (value !== 'None') { if (value !== 'None') {
draw = new Draw({ draw = new ol.interaction.Draw({
source: source, source: source,
type: typeSelect.value type: typeSelect.value
}); });
+17 -17
View File
@@ -1,37 +1,37 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Draw from '../src/ol/interaction/Draw.js'; goog.require('ol.interaction.Draw');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}); });
const source = new VectorSource({wrapX: false}); var source = new ol.source.Vector({wrapX: false});
const vector = new VectorLayer({ var vector = new ol.layer.Vector({
source: source source: source
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [-11000000, 4600000], center: [-11000000, 4600000],
zoom: 4 zoom: 4
}) })
}); });
const typeSelect = document.getElementById('type'); var typeSelect = document.getElementById('type');
let draw; // global so we can remove it later var draw; // global so we can remove it later
function addInteraction() { function addInteraction() {
const value = typeSelect.value; var value = typeSelect.value;
if (value !== 'None') { if (value !== 'None') {
draw = new Draw({ draw = new ol.interaction.Draw({
source: source, source: source,
type: typeSelect.value, type: typeSelect.value,
freehand: true freehand: true
+35 -35
View File
@@ -1,63 +1,63 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Polygon from '../src/ol/geom/Polygon.js'; goog.require('ol.geom.Polygon');
import Draw, {createRegularPolygon, createBox} from '../src/ol/interaction/Draw.js'; goog.require('ol.interaction.Draw');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}); });
const source = new VectorSource({wrapX: false}); var source = new ol.source.Vector({wrapX: false});
const vector = new VectorLayer({ var vector = new ol.layer.Vector({
source: source source: source
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [-11000000, 4600000], center: [-11000000, 4600000],
zoom: 4 zoom: 4
}) })
}); });
const typeSelect = document.getElementById('type'); var typeSelect = document.getElementById('type');
let draw; // global so we can remove it later var draw; // global so we can remove it later
function addInteraction() { function addInteraction() {
let value = typeSelect.value; var value = typeSelect.value;
if (value !== 'None') { if (value !== 'None') {
let geometryFunction; var geometryFunction;
if (value === 'Square') { if (value === 'Square') {
value = 'Circle'; value = 'Circle';
geometryFunction = createRegularPolygon(4); geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
} else if (value === 'Box') { } else if (value === 'Box') {
value = 'Circle'; value = 'Circle';
geometryFunction = createBox(); geometryFunction = ol.interaction.Draw.createBox();
} else if (value === 'Star') { } else if (value === 'Star') {
value = 'Circle'; value = 'Circle';
geometryFunction = function(coordinates, geometry) { geometryFunction = function(coordinates, geometry) {
if (!geometry) { if (!geometry) {
geometry = new Polygon(null); geometry = new ol.geom.Polygon(null);
} }
const center = coordinates[0]; var center = coordinates[0];
const last = coordinates[1]; var last = coordinates[1];
const dx = center[0] - last[0]; var dx = center[0] - last[0];
const dy = center[1] - last[1]; var dy = center[1] - last[1];
const radius = Math.sqrt(dx * dx + dy * dy); var radius = Math.sqrt(dx * dx + dy * dy);
const rotation = Math.atan2(dy, dx); var rotation = Math.atan2(dy, dx);
const newCoordinates = []; var newCoordinates = [];
const numPoints = 12; var numPoints = 12;
for (let i = 0; i < numPoints; ++i) { for (var i = 0; i < numPoints; ++i) {
const angle = rotation + i * 2 * Math.PI / numPoints; var angle = rotation + i * 2 * Math.PI / numPoints;
const fraction = i % 2 === 0 ? 1 : 0.5; var fraction = i % 2 === 0 ? 1 : 0.5;
const offsetX = radius * fraction * Math.cos(angle); var offsetX = radius * fraction * Math.cos(angle);
const offsetY = radius * fraction * Math.sin(angle); var offsetY = radius * fraction * Math.sin(angle);
newCoordinates.push([center[0] + offsetX, center[1] + offsetY]); newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
} }
newCoordinates.push(newCoordinates[0].slice()); newCoordinates.push(newCoordinates[0].slice());
@@ -65,7 +65,7 @@ function addInteraction() {
return geometry; return geometry;
}; };
} }
draw = new Draw({ draw = new ol.interaction.Draw({
source: source, source: source,
type: value, type: value,
geometryFunction: geometryFunction geometryFunction: geometryFunction
+39 -39
View File
@@ -1,74 +1,74 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import MultiPoint from '../src/ol/geom/MultiPoint.js'; goog.require('ol.geom.MultiPoint');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
}); });
const imageStyle = new Style({ var imageStyle = new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: 5, radius: 5,
snapToPixel: false, snapToPixel: false,
fill: new Fill({color: 'yellow'}), fill: new ol.style.Fill({color: 'yellow'}),
stroke: new Stroke({color: 'red', width: 1}) stroke: new ol.style.Stroke({color: 'red', width: 1})
}) })
}); });
const headInnerImageStyle = new Style({ var headInnerImageStyle = new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: 2, radius: 2,
snapToPixel: false, snapToPixel: false,
fill: new Fill({color: 'blue'}) fill: new ol.style.Fill({color: 'blue'})
}) })
}); });
const headOuterImageStyle = new Style({ var headOuterImageStyle = new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: 5, radius: 5,
snapToPixel: false, snapToPixel: false,
fill: new Fill({color: 'black'}) fill: new ol.style.Fill({color: 'black'})
}) })
}); });
const n = 200; var n = 200;
const omegaTheta = 30000; // Rotation period in ms var omegaTheta = 30000; // Rotation period in ms
const R = 7e6; var R = 7e6;
const r = 2e6; var r = 2e6;
const p = 2e6; var p = 2e6;
map.on('postcompose', function(event) { map.on('postcompose', function(event) {
const vectorContext = event.vectorContext; var vectorContext = event.vectorContext;
const frameState = event.frameState; var frameState = event.frameState;
const theta = 2 * Math.PI * frameState.time / omegaTheta; var theta = 2 * Math.PI * frameState.time / omegaTheta;
const coordinates = []; var coordinates = [];
let i; var i;
for (i = 0; i < n; ++i) { for (i = 0; i < n; ++i) {
const t = theta + 2 * Math.PI * i / n; var t = theta + 2 * Math.PI * i / n;
const x = (R + r) * Math.cos(t) + p * Math.cos((R + r) * t / r); var 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); var y = (R + r) * Math.sin(t) + p * Math.sin((R + r) * t / r);
coordinates.push([x, y]); coordinates.push([x, y]);
} }
vectorContext.setStyle(imageStyle); vectorContext.setStyle(imageStyle);
vectorContext.drawGeometry(new MultiPoint(coordinates)); vectorContext.drawGeometry(new ol.geom.MultiPoint(coordinates));
const headPoint = new Point(coordinates[coordinates.length - 1]); var headPoint = new ol.geom.Point(coordinates[coordinates.length - 1]);
vectorContext.setStyle(headOuterImageStyle); vectorContext.setStyle(headOuterImageStyle);
vectorContext.drawGeometry(headPoint); vectorContext.drawGeometry(headPoint);
+60 -61
View File
@@ -1,37 +1,37 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {createEmpty, getWidth, getHeight, extend} from '../src/ol/extent.js'; goog.require('ol.extent');
import KML from '../src/ol/format/KML.js'; goog.require('ol.format.KML');
import {defaults as defaultInteractions} from '../src/ol/interaction.js'; goog.require('ol.interaction');
import Select from '../src/ol/interaction/Select.js'; goog.require('ol.interaction.Select');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import Cluster from '../src/ol/source/Cluster.js'; goog.require('ol.source.Cluster');
import Stamen from '../src/ol/source/Stamen.js'; goog.require('ol.source.Stamen');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import RegularShape from '../src/ol/style/RegularShape.js'; goog.require('ol.style.RegularShape');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
import Text from '../src/ol/style/Text.js'; goog.require('ol.style.Text');
const earthquakeFill = new Fill({ var earthquakeFill = new ol.style.Fill({
color: 'rgba(255, 153, 0, 0.8)' color: 'rgba(255, 153, 0, 0.8)'
}); });
const earthquakeStroke = new Stroke({ var earthquakeStroke = new ol.style.Stroke({
color: 'rgba(255, 204, 0, 0.2)', color: 'rgba(255, 204, 0, 0.2)',
width: 1 width: 1
}); });
const textFill = new Fill({ var textFill = new ol.style.Fill({
color: '#fff' color: '#fff'
}); });
const textStroke = new Stroke({ var textStroke = new ol.style.Stroke({
color: 'rgba(0, 0, 0, 0.6)', color: 'rgba(0, 0, 0, 0.6)',
width: 3 width: 3
}); });
const invisibleFill = new Fill({ var invisibleFill = new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.01)' color: 'rgba(255, 255, 255, 0.01)'
}); });
@@ -39,13 +39,13 @@ function createEarthquakeStyle(feature) {
// 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a
// standards-violating <magnitude> tag in each Placemark. We extract it // standards-violating <magnitude> tag in each Placemark. We extract it
// from the Placemark's name instead. // from the Placemark's name instead.
const name = feature.get('name'); var name = feature.get('name');
const magnitude = parseFloat(name.substr(2)); var magnitude = parseFloat(name.substr(2));
const radius = 5 + 20 * (magnitude - 5); var radius = 5 + 20 * (magnitude - 5);
return new Style({ return new ol.style.Style({
geometry: feature.getGeometry(), geometry: feature.getGeometry(),
image: new RegularShape({ image: new ol.style.RegularShape({
radius1: radius, radius1: radius,
radius2: 3, radius2: 3,
points: 5, points: 5,
@@ -56,78 +56,77 @@ function createEarthquakeStyle(feature) {
}); });
} }
let maxFeatureCount; var maxFeatureCount, vector;
let vector = null; function calculateClusterInfo(resolution) {
const calculateClusterInfo = function(resolution) {
maxFeatureCount = 0; maxFeatureCount = 0;
const features = vector.getSource().getFeatures(); var features = vector.getSource().getFeatures();
let feature, radius; var feature, radius;
for (let i = features.length - 1; i >= 0; --i) { for (var i = features.length - 1; i >= 0; --i) {
feature = features[i]; feature = features[i];
const originalFeatures = feature.get('features'); var originalFeatures = feature.get('features');
const extent = createEmpty(); var extent = ol.extent.createEmpty();
let j, jj; var j, jj;
for (j = 0, jj = originalFeatures.length; j < jj; ++j) { for (j = 0, jj = originalFeatures.length; j < jj; ++j) {
extend(extent, originalFeatures[j].getGeometry().getExtent()); ol.extent.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 * (ol.extent.getWidth(extent) + ol.extent.getHeight(extent)) /
resolution; resolution;
feature.set('radius', radius); feature.set('radius', radius);
} }
}; }
let currentResolution; var currentResolution;
function styleFunction(feature, resolution) { function styleFunction(feature, resolution) {
if (resolution != currentResolution) { if (resolution != currentResolution) {
calculateClusterInfo(resolution); calculateClusterInfo(resolution);
currentResolution = resolution; currentResolution = resolution;
} }
let style; var style;
const size = feature.get('features').length; var size = feature.get('features').length;
if (size > 1) { if (size > 1) {
style = new Style({ style = new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: feature.get('radius'), radius: feature.get('radius'),
fill: new Fill({ fill: new ol.style.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 ol.style.Text({
text: size.toString(), text: size.toString(),
fill: textFill, fill: textFill,
stroke: textStroke stroke: textStroke
}) })
}); });
} else { } else {
const originalFeature = feature.get('features')[0]; var originalFeature = feature.get('features')[0];
style = createEarthquakeStyle(originalFeature); style = createEarthquakeStyle(originalFeature);
} }
return style; return style;
} }
function selectStyleFunction(feature) { function selectStyleFunction(feature) {
const styles = [new Style({ var styles = [new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: feature.get('radius'), radius: feature.get('radius'),
fill: invisibleFill fill: invisibleFill
}) })
})]; })];
const originalFeatures = feature.get('features'); var originalFeatures = feature.get('features');
let originalFeature; var originalFeature;
for (let i = originalFeatures.length - 1; i >= 0; --i) { for (var i = originalFeatures.length - 1; i >= 0; --i) {
originalFeature = originalFeatures[i]; originalFeature = originalFeatures[i];
styles.push(createEarthquakeStyle(originalFeature)); styles.push(createEarthquakeStyle(originalFeature));
} }
return styles; return styles;
} }
vector = new VectorLayer({ vector = new ol.layer.Vector({
source: new Cluster({ source: new ol.source.Cluster({
distance: 40, distance: 40,
source: new VectorSource({ source: new ol.source.Vector({
url: 'data/kml/2012_Earthquakes_Mag5.kml', url: 'data/kml/2012_Earthquakes_Mag5.kml',
format: new KML({ format: new ol.format.KML({
extractStyles: false extractStyles: false
}) })
}) })
@@ -135,15 +134,15 @@ vector = new VectorLayer({
style: styleFunction style: styleFunction
}); });
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new Stamen({ source: new ol.source.Stamen({
layer: 'toner' layer: 'toner'
}) })
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
interactions: defaultInteractions().extend([new Select({ interactions: ol.interaction.defaults().extend([new ol.interaction.Select({
condition: function(evt) { condition: function(evt) {
return evt.type == 'pointermove' || return evt.type == 'pointermove' ||
evt.type == 'singleclick'; evt.type == 'singleclick';
@@ -151,7 +150,7 @@ const map = new Map({
style: selectStyleFunction style: selectStyleFunction
})]), })]),
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
+40 -39
View File
@@ -1,46 +1,47 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import KML from '../src/ol/format/KML.js'; goog.require('ol.format.KML');
import Polygon from '../src/ol/geom/Polygon.js'; goog.require('ol.geom.Polygon');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import {toContext} from '../src/ol/render.js'; goog.require('ol.render');
import Stamen from '../src/ol/source/Stamen.js'; goog.require('ol.source.Stamen');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Icon from '../src/ol/style/Icon.js'; goog.require('ol.style.Icon');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const symbol = [[0, 0], [4, 2], [6, 0], [10, 5], [6, 3], [4, 5], [0, 0]]; var symbol = [[0, 0], [4, 2], [6, 0], [10, 5], [6, 3], [4, 5], [0, 0]];
let scale; var scale;
const scaleFunction = function(coordinate) { var scaleFunction = function(coordinate) {
return [coordinate[0] * scale, coordinate[1] * scale]; return [coordinate[0] * scale, coordinate[1] * scale];
}; };
const styleCache = {}; var styleCache = {};
const styleFunction = function(feature) { var styleFunction = function(feature) {
// 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a
// standards-violating <magnitude> tag in each Placemark. We extract it from // standards-violating <magnitude> tag in each Placemark. We extract it from
// the Placemark's name instead. // the Placemark's name instead.
const name = feature.get('name'); var name = feature.get('name');
const magnitude = parseFloat(name.substr(2)); var magnitude = parseFloat(name.substr(2));
const size = parseInt(10 + 40 * (magnitude - 5), 10); var size = parseInt(10 + 40 * (magnitude - 5), 10);
scale = size / 10; scale = size / 10;
let style = styleCache[size]; var style = styleCache[size];
if (!style) { if (!style) {
const canvas = /** @type {HTMLCanvasElement} */ (document.createElement('canvas')); var canvas =
const vectorContext = toContext( /** @type {HTMLCanvasElement} */ (document.createElement('canvas'));
/** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d')), var vectorContext = ol.render.toContext(
{size: [size, size], pixelRatio: 1}); /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d')),
vectorContext.setStyle(new Style({ {size: [size, size], pixelRatio: 1});
fill: new Fill({color: 'rgba(255, 153, 0, 0.4)'}), vectorContext.setStyle(new ol.style.Style({
stroke: new Stroke({color: 'rgba(255, 204, 0, 0.2)', width: 2}) fill: new ol.style.Fill({color: 'rgba(255, 153, 0, 0.4)'}),
stroke: new ol.style.Stroke({color: 'rgba(255, 204, 0, 0.2)', width: 2})
})); }));
vectorContext.drawGeometry(new Polygon([symbol.map(scaleFunction)])); vectorContext.drawGeometry(new ol.geom.Polygon([symbol.map(scaleFunction)]));
style = new Style({ style = new ol.style.Style({
image: new Icon({ image: new ol.style.Icon({
img: canvas, img: canvas,
imgSize: [size, size], imgSize: [size, size],
rotation: 1.2 rotation: 1.2
@@ -51,26 +52,26 @@ const styleFunction = function(feature) {
return style; return style;
}; };
const vector = new VectorLayer({ var vector = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
url: 'data/kml/2012_Earthquakes_Mag5.kml', url: 'data/kml/2012_Earthquakes_Mag5.kml',
format: new KML({ format: new ol.format.KML({
extractStyles: false extractStyles: false
}) })
}), }),
style: styleFunction style: styleFunction
}); });
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new Stamen({ source: new ol.source.Stamen({
layer: 'toner' layer: 'toner'
}) })
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
+13 -13
View File
@@ -1,14 +1,14 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import ScaleLine from '../src/ol/control/ScaleLine.js'; goog.require('ol.control.ScaleLine');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import TileWMS from '../src/ol/source/TileWMS.js'; goog.require('ol.source.TileWMS');
const layers = [ var layers = [
new TileLayer({ new ol.layer.Tile({
source: new TileWMS({ source: new ol.source.TileWMS({
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',
@@ -18,15 +18,15 @@ const layers = [
}) })
]; ];
const map = new Map({ var map = new ol.Map({
controls: defaultControls().extend([ controls: ol.control.defaults().extend([
new ScaleLine({ new ol.control.ScaleLine({
units: 'degrees' units: 'degrees'
}) })
]), ]),
layers: layers, layers: layers,
target: 'map', target: 'map',
view: new View({ view: new ol.View({
projection: 'EPSG:4326', projection: 'EPSG:4326',
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
+17 -17
View File
@@ -1,33 +1,33 @@
// NOCOMPILE // NOCOMPILE
// this example uses FileSaver.js for which we don't have an externs file. // this example uses FileSaver.js for which we don't have an externs file.
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}), }),
new VectorLayer({ new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new ol.format.GeoJSON()
}) })
}) })
], ],
target: 'map', target: 'map',
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
}), }),
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
@@ -35,7 +35,7 @@ const map = new Map({
document.getElementById('export-png').addEventListener('click', function() { document.getElementById('export-png').addEventListener('click', function() {
map.once('postcompose', function(event) { map.once('postcompose', function(event) {
const canvas = event.context.canvas; var canvas = event.context.canvas;
if (navigator.msSaveBlob) { if (navigator.msSaveBlob) {
navigator.msSaveBlob(canvas.msToBlob(), 'map.png'); navigator.msSaveBlob(canvas.msToBlob(), 'map.png');
} else { } else {
+58 -73
View File
@@ -1,48 +1,47 @@
// NOCOMPILE // NOCOMPILE
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import WKT from '../src/ol/format/WKT.js'; goog.require('ol.format.WKT');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import {unByKey} from '../src/ol/Observable.js'; goog.require('ol.source.OSM');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.Vector');
import VectorSource from '../src/ol/source/Vector.js';
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}); });
const format = new WKT(); var format = new ol.format.WKT();
const feature = format.readFeature( var 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({ var vector = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
features: [feature] features: [feature]
}) })
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
}), }),
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
}); });
const dims = { var dims = {
a0: [1189, 841], a0: [1189, 841],
a1: [841, 594], a1: [841, 594],
a2: [594, 420], a2: [594, 420],
@@ -51,75 +50,61 @@ const dims = {
a5: [210, 148] a5: [210, 148]
}; };
let loading = 0; var loading = 0;
let loaded = 0; var loaded = 0;
const exportButton = document.getElementById('export-pdf'); var 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; var format = document.getElementById('format').value;
const resolution = document.getElementById('resolution').value; var resolution = document.getElementById('resolution').value;
const dim = dims[format]; var dim = dims[format];
const width = Math.round(dim[0] * resolution / 25.4); var width = Math.round(dim[0] * resolution / 25.4);
const height = Math.round(dim[1] * resolution / 25.4); var height = Math.round(dim[1] * resolution / 25.4);
const size = /** @type {ol.Size} */ (map.getSize()); var size = /** @type {ol.Size} */ (map.getSize());
const extent = map.getView().calculateExtent(size); var extent = map.getView().calculateExtent(size);
const source = raster.getSource(); var source = raster.getSource();
const tileLoadStart = function() { var tileLoadStart = function() {
++loading; ++loading;
}; };
let timer; var tileLoadEnd = function() {
let keys = []; ++loaded;
if (loading === loaded) {
function tileLoadEndFactory(canvas) { var canvas = this;
return () => { window.setTimeout(function() {
++loaded; loading = 0;
if (timer) { loaded = 0;
clearTimeout(timer); var data = canvas.toDataURL('image/png');
timer = null; var pdf = new jsPDF('landscape', undefined, format);
} pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]);
if (loading === loaded) { pdf.save('map.pdf');
timer = window.setTimeout(() => { source.un('tileloadstart', tileLoadStart);
loading = 0; source.un('tileloadend', tileLoadEnd, canvas);
loaded = 0; source.un('tileloaderror', tileLoadEnd, canvas);
const data = canvas.toDataURL('image/jpeg'); map.setSize(size);
const pdf = new jsPDF('landscape', undefined, format); map.getView().fit(extent);
pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]); map.renderSync();
pdf.save('map.pdf'); exportButton.disabled = false;
keys.forEach(unByKey); document.body.style.cursor = 'auto';
keys = []; }, 100);
map.setSize(size); }
map.getView().fit(extent, {size}); };
map.renderSync();
exportButton.disabled = false;
document.body.style.cursor = 'auto';
}, 500);
}
};
}
map.once('postcompose', function(event) { map.once('postcompose', function(event) {
const canvas = event.context.canvas; source.on('tileloadstart', tileLoadStart);
const tileLoadEnd = tileLoadEndFactory(canvas); source.on('tileloadend', tileLoadEnd, event.context.canvas);
keys = [ source.on('tileloaderror', tileLoadEnd, event.context.canvas);
source.on('tileloadstart', tileLoadStart),
source.on('tileloadend', tileLoadEnd),
source.on('tileloaderror', tileLoadEnd)
];
tileLoadEnd();
}); });
const printSize = [width, height]; map.setSize([width, height]);
map.setSize(printSize); map.getView().fit(extent);
map.getView().fit(extent, {size: printSize});
loaded = -1;
map.renderSync(); map.renderSync();
}, false); }, false);
+18 -18
View File
@@ -1,36 +1,36 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {platformModifierKeyOnly} from '../src/ol/events/condition.js'; goog.require('ol.events.condition');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import ExtentInteraction from '../src/ol/interaction/Extent.js'; goog.require('ol.interaction.Extent');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
const vectorSource = new VectorSource({ var vectorSource = new ol.source.Vector({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new ol.format.GeoJSON()
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}), }),
new VectorLayer({ new ol.layer.Vector({
source: vectorSource source: vectorSource
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
}); });
const extent = new ExtentInteraction({ var extent = new ol.interaction.Extent({
condition: platformModifierKeyOnly condition: ol.events.condition.platformModifierKeyOnly
}); });
map.addInteraction(extent); map.addInteraction(extent);
extent.setActive(false); extent.setActive(false);
+42 -40
View File
@@ -1,76 +1,77 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import {unByKey} from '../src/ol/Observable.js'; goog.require('ol.Observable');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import {easeOut} from '../src/ol/easing.js'; goog.require('ol.easing');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import {fromLonLat} from '../src/ol/proj.js'; goog.require('ol.proj');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM({ source: new ol.source.OSM({
wrapX: false wrapX: false
}) })
}) })
], ],
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
}), }),
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1
}) })
}); });
const source = new VectorSource({ var source = new ol.source.Vector({
wrapX: false wrapX: false
}); });
const vector = new VectorLayer({ var vector = new ol.layer.Vector({
source: source source: source
}); });
map.addLayer(vector); map.addLayer(vector);
function addRandomFeature() { function addRandomFeature() {
const x = Math.random() * 360 - 180; var x = Math.random() * 360 - 180;
const y = Math.random() * 180 - 90; var y = Math.random() * 180 - 90;
const geom = new Point(fromLonLat([x, y])); var geom = new ol.geom.Point(ol.proj.transform([x, y],
const feature = new Feature(geom); 'EPSG:4326', 'EPSG:3857'));
var feature = new ol.Feature(geom);
source.addFeature(feature); source.addFeature(feature);
} }
const duration = 3000; var duration = 3000;
function flash(feature) { function flash(feature) {
const start = new Date().getTime(); var start = new Date().getTime();
const listenerKey = map.on('postcompose', animate); var listenerKey;
function animate(event) { function animate(event) {
const vectorContext = event.vectorContext; var vectorContext = event.vectorContext;
const frameState = event.frameState; var frameState = event.frameState;
const flashGeom = feature.getGeometry().clone(); var flashGeom = feature.getGeometry().clone();
const elapsed = frameState.time - start; var elapsed = frameState.time - start;
const elapsedRatio = elapsed / duration; var elapsedRatio = elapsed / duration;
// radius will be 5 at start and 30 at end. // radius will be 5 at start and 30 at end.
const radius = easeOut(elapsedRatio) * 25 + 5; var radius = ol.easing.easeOut(elapsedRatio) * 25 + 5;
const opacity = easeOut(1 - elapsedRatio); var opacity = ol.easing.easeOut(1 - elapsedRatio);
const style = new Style({ var style = new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: radius, radius: radius,
snapToPixel: false, snapToPixel: false,
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'rgba(255, 0, 0, ' + opacity + ')', color: 'rgba(255, 0, 0, ' + opacity + ')',
width: 0.25 + opacity width: 0.25 + opacity
}) })
@@ -80,12 +81,13 @@ function flash(feature) {
vectorContext.setStyle(style); vectorContext.setStyle(style);
vectorContext.drawGeometry(flashGeom); vectorContext.drawGeometry(flashGeom);
if (elapsed > duration) { if (elapsed > duration) {
unByKey(listenerKey); ol.Observable.unByKey(listenerKey);
return; return;
} }
// tell OpenLayers to continue postcompose animation // tell OpenLayers to continue postcompose animation
map.render(); map.render();
} }
listenerKey = map.on('postcompose', animate);
} }
source.on('addfeature', function(e) { source.on('addfeature', function(e) {
+55 -55
View File
@@ -1,21 +1,21 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Polyline from '../src/ol/format/Polyline.js'; goog.require('ol.format.Polyline');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import BingMaps from '../src/ol/source/BingMaps.js'; goog.require('ol.source.BingMaps');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Icon from '../src/ol/style/Icon.js'; goog.require('ol.style.Icon');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
// This long string is placed here due to jsFiddle limitations. // This long string is placed here due to jsFiddle limitations.
// It is usually loaded with AJAX. // It is usually loaded with AJAX.
const polyline = [ var polyline = [
'hldhx@lnau`BCG_EaC??cFjAwDjF??uBlKMd@}@z@??aC^yk@z_@se@b[wFdE??wFfE}N', 'hldhx@lnau`BCG_EaC??cFjAwDjF??uBlKMd@}@z@??aC^yk@z_@se@b[wFdE??wFfE}N',
'fIoGxB_I\\gG}@eHoCyTmPqGaBaHOoD\\??yVrGotA|N??o[N_STiwAtEmHGeHcAkiA}^', 'fIoGxB_I\\gG}@eHoCyTmPqGaBaHOoD\\??yVrGotA|N??o[N_STiwAtEmHGeHcAkiA}^',
'aMyBiHOkFNoI`CcVvM??gG^gF_@iJwC??eCcA]OoL}DwFyCaCgCcCwDcGwHsSoX??wI_E', 'aMyBiHOkFNoI`CcVvM??gG^gF_@iJwC??eCcA]OoL}DwFyCaCgCcCwDcGwHsSoX??wI_E',
@@ -57,64 +57,64 @@ const polyline = [
'~@ym@yjA??a@cFd@kBrCgDbAUnAcBhAyAdk@et@??kF}D??OL' '~@ym@yjA??a@cFd@kBrCgDbAUnAcBhAyAdk@et@??kF}D??OL'
].join(''); ].join('');
const route = /** @type {module:ol/geom/LineString~LineString} */ (new Polyline({ var route = /** @type {ol.geom.LineString} */ (new ol.format.Polyline({
factor: 1e6 factor: 1e6
}).readGeometry(polyline, { }).readGeometry(polyline, {
dataProjection: 'EPSG:4326', dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857' featureProjection: 'EPSG:3857'
})); }));
const routeCoords = route.getCoordinates(); var routeCoords = route.getCoordinates();
const routeLength = routeCoords.length; var routeLength = routeCoords.length;
const routeFeature = new Feature({ var routeFeature = new ol.Feature({
type: 'route', type: 'route',
geometry: route geometry: route
}); });
const geoMarker = new Feature({ var geoMarker = new ol.Feature({
type: 'geoMarker', type: 'geoMarker',
geometry: new Point(routeCoords[0]) geometry: new ol.geom.Point(routeCoords[0])
}); });
const startMarker = new Feature({ var startMarker = new ol.Feature({
type: 'icon', type: 'icon',
geometry: new Point(routeCoords[0]) geometry: new ol.geom.Point(routeCoords[0])
}); });
const endMarker = new Feature({ var endMarker = new ol.Feature({
type: 'icon', type: 'icon',
geometry: new Point(routeCoords[routeLength - 1]) geometry: new ol.geom.Point(routeCoords[routeLength - 1])
}); });
const styles = { var styles = {
'route': new Style({ 'route': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
width: 6, color: [237, 212, 0, 0.8] width: 6, color: [237, 212, 0, 0.8]
}) })
}), }),
'icon': new Style({ 'icon': new ol.style.Style({
image: new Icon({ image: new ol.style.Icon({
anchor: [0.5, 1], anchor: [0.5, 1],
src: 'data/icon.png' src: 'data/icon.png'
}) })
}), }),
'geoMarker': new Style({ 'geoMarker': new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: 7, radius: 7,
snapToPixel: false, snapToPixel: false,
fill: new Fill({color: 'black'}), fill: new ol.style.Fill({color: 'black'}),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'white', width: 2 color: 'white', width: 2
}) })
}) })
}) })
}; };
let animating = false; var animating = false;
let speed, now; var speed, now;
const speedInput = document.getElementById('speed'); var speedInput = document.getElementById('speed');
const startButton = document.getElementById('start-animation'); var startButton = document.getElementById('start-animation');
const vectorLayer = new VectorLayer({ var vectorLayer = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
features: [routeFeature, geoMarker, startMarker, endMarker] features: [routeFeature, geoMarker, startMarker, endMarker]
}), }),
style: function(feature) { style: function(feature) {
@@ -126,19 +126,19 @@ const vectorLayer = new VectorLayer({
} }
}); });
const center = [-5639523.95, -3501274.52]; var center = [-5639523.95, -3501274.52];
const map = new Map({ var map = new ol.Map({
target: document.getElementById('map'), target: document.getElementById('map'),
loadTilesWhileAnimating: true, loadTilesWhileAnimating: true,
view: new View({ view: new ol.View({
center: center, center: center,
zoom: 10, zoom: 10,
minZoom: 2, minZoom: 2,
maxZoom: 19 maxZoom: 19
}), }),
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new BingMaps({ source: new ol.source.BingMaps({
imagerySet: 'AerialWithLabels', imagerySet: 'AerialWithLabels',
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'
}) })
@@ -147,23 +147,23 @@ const map = new Map({
] ]
}); });
const moveFeature = function(event) { var moveFeature = function(event) {
const vectorContext = event.vectorContext; var vectorContext = event.vectorContext;
const frameState = event.frameState; var frameState = event.frameState;
if (animating) { if (animating) {
const elapsedTime = frameState.time - now; var 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); var index = Math.round(speed * elapsedTime / 1000);
if (index >= routeLength) { if (index >= routeLength) {
stopAnimation(true); stopAnimation(true);
return; return;
} }
const currentPoint = new Point(routeCoords[index]); var currentPoint = new ol.geom.Point(routeCoords[index]);
const feature = new Feature(currentPoint); var feature = new ol.Feature(currentPoint);
vectorContext.drawFeature(feature, styles.geoMarker); vectorContext.drawFeature(feature, styles.geoMarker);
} }
// tell OpenLayers to continue the postcompose animation // tell OpenLayers to continue the postcompose animation
@@ -196,9 +196,9 @@ function stopAnimation(ended) {
startButton.textContent = 'Start Animation'; startButton.textContent = 'Start Animation';
// if animation cancelled set the marker at the beginning // if animation cancelled set the marker at the beginning
const coord = ended ? routeCoords[routeLength - 1] : routeCoords[0]; var coord = ended ? routeCoords[routeLength - 1] : routeCoords[0];
/** @type {module:ol/geom/Point~Point} */ (geoMarker.getGeometry()) /** @type {ol.geom.Point} */ (geoMarker.getGeometry())
.setCoordinates(coord); .setCoordinates(coord);
//remove listener //remove listener
map.un('postcompose', moveFeature); map.un('postcompose', moveFeature);
} }
+70 -69
View File
@@ -1,63 +1,102 @@
// NOCOMPILE // NOCOMPILE
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import LineString from '../src/ol/geom/LineString.js'; goog.require('ol.geom.LineString');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import Stamen from '../src/ol/source/Stamen.js'; goog.require('ol.proj');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Stamen');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.source.Vector');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Stroke');
goog.require('ol.style.Style');
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new Stamen({ source: new ol.source.Stamen({
layer: 'toner' layer: 'toner'
}) })
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
}); });
const style = new Style({ var style = new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#EAE911', color: '#EAE911',
width: 2 width: 2
}) })
}); });
const flightsSource = new VectorSource({ var flightsSource;
var addLater = function(feature, timeout) {
window.setTimeout(function() {
feature.set('start', new Date().getTime());
flightsSource.addFeature(feature);
}, timeout);
};
var pointsPerMs = 0.1;
var animateFlights = function(event) {
var vectorContext = event.vectorContext;
var frameState = event.frameState;
vectorContext.setStyle(style);
var features = flightsSource.getFeatures();
for (var i = 0; i < features.length; i++) {
var feature = features[i];
if (!feature.get('finished')) {
// only draw the lines for which the animation has not finished yet
var coords = feature.getGeometry().getCoordinates();
var elapsedTime = frameState.time - feature.get('start');
var elapsedPoints = elapsedTime * pointsPerMs;
if (elapsedPoints >= coords.length) {
feature.set('finished', true);
}
var maxIndex = Math.min(elapsedPoints, coords.length);
var currentLine = new ol.geom.LineString(coords.slice(0, maxIndex));
// directly draw the line with the vector context
vectorContext.drawGeometry(currentLine);
}
}
// tell OpenLayers to continue the animation
map.render();
};
flightsSource = new ol.source.Vector({
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'; var 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; var flightsData = json.flights;
for (let i = 0; i < flightsData.length; i++) { for (var i = 0; i < flightsData.length; i++) {
const flight = flightsData[i]; var flight = flightsData[i];
const from = flight[0]; var from = flight[0];
const to = flight[1]; var to = flight[1];
// create an arc circle between the two locations // create an arc circle between the two locations
const arcGenerator = new arc.GreatCircle( var 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}); var arcLine = arcGenerator.Arc(100, {offset: 10});
if (arcLine.geometries.length === 1) { if (arcLine.geometries.length === 1) {
const line = new LineString(arcLine.geometries[0].coords); var line = new ol.geom.LineString(arcLine.geometries[0].coords);
line.transform('EPSG:4326', 'EPSG:3857'); line.transform(ol.proj.get('EPSG:4326'), ol.proj.get('EPSG:3857'));
const feature = new Feature({ var feature = new ol.Feature({
geometry: line, geometry: line,
finished: false finished: false
}); });
@@ -71,7 +110,7 @@ const flightsSource = new VectorSource({
} }
}); });
const flightsLayer = new VectorLayer({ var flightsLayer = new ol.layer.Vector({
source: flightsSource, source: flightsSource,
style: function(feature) { style: function(feature) {
// if the animation is still active for a feature, do not // if the animation is still active for a feature, do not
@@ -83,42 +122,4 @@ const flightsLayer = new VectorLayer({
} }
} }
}); });
map.addLayer(flightsLayer); map.addLayer(flightsLayer);
const pointsPerMs = 0.1;
function animateFlights(event) {
const vectorContext = event.vectorContext;
const frameState = event.frameState;
vectorContext.setStyle(style);
const features = flightsSource.getFeatures();
for (let i = 0; i < features.length; i++) {
const feature = features[i];
if (!feature.get('finished')) {
// only draw the lines for which the animation has not finished yet
const coords = feature.getGeometry().getCoordinates();
const elapsedTime = frameState.time - feature.get('start');
const elapsedPoints = elapsedTime * pointsPerMs;
if (elapsedPoints >= coords.length) {
feature.set('finished', true);
}
const maxIndex = Math.min(elapsedPoints, coords.length);
const currentLine = new LineString(coords.slice(0, maxIndex));
// directly draw the line with the vector context
vectorContext.drawGeometry(currentLine);
}
}
// tell OpenLayers to continue the animation
map.render();
}
function addLater(feature, timeout) {
window.setTimeout(function() {
feature.set('start', new Date().getTime());
flightsSource.addFeature(feature);
}, timeout);
}
+40 -40
View File
@@ -1,76 +1,76 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import LineString from '../src/ol/geom/LineString.js'; goog.require('ol.geom.LineString');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
const radius = 10e6; var radius = 10e6;
const cos30 = Math.cos(Math.PI / 6); var cos30 = Math.cos(Math.PI / 6);
const sin30 = Math.sin(Math.PI / 6); var sin30 = Math.sin(Math.PI / 6);
const rise = radius * sin30; var rise = radius * sin30;
const run = radius * cos30; var run = radius * cos30;
const triangle = new LineString([ var triangle = new ol.geom.LineString([
[0, radius], [run, -rise], [-run, -rise], [0, radius] [0, radius], [run, -rise], [-run, -rise], [0, radius]
]); ]);
const feature = new Feature(triangle); var feature = new ol.Feature(triangle);
const layer = new VectorLayer({ var layer = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
features: [feature] features: [feature]
}) })
}); });
const map = new Map({ var map = new ol.Map({
layers: [layer], layers: [layer],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1
}) })
}); });
function makeFractal(depth) { function makeFractal(depth) {
const geometry = triangle.clone(); var geometry = triangle.clone();
const graph = coordsToGraph(geometry.getCoordinates()); var graph = coordsToGraph(geometry.getCoordinates());
for (let i = 0; i < depth; ++i) { for (var i = 0; i < depth; ++i) {
let node = graph; var node = graph;
while (node.next) { while (node.next) {
const next = node.next; var next = node.next;
injectNodes(node); injectNodes(node);
node = next; node = next;
} }
} }
const coordinates = graphToCoords(graph); var coordinates = graphToCoords(graph);
document.getElementById('count').innerHTML = coordinates.length; document.getElementById('count').innerHTML = coordinates.length;
geometry.setCoordinates(coordinates); geometry.setCoordinates(coordinates);
feature.setGeometry(geometry); feature.setGeometry(geometry);
} }
function injectNodes(startNode) { function injectNodes(startNode) {
const endNode = startNode.next; var endNode = startNode.next;
const start = startNode.point; var start = startNode.point;
const end = startNode.next.point; var end = startNode.next.point;
const dx = end[0] - start[0]; var dx = end[0] - start[0];
const dy = end[1] - start[1]; var dy = end[1] - start[1];
// first point at 1/3 along the segment // first point at 1/3 along the segment
const firstNode = { var 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); var r = Math.sqrt(dx * dx + dy * dy) / (2 * cos30);
const a = Math.atan2(dy, dx) + Math.PI / 6; var a = Math.atan2(dy, dx) + Math.PI / 6;
const secondNode = { var 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 = { var thirdNode = {
point: [end[0] - dx / 3, end[1] - dy / 3] point: [end[0] - dx / 3, end[1] - dy / 3]
}; };
@@ -82,11 +82,11 @@ function injectNodes(startNode) {
function coordsToGraph(coordinates) { function coordsToGraph(coordinates) {
const graph = { var graph = {
point: coordinates[0] point: coordinates[0]
}; };
const length = coordinates.length; var length = coordinates.length;
for (let level = 0, node = graph; level < length - 1; ++level) { for (var level = 0, node = graph; level < length - 1; ++level) {
node.next = { node.next = {
point: coordinates[level + 1] point: coordinates[level + 1]
}; };
@@ -96,20 +96,20 @@ function coordsToGraph(coordinates) {
} }
function graphToCoords(graph) { function graphToCoords(graph) {
const coordinates = [graph.point]; var coordinates = [graph.point];
for (let node = graph, i = 1; node.next; node = node.next, ++i) { for (var node = graph, i = 1; node.next; node = node.next, ++i) {
coordinates[i] = node.next.point; coordinates[i] = node.next.point;
} }
return coordinates; return coordinates;
} }
const depthInput = document.getElementById('depth'); var depthInput = document.getElementById('depth');
function update() { function update() {
makeFractal(Number(depthInput.value)); makeFractal(Number(depthInput.value));
} }
let updateTimer; var updateTimer;
/** /**
+16 -16
View File
@@ -1,23 +1,23 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import FullScreen from '../src/ol/control/FullScreen.js'; goog.require('ol.control.FullScreen');
import {defaults as defaultInteractions} from '../src/ol/interaction.js'; goog.require('ol.interaction');
import DragRotateAndZoom from '../src/ol/interaction/DragRotateAndZoom.js'; goog.require('ol.interaction.DragRotateAndZoom');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import BingMaps from '../src/ol/source/BingMaps.js'; goog.require('ol.source.BingMaps');
const map = new Map({ var map = new ol.Map({
controls: defaultControls().extend([ controls: ol.control.defaults().extend([
new FullScreen() new ol.control.FullScreen()
]), ]),
interactions: defaultInteractions().extend([ interactions: ol.interaction.defaults().extend([
new DragRotateAndZoom() new ol.interaction.DragRotateAndZoom()
]), ]),
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new BingMaps({ source: new ol.source.BingMaps({
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5', key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5',
imagerySet: 'Aerial' imagerySet: 'Aerial'
}) })
@@ -25,7 +25,7 @@ const map = new Map({
], ],
// Use the canvas renderer because it's currently the fastest // Use the canvas renderer because it's currently the fastest
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [-33519607, 5616436], center: [-33519607, 5616436],
rotation: -Math.PI / 8, rotation: -Math.PI / 8,
zoom: 8 zoom: 8
+12 -12
View File
@@ -1,25 +1,25 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import FullScreen from '../src/ol/control/FullScreen.js'; goog.require('ol.control.FullScreen');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
const view = new View({ var view = new ol.View({
center: [-9101767, 2822912], center: [-9101767, 2822912],
zoom: 14 zoom: 14
}); });
const map = new Map({ var map = new ol.Map({
controls: defaultControls().extend([ controls: ol.control.defaults().extend([
new FullScreen({ new ol.control.FullScreen({
source: 'fullscreen' source: 'fullscreen'
}) })
]), ]),
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
target: 'map', target: 'map',
+12 -12
View File
@@ -1,23 +1,23 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import FullScreen from '../src/ol/control/FullScreen.js'; goog.require('ol.control.FullScreen');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import BingMaps from '../src/ol/source/BingMaps.js'; goog.require('ol.source.BingMaps');
const view = new View({ var view = new ol.View({
center: [-9101767, 2822912], center: [-9101767, 2822912],
zoom: 14 zoom: 14
}); });
const map = new Map({ var map = new ol.Map({
controls: defaultControls().extend([ controls: ol.control.defaults().extend([
new FullScreen() new ol.control.FullScreen()
]), ]),
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new BingMaps({ source: new ol.source.BingMaps({
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5', key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5',
imagerySet: 'Aerial' imagerySet: 'Aerial'
}) })
+30 -30
View File
@@ -1,19 +1,19 @@
// NOCOMPILE // NOCOMPILE
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorTileSource from '../src/ol/source/VectorTile.js'; goog.require('ol.source.VectorTile');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorTileLayer from '../src/ol/layer/VectorTile.js'; goog.require('ol.layer.VectorTile');
import Projection from '../src/ol/proj/Projection.js'; goog.require('ol.proj.Projection');
const replacer = function(key, value) { var replacer = function(key, value) {
if (value.geometry) { if (value.geometry) {
let type; var type;
const rawType = value.type; var rawType = value.type;
let geometry = value.geometry; var geometry = value.geometry;
if (rawType === 1) { if (rawType === 1) {
type = 'MultiPoint'; type = 'MultiPoint';
@@ -48,44 +48,44 @@ const replacer = function(key, value) {
} }
}; };
const tilePixels = new Projection({ var tilePixels = new ol.proj.Projection({
code: 'TILE_PIXELS', code: 'TILE_PIXELS',
units: 'tile-pixels' units: 'tile-pixels'
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
}); });
const url = 'data/geojson/countries.geojson'; var 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, { var tileIndex = geojsonvt(json, {
extent: 4096, extent: 4096,
debug: 1 debug: 1
}); });
const vectorSource = new VectorTileSource({ var vectorSource = new ol.source.VectorTile({
format: new GeoJSON(), format: new ol.format.GeoJSON(),
tileLoadFunction: function(tile) { tileLoadFunction: function(tile) {
const format = tile.getFormat(); var format = tile.getFormat();
const tileCoord = tile.getTileCoord(); var tileCoord = tile.getTileCoord();
const data = tileIndex.getTile(tileCoord[0], tileCoord[1], -tileCoord[2] - 1); var data = tileIndex.getTile(tileCoord[0], tileCoord[1], -tileCoord[2] - 1);
const features = format.readFeatures( var features = format.readFeatures(
JSON.stringify({ JSON.stringify({
type: 'FeatureCollection', type: 'FeatureCollection',
features: data ? data.features : [] features: data ? data.features : []
}, replacer)); }, replacer));
tile.setLoader(function() { tile.setLoader(function() {
tile.setFeatures(features); tile.setFeatures(features);
tile.setProjection(tilePixels); tile.setProjection(tilePixels);
@@ -93,7 +93,7 @@ fetch(url).then(function(response) {
}, },
url: 'data:' // arbitrary url, we don't use it in the tileLoadFunction url: 'data:' // arbitrary url, we don't use it in the tileLoadFunction
}); });
const vectorLayer = new VectorTileLayer({ var vectorLayer = new ol.layer.VectorTile({
source: vectorSource source: vectorSource
}); });
map.addLayer(vectorLayer); map.addLayer(vectorLayer);
+48 -48
View File
@@ -1,95 +1,95 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import Circle from '../src/ol/geom/Circle.js'; goog.require('ol.geom.Circle');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const image = new CircleStyle({ var image = new ol.style.Circle({
radius: 5, radius: 5,
fill: null, fill: null,
stroke: new Stroke({color: 'red', width: 1}) stroke: new ol.style.Stroke({color: 'red', width: 1})
}); });
const styles = { var styles = {
'Point': new Style({ 'Point': new ol.style.Style({
image: image image: image
}), }),
'LineString': new Style({ 'LineString': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'green', color: 'green',
width: 1 width: 1
}) })
}), }),
'MultiLineString': new Style({ 'MultiLineString': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'green', color: 'green',
width: 1 width: 1
}) })
}), }),
'MultiPoint': new Style({ 'MultiPoint': new ol.style.Style({
image: image image: image
}), }),
'MultiPolygon': new Style({ 'MultiPolygon': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'yellow', color: 'yellow',
width: 1 width: 1
}), }),
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255, 255, 0, 0.1)' color: 'rgba(255, 255, 0, 0.1)'
}) })
}), }),
'Polygon': new Style({ 'Polygon': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'blue', color: 'blue',
lineDash: [4], lineDash: [4],
width: 3 width: 3
}), }),
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)' color: 'rgba(0, 0, 255, 0.1)'
}) })
}), }),
'GeometryCollection': new Style({ 'GeometryCollection': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'magenta', color: 'magenta',
width: 2 width: 2
}), }),
fill: new Fill({ fill: new ol.style.Fill({
color: 'magenta' color: 'magenta'
}), }),
image: new CircleStyle({ image: new ol.style.Circle({
radius: 10, radius: 10,
fill: null, fill: null,
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'magenta' color: 'magenta'
}) })
}) })
}), }),
'Circle': new Style({ 'Circle': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'red', color: 'red',
width: 2 width: 2
}), }),
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.2)' color: 'rgba(255,0,0,0.2)'
}) })
}) })
}; };
const styleFunction = function(feature) { var styleFunction = function(feature) {
return styles[feature.getGeometry().getType()]; return styles[feature.getGeometry().getType()];
}; };
const geojsonObject = { var geojsonObject = {
'type': 'FeatureCollection', 'type': 'FeatureCollection',
'crs': { 'crs': {
'type': 'name', 'type': 'name',
@@ -160,31 +160,31 @@ const geojsonObject = {
}] }]
}; };
const vectorSource = new VectorSource({ var vectorSource = new ol.source.Vector({
features: (new GeoJSON()).readFeatures(geojsonObject) features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
}); });
vectorSource.addFeature(new Feature(new Circle([5e6, 7e6], 1e6))); vectorSource.addFeature(new ol.Feature(new ol.geom.Circle([5e6, 7e6], 1e6)));
const vectorLayer = new VectorLayer({ var vectorLayer = new ol.layer.Vector({
source: vectorSource, source: vectorSource,
style: styleFunction style: styleFunction
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}), }),
vectorLayer vectorLayer
], ],
target: 'map', target: 'map',
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
}), }),
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
+54 -52
View File
@@ -1,28 +1,28 @@
import Geolocation from '../src/ol/Geolocation.js'; goog.require('ol.Geolocation');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import Overlay from '../src/ol/Overlay.js'; goog.require('ol.Overlay');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import LineString from '../src/ol/geom/LineString.js'; goog.require('ol.geom.LineString');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import {fromLonLat} from '../src/ol/proj.js'; goog.require('ol.proj');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
// creating the view // creating the view
const view = new View({ var view = new ol.View({
center: fromLonLat([5.8713, 45.6452]), center: ol.proj.fromLonLat([5.8713, 45.6452]),
zoom: 19 zoom: 19
}); });
// creating the map // creating the map
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
target: 'map', target: 'map',
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
@@ -31,8 +31,8 @@ const map = new Map({
}); });
// Geolocation marker // Geolocation marker
const markerEl = document.getElementById('geolocation_marker'); var markerEl = document.getElementById('geolocation_marker');
const marker = new Overlay({ var marker = new ol.Overlay({
positioning: 'center-center', positioning: 'center-center',
element: markerEl, element: markerEl,
stopEvent: false stopEvent: false
@@ -42,11 +42,11 @@ map.addOverlay(marker);
// LineString to store the different geolocation positions. This LineString // LineString to store the different geolocation positions. This LineString
// is time aware. // is time aware.
// The Z dimension is actually used to store the rotation (heading). // The Z dimension is actually used to store the rotation (heading).
const positions = new LineString([], var positions = new ol.geom.LineString([],
/** @type {module:ol/geom/GeometryLayout~GeometryLayout} */ ('XYZM')); /** @type {ol.geom.GeometryLayout} */ ('XYZM'));
// Geolocation Control // Geolocation Control
const geolocation = new Geolocation({ var geolocation = new ol.Geolocation({
projection: view.getProjection(), projection: view.getProjection(),
trackingOptions: { trackingOptions: {
maximumAge: 10000, maximumAge: 10000,
@@ -55,25 +55,25 @@ const geolocation = new Geolocation({
} }
}); });
let deltaMean = 500; // the geolocation sampling period mean in ms var deltaMean = 500; // the geolocation sampling period mean in ms
// Listen to position changes // Listen to position changes
geolocation.on('change', function() { geolocation.on('change', function() {
const position = geolocation.getPosition(); var position = geolocation.getPosition();
const accuracy = geolocation.getAccuracy(); var accuracy = geolocation.getAccuracy();
const heading = geolocation.getHeading() || 0; var heading = geolocation.getHeading() || 0;
const speed = geolocation.getSpeed() || 0; var speed = geolocation.getSpeed() || 0;
const m = Date.now(); var m = Date.now();
addPosition(position, heading, m, speed); addPosition(position, heading, m, speed);
const coords = positions.getCoordinates(); var coords = positions.getCoordinates();
const len = coords.length; var len = coords.length;
if (len >= 2) { if (len >= 2) {
deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1); deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1);
} }
const html = [ var html = [
'Position: ' + position[0].toFixed(2) + ', ' + position[1].toFixed(2), 'Position: ' + position[0].toFixed(2) + ', ' + position[1].toFixed(2),
'Accuracy: ' + accuracy, 'Accuracy: ' + accuracy,
'Heading: ' + Math.round(radToDeg(heading)) + '&deg;', 'Heading: ' + Math.round(radToDeg(heading)) + '&deg;',
@@ -102,17 +102,17 @@ function mod(n) {
} }
function addPosition(position, heading, m, speed) { function addPosition(position, heading, m, speed) {
const x = position[0]; var x = position[0];
const y = position[1]; var y = position[1];
const fCoords = positions.getCoordinates(); var fCoords = positions.getCoordinates();
const previous = fCoords[fCoords.length - 1]; var previous = fCoords[fCoords.length - 1];
const prevHeading = previous && previous[2]; var prevHeading = previous && previous[2];
if (prevHeading) { if (prevHeading) {
let headingDiff = heading - mod(prevHeading); var headingDiff = heading - mod(prevHeading);
// force the rotation change to be less than 180° // force the rotation change to be less than 180°
if (Math.abs(headingDiff) > Math.PI) { if (Math.abs(headingDiff) > Math.PI) {
const sign = (headingDiff >= 0) ? 1 : -1; var sign = (headingDiff >= 0) ? 1 : -1;
headingDiff = -sign * (2 * Math.PI - Math.abs(headingDiff)); headingDiff = -sign * (2 * Math.PI - Math.abs(headingDiff));
} }
heading = prevHeading + headingDiff; heading = prevHeading + headingDiff;
@@ -133,8 +133,8 @@ function addPosition(position, heading, m, speed) {
// recenters the view by putting the given coordinates at 3/4 from the top or // recenters the view by putting the given coordinates at 3/4 from the top or
// the screen // the screen
function getCenterWithHeading(position, rotation, resolution) { function getCenterWithHeading(position, rotation, resolution) {
const size = map.getSize(); var size = map.getSize();
const height = size[1]; var height = size[1];
return [ return [
position[0] - Math.sin(rotation) * height * resolution * 1 / 4, position[0] - Math.sin(rotation) * height * resolution * 1 / 4,
@@ -142,14 +142,14 @@ function getCenterWithHeading(position, rotation, resolution) {
]; ];
} }
let previousM = 0; var previousM = 0;
function updateView() { function updateView() {
// use sampling period to get a smooth transition // use sampling period to get a smooth transition
let m = Date.now() - deltaMean * 1.5; var m = Date.now() - deltaMean * 1.5;
m = Math.max(m, previousM); m = Math.max(m, previousM);
previousM = m; previousM = m;
// interpolate position along positions LineString // interpolate position along positions LineString
const c = positions.getCoordinateAtM(m, true); var c = positions.getCoordinateAtM(m, true);
if (c) { if (c) {
view.setCenter(getCenterWithHeading(c, -c[2], view.getResolution())); view.setCenter(getCenterWithHeading(c, -c[2], view.getResolution()));
view.setRotation(-c[2]); view.setRotation(-c[2]);
@@ -158,7 +158,7 @@ function updateView() {
} }
// geolocate device // geolocate device
const geolocateBtn = document.getElementById('geolocate'); var geolocateBtn = document.getElementById('geolocate');
geolocateBtn.addEventListener('click', function() { geolocateBtn.addEventListener('click', function() {
geolocation.setTracking(true); // Start position tracking geolocation.setTracking(true); // Start position tracking
@@ -169,8 +169,8 @@ geolocateBtn.addEventListener('click', function() {
}, false); }, false);
// simulate device move // simulate device move
let simulationData; var simulationData;
const client = new XMLHttpRequest(); var client = new XMLHttpRequest();
client.open('GET', 'data/geolocation-orientation.json'); client.open('GET', 'data/geolocation-orientation.json');
@@ -182,20 +182,20 @@ client.onload = function() {
}; };
client.send(); client.send();
const simulateBtn = document.getElementById('simulate'); var simulateBtn = document.getElementById('simulate');
simulateBtn.addEventListener('click', function() { simulateBtn.addEventListener('click', function() {
const coordinates = simulationData; var coordinates = simulationData;
const first = coordinates.shift(); var first = coordinates.shift();
simulatePositionChange(first); simulatePositionChange(first);
let prevDate = first.timestamp; var prevDate = first.timestamp;
function geolocate() { function geolocate() {
const position = coordinates.shift(); var position = coordinates.shift();
if (!position) { if (!position) {
return; return;
} }
const newDate = position.timestamp; var newDate = position.timestamp;
simulatePositionChange(position); simulatePositionChange(position);
window.setTimeout(function() { window.setTimeout(function() {
prevDate = newDate; prevDate = newDate;
@@ -211,10 +211,12 @@ simulateBtn.addEventListener('click', function() {
}, false); }, false);
function simulatePositionChange(position) { function simulatePositionChange(position) {
const coords = position.coords; var coords = position.coords;
geolocation.set('accuracy', coords.accuracy); geolocation.set('accuracy', coords.accuracy);
geolocation.set('heading', degToRad(coords.heading)); geolocation.set('heading', degToRad(coords.heading));
const projectedPosition = fromLonLat([coords.longitude, coords.latitude]); var position_ = [coords.longitude, coords.latitude];
var projectedPosition = ol.proj.transform(position_, 'EPSG:4326',
'EPSG:3857');
geolocation.set('position', projectedPosition); geolocation.set('position', projectedPosition);
geolocation.set('speed', coords.speed); geolocation.set('speed', coords.speed);
geolocation.changed(); geolocation.changed();
+31 -35
View File
@@ -1,31 +1,31 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Geolocation from '../src/ol/Geolocation.js'; goog.require('ol.Geolocation');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const view = new View({ var view = new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}) })
], ],
target: 'map', target: 'map',
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
@@ -33,11 +33,7 @@ const map = new Map({
view: view view: view
}); });
const geolocation = new Geolocation({ var geolocation = new ol.Geolocation({
// enableHighAccuracy must be set to true to have the heading value.
trackingOptions: {
enableHighAccuracy: true
},
projection: view.getProjection() projection: view.getProjection()
}); });
@@ -60,24 +56,24 @@ geolocation.on('change', function() {
// handle geolocation error. // handle geolocation error.
geolocation.on('error', function(error) { geolocation.on('error', function(error) {
const info = document.getElementById('info'); var info = document.getElementById('info');
info.innerHTML = error.message; info.innerHTML = error.message;
info.style.display = ''; info.style.display = '';
}); });
const accuracyFeature = new Feature(); var accuracyFeature = new ol.Feature();
geolocation.on('change:accuracyGeometry', function() { geolocation.on('change:accuracyGeometry', function() {
accuracyFeature.setGeometry(geolocation.getAccuracyGeometry()); accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
}); });
const positionFeature = new Feature(); var positionFeature = new ol.Feature();
positionFeature.setStyle(new Style({ positionFeature.setStyle(new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: 6, radius: 6,
fill: new Fill({ fill: new ol.style.Fill({
color: '#3399CC' color: '#3399CC'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#fff', color: '#fff',
width: 2 width: 2
}) })
@@ -85,14 +81,14 @@ positionFeature.setStyle(new Style({
})); }));
geolocation.on('change:position', function() { geolocation.on('change:position', function() {
const coordinates = geolocation.getPosition(); var coordinates = geolocation.getPosition();
positionFeature.setGeometry(coordinates ? positionFeature.setGeometry(coordinates ?
new Point(coordinates) : null); new ol.geom.Point(coordinates) : null);
}); });
new VectorLayer({ new ol.layer.Vector({
map: map, map: map,
source: new VectorSource({ source: new ol.source.Vector({
features: [accuracyFeature, positionFeature] features: [accuracyFeature, positionFeature]
}) })
}); });
+14 -14
View File
@@ -1,26 +1,26 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import ImageLayer from '../src/ol/layer/Image.js'; goog.require('ol.layer.Image');
import ImageWMS from '../src/ol/source/ImageWMS.js'; goog.require('ol.source.ImageWMS');
const wmsSource = new ImageWMS({ var wmsSource = new ol.source.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({ var wmsLayer = new ol.layer.Image({
source: wmsSource source: wmsSource
}); });
const view = new View({ var view = new ol.View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1
}); });
const map = new Map({ var map = new ol.Map({
layers: [wmsLayer], layers: [wmsLayer],
target: 'map', target: 'map',
view: view view: view
@@ -28,10 +28,10 @@ const map = new Map({
map.on('singleclick', function(evt) { map.on('singleclick', function(evt) {
document.getElementById('info').innerHTML = ''; document.getElementById('info').innerHTML = '';
const viewResolution = /** @type {number} */ (view.getResolution()); var viewResolution = /** @type {number} */ (view.getResolution());
const url = wmsSource.getGetFeatureInfoUrl( var url = wmsSource.getGetFeatureInfoUrl(
evt.coordinate, viewResolution, 'EPSG:3857', evt.coordinate, viewResolution, 'EPSG:3857',
{'INFO_FORMAT': 'text/html'}); {'INFO_FORMAT': 'text/html'});
if (url) { if (url) {
document.getElementById('info').innerHTML = document.getElementById('info').innerHTML =
'<iframe seamless src="' + url + '"></iframe>'; '<iframe seamless src="' + url + '"></iframe>';
@@ -42,8 +42,8 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
const pixel = map.getEventPixel(evt.originalEvent); var pixel = map.getEventPixel(evt.originalEvent);
const hit = map.forEachLayerAtPixel(pixel, function() { var hit = map.forEachLayerAtPixel(pixel, function() {
return true; return true;
}); });
map.getTargetElement().style.cursor = hit ? 'pointer' : ''; map.getTargetElement().style.cursor = hit ? 'pointer' : '';
+4 -4
View File
@@ -1,21 +1,21 @@
import WMSGetFeatureInfo from '../src/ol/format/WMSGetFeatureInfo.js'; goog.require('ol.format.WMSGetFeatureInfo');
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); var allFeatures = new ol.format.WMSGetFeatureInfo().readFeatures(response);
document.getElementById('all').innerText = allFeatures.length.toString(); document.getElementById('all').innerText = allFeatures.length.toString();
// when specifying the 'layers' options, only the features of those // when specifying the 'layers' options, only the features of those
// layers are returned by the format // layers are returned by the format
const hotelFeatures = new WMSGetFeatureInfo({ var hotelFeatures = new ol.format.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({ var restaurantFeatures = new ol.format.WMSGetFeatureInfo({
layers: ['restaurant'] layers: ['restaurant']
}).readFeatures(response); }).readFeatures(response);
document.getElementById('restaurant').innerText = restaurantFeatures.length.toString(); document.getElementById('restaurant').innerText = restaurantFeatures.length.toString();
+14 -14
View File
@@ -1,26 +1,26 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import TileWMS from '../src/ol/source/TileWMS.js'; goog.require('ol.source.TileWMS');
const wmsSource = new TileWMS({ var wmsSource = new ol.source.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({ var wmsLayer = new ol.layer.Tile({
source: wmsSource source: wmsSource
}); });
const view = new View({ var view = new ol.View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1
}); });
const map = new Map({ var map = new ol.Map({
layers: [wmsLayer], layers: [wmsLayer],
target: 'map', target: 'map',
view: view view: view
@@ -28,10 +28,10 @@ const map = new Map({
map.on('singleclick', function(evt) { map.on('singleclick', function(evt) {
document.getElementById('info').innerHTML = ''; document.getElementById('info').innerHTML = '';
const viewResolution = /** @type {number} */ (view.getResolution()); var viewResolution = /** @type {number} */ (view.getResolution());
const url = wmsSource.getGetFeatureInfoUrl( var url = wmsSource.getGetFeatureInfoUrl(
evt.coordinate, viewResolution, 'EPSG:3857', evt.coordinate, viewResolution, 'EPSG:3857',
{'INFO_FORMAT': 'text/html'}); {'INFO_FORMAT': 'text/html'});
if (url) { if (url) {
document.getElementById('info').innerHTML = document.getElementById('info').innerHTML =
'<iframe seamless src="' + url + '"></iframe>'; '<iframe seamless src="' + url + '"></iframe>';
@@ -42,8 +42,8 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
const pixel = map.getEventPixel(evt.originalEvent); var pixel = map.getEventPixel(evt.originalEvent);
const hit = map.forEachLayerAtPixel(pixel, function() { var hit = map.forEachLayerAtPixel(pixel, function() {
return true; return true;
}); });
map.getTargetElement().style.cursor = hit ? 'pointer' : ''; map.getTargetElement().style.cursor = hit ? 'pointer' : '';
+32 -32
View File
@@ -1,76 +1,76 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import GPX from '../src/ol/format/GPX.js'; goog.require('ol.format.GPX');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import BingMaps from '../src/ol/source/BingMaps.js'; goog.require('ol.source.BingMaps');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new BingMaps({ source: new ol.source.BingMaps({
imagerySet: 'Aerial', imagerySet: 'Aerial',
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5' key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'
}) })
}); });
const style = { var style = {
'Point': new Style({ 'Point': new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255,255,0,0.4)' color: 'rgba(255,255,0,0.4)'
}), }),
radius: 5, radius: 5,
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#ff0', color: '#ff0',
width: 1 width: 1
}) })
}) })
}), }),
'LineString': new Style({ 'LineString': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#f00', color: '#f00',
width: 3 width: 3
}) })
}), }),
'MultiLineString': new Style({ 'MultiLineString': new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#0f0', color: '#0f0',
width: 3 width: 3
}) })
}) })
}; };
const vector = new VectorLayer({ var vector = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
url: 'data/gpx/fells_loop.gpx', url: 'data/gpx/fells_loop.gpx',
format: new GPX() format: new ol.format.GPX()
}), }),
style: function(feature) { style: function(feature) {
return style[feature.getGeometry().getType()]; return style[feature.getGeometry().getType()];
} }
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new ol.View({
center: [-7916041.528716288, 5228379.045749711], center: [-7916041.528716288, 5228379.045749711],
zoom: 12 zoom: 12
}) })
}); });
const displayFeatureInfo = function(pixel) { var displayFeatureInfo = function(pixel) {
const features = []; var features = [];
map.forEachFeatureAtPixel(pixel, function(feature) { map.forEachFeatureAtPixel(pixel, function(feature) {
features.push(feature); features.push(feature);
}); });
if (features.length > 0) { if (features.length > 0) {
const info = []; var info = [];
let i, ii; var i, ii;
for (i = 0, ii = features.length; i < ii; ++i) { for (i = 0, ii = features.length; i < ii; ++i) {
info.push(features[i].get('desc')); info.push(features[i].get('desc'));
} }
@@ -86,7 +86,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
const pixel = map.getEventPixel(evt.originalEvent); var pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel); displayFeatureInfo(pixel);
}); });
+15 -14
View File
@@ -1,31 +1,32 @@
import Graticule from '../src/ol/Graticule.js'; goog.require('ol.Graticule');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import {fromLonLat} from '../src/ol/proj.js'; goog.require('ol.proj');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM({ source: new ol.source.OSM({
wrapX: false wrapX: false
}) })
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: fromLonLat([4.8, 47.75]), center: ol.proj.fromLonLat([4.8, 47.75]),
extent: ol.proj.get('EPSG:3857').getExtent(),
zoom: 5 zoom: 5
}) })
}); });
// Create the graticule component // Create the graticule component
const graticule = new Graticule({ var graticule = new ol.Graticule({
// the style to use for the lines, optional. // the style to use for the lines, optional.
strokeStyle: new Stroke({ strokeStyle: new ol.style.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]
+18 -18
View File
@@ -1,18 +1,18 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import KML from '../src/ol/format/KML.js'; goog.require('ol.format.KML');
import HeatmapLayer from '../src/ol/layer/Heatmap.js'; goog.require('ol.layer.Heatmap');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import Stamen from '../src/ol/source/Stamen.js'; goog.require('ol.source.Stamen');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
const blur = document.getElementById('blur'); var blur = document.getElementById('blur');
const radius = document.getElementById('radius'); var radius = document.getElementById('radius');
const vector = new HeatmapLayer({ var vector = new ol.layer.Heatmap({
source: new VectorSource({ source: new ol.source.Vector({
url: 'data/kml/2012_Earthquakes_Mag5.kml', url: 'data/kml/2012_Earthquakes_Mag5.kml',
format: new KML({ format: new ol.format.KML({
extractStyles: false extractStyles: false
}) })
}), }),
@@ -24,21 +24,21 @@ vector.getSource().on('addfeature', function(event) {
// 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a
// standards-violating <magnitude> tag in each Placemark. We extract it from // standards-violating <magnitude> tag in each Placemark. We extract it from
// the Placemark's name instead. // the Placemark's name instead.
const name = event.feature.get('name'); var name = event.feature.get('name');
const magnitude = parseFloat(name.substr(2)); var magnitude = parseFloat(name.substr(2));
event.feature.set('weight', magnitude - 5); event.feature.set('weight', magnitude - 5);
}); });
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new Stamen({ source: new ol.source.Stamen({
layer: 'toner' layer: 'toner'
}) })
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
+23 -23
View File
@@ -1,11 +1,11 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import XYZ from '../src/ol/source/XYZ.js'; goog.require('ol.source.XYZ');
const appId = 'kDm0Jq1K4Ak7Bwtn8uvk'; var appId = 'kDm0Jq1K4Ak7Bwtn8uvk';
const appCode = 'xnmvc4dKZrDfGlvQHXSvwQ'; var appCode = 'xnmvc4dKZrDfGlvQHXSvwQ';
const hereLayers = [ var hereLayers = [
{ {
base: 'base', base: 'base',
type: 'maptile', type: 'maptile',
@@ -49,17 +49,17 @@ const hereLayers = [
app_code: appCode app_code: appCode
} }
]; ];
const urlTpl = 'https://{1-4}.{base}.maps.cit.api.here.com' + var 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 = []; var layers = [];
let i, ii; var i, ii;
for (i = 0, ii = hereLayers.length; i < ii; ++i) { for (i = 0, ii = hereLayers.length; i < ii; ++i) {
const layerDesc = hereLayers[i]; var layerDesc = hereLayers[i];
layers.push(new TileLayer({ layers.push(new ol.layer.Tile({
visible: false, visible: false,
preload: Infinity, preload: Infinity,
source: new XYZ({ source: new ol.source.XYZ({
url: createUrl(urlTpl, layerDesc), url: createUrl(urlTpl, layerDesc),
attributions: 'Map Tiles &copy; ' + new Date().getFullYear() + ' ' + attributions: 'Map Tiles &copy; ' + new Date().getFullYear() + ' ' +
'<a href="http://developer.here.com">HERE</a>' '<a href="http://developer.here.com">HERE</a>'
@@ -67,13 +67,13 @@ for (i = 0, ii = hereLayers.length; i < ii; ++i) {
})); }));
} }
const map = new Map({ var map = new ol.Map({
layers: layers, layers: layers,
// Improve user experience by loading tiles while dragging/zooming. Will make // Improve user experience by loading tiles while dragging/zooming. Will make
// zooming choppy on mobile or slow devices. // zooming choppy on mobile or slow devices.
loadTilesWhileInteracting: true, loadTilesWhileInteracting: true,
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [921371.9389, 6358337.7609], center: [921371.9389, 6358337.7609],
zoom: 10 zoom: 10
}) })
@@ -81,17 +81,17 @@ const map = new Map({
function createUrl(tpl, layerDesc) { function createUrl(tpl, layerDesc) {
return tpl return tpl
.replace('{base}', layerDesc.base) .replace('{base}', layerDesc.base)
.replace('{type}', layerDesc.type) .replace('{type}', layerDesc.type)
.replace('{scheme}', layerDesc.scheme) .replace('{scheme}', layerDesc.scheme)
.replace('{app_id}', layerDesc.app_id) .replace('{app_id}', layerDesc.app_id)
.replace('{app_code}', layerDesc.app_code); .replace('{app_code}', layerDesc.app_code);
} }
const select = document.getElementById('layer-select'); var select = document.getElementById('layer-select');
function onChange() { function onChange() {
const scheme = select.value; var scheme = select.value;
for (let i = 0, ii = layers.length; i < ii; ++i) { for (var i = 0, ii = layers.length; i < ii; ++i) {
layers[i].setVisible(hereLayers[i].scheme === scheme); layers[i].setVisible(hereLayers[i].scheme === scheme);
} }
} }
+27 -27
View File
@@ -1,49 +1,49 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import LineString from '../src/ol/geom/LineString.js'; goog.require('ol.geom.LineString');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}); });
const style = new Style({ var style = new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'black', color: 'black',
width: 1 width: 1
}) })
}); });
const feature = new Feature(new LineString([[-4000000, 0], [4000000, 0]])); var feature = new ol.Feature(new ol.geom.LineString([[-4000000, 0], [4000000, 0]]));
const vector = new VectorLayer({ var vector = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
features: [feature] features: [feature]
}), }),
style: style style: style
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
}); });
let hitTolerance; var hitTolerance;
const statusElement = document.getElementById('status'); var statusElement = document.getElementById('status');
map.on('singleclick', function(e) { map.on('singleclick', function(e) {
let hit = false; var hit = false;
map.forEachFeatureAtPixel(e.pixel, function() { map.forEachFeatureAtPixel(e.pixel, function() {
hit = true; hit = true;
}, { }, {
@@ -59,16 +59,16 @@ map.on('singleclick', function(e) {
feature.changed(); feature.changed();
}); });
const selectHitToleranceElement = document.getElementById('hitTolerance'); var selectHitToleranceElement = document.getElementById('hitTolerance');
const circleCanvas = document.getElementById('circle'); var circleCanvas = document.getElementById('circle');
const changeHitTolerance = function() { var changeHitTolerance = function() {
hitTolerance = parseInt(selectHitToleranceElement.value, 10); hitTolerance = parseInt(selectHitToleranceElement.value, 10);
const size = 2 * hitTolerance + 2; var size = 2 * hitTolerance + 2;
circleCanvas.width = size; circleCanvas.width = size;
circleCanvas.height = size; circleCanvas.height = size;
const ctx = circleCanvas.getContext('2d'); var 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);
+30 -30
View File
@@ -1,46 +1,46 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import {fromLonLat} from '../src/ol/proj.js'; goog.require('ol.proj');
import TileJSON from '../src/ol/source/TileJSON.js'; goog.require('ol.source.TileJSON');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import Icon from '../src/ol/style/Icon.js'; goog.require('ol.style.Icon');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const rome = new Feature({ var rome = new ol.Feature({
geometry: new Point(fromLonLat([12.5, 41.9])) geometry: new ol.geom.Point(ol.proj.fromLonLat([12.5, 41.9]))
}); });
const london = new Feature({ var london = new ol.Feature({
geometry: new Point(fromLonLat([-0.12755, 51.507222])) geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.12755, 51.507222]))
}); });
const madrid = new Feature({ var madrid = new ol.Feature({
geometry: new Point(fromLonLat([-3.683333, 40.4])) geometry: new ol.geom.Point(ol.proj.fromLonLat([-3.683333, 40.4]))
}); });
rome.setStyle(new Style({ rome.setStyle(new ol.style.Style({
image: new Icon(/** @type {olx.style.IconOptions} */ ({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
color: '#8959A8', color: '#8959A8',
crossOrigin: 'anonymous', crossOrigin: 'anonymous',
src: 'data/dot.png' src: 'data/dot.png'
})) }))
})); }));
london.setStyle(new Style({ london.setStyle(new ol.style.Style({
image: new Icon(/** @type {olx.style.IconOptions} */ ({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
color: '#4271AE', color: '#4271AE',
crossOrigin: 'anonymous', crossOrigin: 'anonymous',
src: 'data/dot.png' src: 'data/dot.png'
})) }))
})); }));
madrid.setStyle(new Style({ madrid.setStyle(new ol.style.Style({
image: new Icon(/** @type {olx.style.IconOptions} */ ({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
color: [113, 140, 0], color: [113, 140, 0],
crossOrigin: 'anonymous', crossOrigin: 'anonymous',
src: 'data/dot.png' src: 'data/dot.png'
@@ -48,26 +48,26 @@ madrid.setStyle(new Style({
})); }));
const vectorSource = new VectorSource({ var vectorSource = new ol.source.Vector({
features: [rome, london, madrid] features: [rome, london, madrid]
}); });
const vectorLayer = new VectorLayer({ var vectorLayer = new ol.layer.Vector({
source: vectorSource source: vectorSource
}); });
const rasterLayer = new TileLayer({ var rasterLayer = new ol.layer.Tile({
source: new TileJSON({ source: new ol.source.TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure', url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
crossOrigin: '' crossOrigin: ''
}) })
}); });
const map = new Map({ var map = new ol.Map({
layers: [rasterLayer, vectorLayer], layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new ol.View({
center: fromLonLat([2.896372, 44.60240]), center: ol.proj.fromLonLat([2.896372, 44.60240]),
zoom: 3 zoom: 3
}) })
}); });
+28 -28
View File
@@ -1,19 +1,19 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import Select from '../src/ol/interaction/Select.js'; goog.require('ol.interaction.Select');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import Stamen from '../src/ol/source/Stamen.js'; goog.require('ol.source.Stamen');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import Icon from '../src/ol/style/Icon.js'; goog.require('ol.style.Icon');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
function createStyle(src, img) { function createStyle(src, img) {
return new Style({ return new ol.style.Style({
image: new Icon(/** @type {olx.style.IconOptions} */ ({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 0.96], anchor: [0.5, 0.96],
crossOrigin: 'anonymous', crossOrigin: 'anonymous',
src: src, src: src,
@@ -23,41 +23,41 @@ function createStyle(src, img) {
}); });
} }
const iconFeature = new Feature(new Point([0, 0])); var iconFeature = new ol.Feature(new ol.geom.Point([0, 0]));
iconFeature.set('style', createStyle('data/icon.png', undefined)); iconFeature.set('style', createStyle('data/icon.png', undefined));
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new Stamen({layer: 'watercolor'}) source: new ol.source.Stamen({layer: 'watercolor'})
}), }),
new VectorLayer({ new ol.layer.Vector({
style: function(feature) { style: function(feature) {
return feature.get('style'); return feature.get('style');
}, },
source: new VectorSource({features: [iconFeature]}) source: new ol.source.Vector({features: [iconFeature]})
}) })
], ],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 3 zoom: 3
}) })
}); });
const selectStyle = {}; var selectStyle = {};
const select = new Select({ var select = new ol.interaction.Select({
style: function(feature) { style: function(feature) {
const image = feature.get('style').getImage().getImage(); var image = feature.get('style').getImage().getImage();
if (!selectStyle[image.src]) { if (!selectStyle[image.src]) {
const canvas = document.createElement('canvas'); var canvas = document.createElement('canvas');
const context = canvas.getContext('2d'); var context = canvas.getContext('2d');
canvas.width = image.width; canvas.width = image.width;
canvas.height = image.height; canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height); context.drawImage(image, 0, 0, image.width, image.height);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height); var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data; var data = imageData.data;
for (let i = 0, ii = data.length; i < ii; i = i + (i % 4 == 2 ? 2 : 1)) { for (var i = 0, ii = data.length; i < ii; i = i + (i % 4 == 2 ? 2 : 1)) {
data[i] = 255 - data[i]; data[i] = 255 - data[i];
} }
context.putImageData(imageData, 0, 0); context.putImageData(imageData, 0, 0);
+37 -37
View File
@@ -1,14 +1,14 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import Icon from '../src/ol/style/Icon.js'; goog.require('ol.style.Icon');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const iconInfo = [{ var iconInfo = [{
offset: [0, 0], offset: [0, 0],
opacity: 1.0, opacity: 1.0,
rotateWithView: true, rotateWithView: true,
@@ -38,13 +38,13 @@ const iconInfo = [{
size: [44, 44] size: [44, 44]
}]; }];
let i; var i;
const iconCount = iconInfo.length; var iconCount = iconInfo.length;
const icons = new Array(iconCount); var icons = new Array(iconCount);
for (i = 0; i < iconCount; ++i) { for (i = 0; i < iconCount; ++i) {
const info = iconInfo[i]; var info = iconInfo[i];
icons[i] = new Icon({ icons[i] = new ol.style.Icon({
offset: info.offset, offset: info.offset,
opacity: info.opacity, opacity: info.opacity,
rotateWithView: info.rotateWithView, rotateWithView: info.rotateWithView,
@@ -56,63 +56,63 @@ for (i = 0; i < iconCount; ++i) {
}); });
} }
const featureCount = 50000; var featureCount = 50000;
const features = new Array(featureCount); var features = new Array(featureCount);
let feature, geometry; var feature, geometry;
const e = 25000000; var e = 25000000;
for (i = 0; i < featureCount; ++i) { for (i = 0; i < featureCount; ++i) {
geometry = new Point( geometry = new ol.geom.Point(
[2 * e * Math.random() - e, 2 * e * Math.random() - e]); [2 * e * Math.random() - e, 2 * e * Math.random() - e]);
feature = new Feature(geometry); feature = new ol.Feature(geometry);
feature.setStyle( feature.setStyle(
new Style({ new ol.style.Style({
image: icons[i % (iconCount - 1)] image: icons[i % (iconCount - 1)]
}) })
); );
features[i] = feature; features[i] = feature;
} }
const vectorSource = new VectorSource({ var vectorSource = new ol.source.Vector({
features: features features: features
}); });
const vector = new VectorLayer({ var vector = new ol.layer.Vector({
source: vectorSource source: vectorSource
}); });
const map = new Map({ var map = new ol.Map({
renderer: /** @type {Array<ol.renderer.Type>} */ (['webgl', 'canvas']), renderer: /** @type {Array<ol.renderer.Type>} */ (['webgl', 'canvas']),
layers: [vector], layers: [vector],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 5 zoom: 5
}) })
}); });
const overlayFeatures = []; var overlayFeatures = [];
for (i = 0; i < featureCount; i += 30) { for (i = 0; i < featureCount; i += 30) {
const clone = features[i].clone(); var clone = features[i].clone();
clone.setStyle(null); clone.setStyle(null);
overlayFeatures.push(clone); overlayFeatures.push(clone);
} }
new VectorLayer({ new ol.layer.Vector({
map: map, map: map,
source: new VectorSource({ source: new ol.source.Vector({
features: overlayFeatures features: overlayFeatures
}), }),
style: new Style({ style: new ol.style.Style({
image: icons[iconCount - 1] image: icons[iconCount - 1]
}) })
}); });
map.on('click', function(evt) { map.on('click', function(evt) {
const info = document.getElementById('info'); var info = document.getElementById('info');
info.innerHTML = info.innerHTML =
'Hold on a second, while I catch those butterflies for you ...'; 'Hold on a second, while I catch those butterflies for you ...';
window.setTimeout(function() { window.setTimeout(function() {
const features = []; var features = [];
map.forEachFeatureAtPixel(evt.pixel, function(feature) { map.forEachFeatureAtPixel(evt.pixel, function(feature) {
features.push(feature); features.push(feature);
return false; return false;
@@ -132,7 +132,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
const pixel = map.getEventPixel(evt.originalEvent); var pixel = map.getEventPixel(evt.originalEvent);
const hit = map.hasFeatureAtPixel(pixel); var hit = map.hasFeatureAtPixel(pixel);
map.getTarget().style.cursor = hit ? 'pointer' : ''; map.getTarget().style.cursor = hit ? 'pointer' : '';
}); });
+30 -30
View File
@@ -1,25 +1,25 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import Overlay from '../src/ol/Overlay.js'; goog.require('ol.Overlay');
import View from '../src/ol/View.js'; goog.require('ol.View');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import TileJSON from '../src/ol/source/TileJSON.js'; goog.require('ol.source.TileJSON');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import Icon from '../src/ol/style/Icon.js'; goog.require('ol.style.Icon');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const iconFeature = new Feature({ var iconFeature = new ol.Feature({
geometry: new Point([0, 0]), geometry: new ol.geom.Point([0, 0]),
name: 'Null Island', name: 'Null Island',
population: 4000, population: 4000,
rainfall: 500 rainfall: 500
}); });
const iconStyle = new Style({ var iconStyle = new ol.style.Style({
image: new Icon(/** @type {olx.style.IconOptions} */ ({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 46], anchor: [0.5, 46],
anchorXUnits: 'fraction', anchorXUnits: 'fraction',
anchorYUnits: 'pixels', anchorYUnits: 'pixels',
@@ -29,33 +29,33 @@ const iconStyle = new Style({
iconFeature.setStyle(iconStyle); iconFeature.setStyle(iconStyle);
const vectorSource = new VectorSource({ var vectorSource = new ol.source.Vector({
features: [iconFeature] features: [iconFeature]
}); });
const vectorLayer = new VectorLayer({ var vectorLayer = new ol.layer.Vector({
source: vectorSource source: vectorSource
}); });
const rasterLayer = new TileLayer({ var rasterLayer = new ol.layer.Tile({
source: new TileJSON({ source: new ol.source.TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure', url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
crossOrigin: '' crossOrigin: ''
}) })
}); });
const map = new Map({ var map = new ol.Map({
layers: [rasterLayer, vectorLayer], layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 3 zoom: 3
}) })
}); });
const element = document.getElementById('popup'); var element = document.getElementById('popup');
const popup = new Overlay({ var popup = new ol.Overlay({
element: element, element: element,
positioning: 'bottom-center', positioning: 'bottom-center',
stopEvent: false, stopEvent: false,
@@ -65,12 +65,12 @@ map.addOverlay(popup);
// display popup on click // display popup on click
map.on('click', function(evt) { map.on('click', function(evt) {
const feature = map.forEachFeatureAtPixel(evt.pixel, var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) { function(feature) {
return feature; return feature;
}); });
if (feature) { if (feature) {
const coordinates = feature.getGeometry().getCoordinates(); var coordinates = feature.getGeometry().getCoordinates();
popup.setPosition(coordinates); popup.setPosition(coordinates);
$(element).popover({ $(element).popover({
'placement': 'top', 'placement': 'top',
@@ -89,7 +89,7 @@ map.on('pointermove', function(e) {
$(element).popover('destroy'); $(element).popover('destroy');
return; return;
} }
const pixel = map.getEventPixel(e.originalEvent); var pixel = map.getEventPixel(e.originalEvent);
const hit = map.hasFeatureAtPixel(pixel); var hit = map.hasFeatureAtPixel(pixel);
map.getTarget().style.cursor = hit ? 'pointer' : ''; map.getTarget().style.cursor = hit ? 'pointer' : '';
}); });
+65 -65
View File
@@ -1,21 +1,21 @@
import Feature from '../src/ol/Feature.js'; goog.require('ol.Feature');
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import {defaults as defaultControls} from '../src/ol/control.js'; goog.require('ol.control');
import IGC from '../src/ol/format/IGC.js'; goog.require('ol.format.IGC');
import LineString from '../src/ol/geom/LineString.js'; goog.require('ol.geom.LineString');
import Point from '../src/ol/geom/Point.js'; goog.require('ol.geom.Point');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import OSM, {ATTRIBUTION} from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const colors = { var colors = {
'Clement Latour': 'rgba(0, 0, 255, 0.7)', 'Clement Latour': 'rgba(0, 0, 255, 0.7)',
'Damien de Baesnt': 'rgba(0, 215, 255, 0.7)', 'Damien de Baesnt': 'rgba(0, 215, 255, 0.7)',
'Sylvain Dhonneur': 'rgba(0, 165, 255, 0.7)', 'Sylvain Dhonneur': 'rgba(0, 165, 255, 0.7)',
@@ -23,13 +23,13 @@ const colors = {
'Ulrich Prinz': 'rgba(0, 215, 255, 0.7)' 'Ulrich Prinz': 'rgba(0, 215, 255, 0.7)'
}; };
const styleCache = {}; var styleCache = {};
const styleFunction = function(feature) { var styleFunction = function(feature) {
const color = colors[feature.get('PLT')]; var color = colors[feature.get('PLT')];
let style = styleCache[color]; var style = styleCache[color];
if (!style) { if (!style) {
style = new Style({ style = new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: color, color: color,
width: 3 width: 3
}) })
@@ -39,9 +39,9 @@ const styleFunction = function(feature) {
return style; return style;
}; };
const vectorSource = new VectorSource(); var vectorSource = new ol.source.Vector();
const igcUrls = [ var igcUrls = [
'data/igc/Clement-Latour.igc', 'data/igc/Clement-Latour.igc',
'data/igc/Damien-de-Baenst.igc', 'data/igc/Damien-de-Baenst.igc',
'data/igc/Sylvain-Dhonneur.igc', 'data/igc/Sylvain-Dhonneur.igc',
@@ -50,7 +50,7 @@ const igcUrls = [
]; ];
function get(url, callback) { function get(url, callback) {
const client = new XMLHttpRequest(); var client = new XMLHttpRequest();
client.open('GET', url); client.open('GET', url);
client.onload = function() { client.onload = function() {
callback(client.responseText); callback(client.responseText);
@@ -58,81 +58,81 @@ function get(url, callback) {
client.send(); client.send();
} }
const igcFormat = new IGC(); var igcFormat = new ol.format.IGC();
for (let i = 0; i < igcUrls.length; ++i) { for (var i = 0; i < igcUrls.length; ++i) {
get(igcUrls[i], function(data) { get(igcUrls[i], function(data) {
const features = igcFormat.readFeatures(data, var features = igcFormat.readFeatures(data,
{featureProjection: 'EPSG:3857'}); {featureProjection: 'EPSG:3857'});
vectorSource.addFeatures(features); vectorSource.addFeatures(features);
}); });
} }
const time = { var 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(); var geometry = event.feature.getGeometry();
time.start = Math.min(time.start, geometry.getFirstCoordinate()[2]); time.start = Math.min(time.start, geometry.getFirstCoordinate()[2]);
time.stop = Math.max(time.stop, geometry.getLastCoordinate()[2]); time.stop = Math.max(time.stop, geometry.getLastCoordinate()[2]);
time.duration = time.stop - time.start; time.duration = time.stop - time.start;
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new TileLayer({ new ol.layer.Tile({
source: new OSM({ source: new ol.source.OSM({
attributions: [ attributions: [
'All maps © <a href="https://www.opencyclemap.org/">OpenCycleMap</a>', 'All maps © <a href="https://www.opencyclemap.org/">OpenCycleMap</a>',
ATTRIBUTION ol.source.OSM.ATTRIBUTION
], ],
url: 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' + url: 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' +
'?apikey=0e6fc415256d4fbb9b5166a718591d71' '?apikey=0e6fc415256d4fbb9b5166a718591d71'
}) })
}), }),
new VectorLayer({ new ol.layer.Vector({
source: vectorSource, source: vectorSource,
style: styleFunction style: styleFunction
}) })
], ],
target: 'map', target: 'map',
controls: defaultControls({ controls: ol.control.defaults({
attributionOptions: { attributionOptions: {
collapsible: false collapsible: false
} }
}), }),
view: new View({ view: new ol.View({
center: [703365.7089403362, 5714629.865071137], center: [703365.7089403362, 5714629.865071137],
zoom: 9 zoom: 9
}) })
}); });
let point = null; var point = null;
let line = null; var line = null;
const displaySnap = function(coordinate) { var displaySnap = function(coordinate) {
const closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate); var closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate);
const info = document.getElementById('info'); var info = document.getElementById('info');
if (closestFeature === null) { if (closestFeature === null) {
point = null; point = null;
line = null; line = null;
info.innerHTML = '&nbsp;'; info.innerHTML = '&nbsp;';
} else { } else {
const geometry = closestFeature.getGeometry(); var geometry = closestFeature.getGeometry();
const closestPoint = geometry.getClosestPoint(coordinate); var closestPoint = geometry.getClosestPoint(coordinate);
if (point === null) { if (point === null) {
point = new Point(closestPoint); point = new ol.geom.Point(closestPoint);
} else { } else {
point.setCoordinates(closestPoint); point.setCoordinates(closestPoint);
} }
const date = new Date(closestPoint[2] * 1000); var date = new Date(closestPoint[2] * 1000);
info.innerHTML = info.innerHTML =
closestFeature.get('PLT') + ' (' + date.toUTCString() + ')'; closestFeature.get('PLT') + ' (' + date.toUTCString() + ')';
const coordinates = [coordinate, [closestPoint[0], closestPoint[1]]]; var coordinates = [coordinate, [closestPoint[0], closestPoint[1]]];
if (line === null) { if (line === null) {
line = new LineString(coordinates); line = new ol.geom.LineString(coordinates);
} else { } else {
line.setCoordinates(coordinates); line.setCoordinates(coordinates);
} }
@@ -144,7 +144,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
const coordinate = map.getEventCoordinate(evt.originalEvent); var coordinate = map.getEventCoordinate(evt.originalEvent);
displaySnap(coordinate); displaySnap(coordinate);
}); });
@@ -152,20 +152,20 @@ map.on('click', function(evt) {
displaySnap(evt.coordinate); displaySnap(evt.coordinate);
}); });
const stroke = new Stroke({ var stroke = new ol.style.Stroke({
color: 'rgba(255,0,0,0.9)', color: 'rgba(255,0,0,0.9)',
width: 1 width: 1
}); });
const style = new Style({ var style = new ol.style.Style({
stroke: stroke, stroke: stroke,
image: new CircleStyle({ image: new ol.style.Circle({
radius: 5, radius: 5,
fill: null, fill: null,
stroke: stroke stroke: stroke
}) })
}); });
map.on('postcompose', function(evt) { map.on('postcompose', function(evt) {
const vectorContext = evt.vectorContext; var vectorContext = evt.vectorContext;
vectorContext.setStyle(style); vectorContext.setStyle(style);
if (point !== null) { if (point !== null) {
vectorContext.drawGeometry(point); vectorContext.drawGeometry(point);
@@ -175,13 +175,13 @@ map.on('postcompose', function(evt) {
} }
}); });
const featureOverlay = new VectorLayer({ var featureOverlay = new ol.layer.Vector({
source: new VectorSource(), source: new ol.source.Vector(),
map: map, map: map,
style: new Style({ style: new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: 5, radius: 5,
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.9)' color: 'rgba(255,0,0,0.9)'
}) })
}) })
@@ -189,14 +189,14 @@ const featureOverlay = new VectorLayer({
}); });
document.getElementById('time').addEventListener('input', function() { document.getElementById('time').addEventListener('input', function() {
const value = parseInt(this.value, 10) / 100; var value = parseInt(this.value, 10) / 100;
const m = time.start + (time.duration * value); var m = time.start + (time.duration * value);
vectorSource.forEachFeature(function(feature) { vectorSource.forEachFeature(function(feature) {
const geometry = /** @type {module:ol/geom/LineString~LineString} */ (feature.getGeometry()); var geometry = /** @type {ol.geom.LineString} */ (feature.getGeometry());
const coordinate = geometry.getCoordinateAtM(m, true); var coordinate = geometry.getCoordinateAtM(m, true);
let highlight = feature.get('highlight'); var highlight = feature.get('highlight');
if (highlight === undefined) { if (highlight === undefined) {
highlight = new Feature(new Point(coordinate)); highlight = new ol.Feature(new ol.geom.Point(coordinate));
feature.set('highlight', highlight); feature.set('highlight', highlight);
featureOverlay.getSource().addFeature(highlight); featureOverlay.getSource().addFeature(highlight);
} else { } else {
+38 -38
View File
@@ -1,25 +1,25 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import {fromLonLat} from '../src/ol/proj.js'; goog.require('ol.proj');
import BingMaps from '../src/ol/source/BingMaps.js'; goog.require('ol.source.BingMaps');
const key = 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5'; var key = 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5';
const imagery = new TileLayer({ var imagery = new ol.layer.Tile({
source: new BingMaps({key: key, imagerySet: 'Aerial'}) source: new ol.source.BingMaps({key: key, imagerySet: 'Aerial'})
}); });
const map = new Map({ var map = new ol.Map({
layers: [imagery], layers: [imagery],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: fromLonLat([-120, 50]), center: ol.proj.fromLonLat([-120, 50]),
zoom: 6 zoom: 6
}) })
}); });
const kernels = { var kernels = {
none: [ none: [
0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0,
@@ -58,9 +58,9 @@ const kernels = {
}; };
function normalize(kernel) { function normalize(kernel) {
const len = kernel.length; var len = kernel.length;
const normal = new Array(len); var normal = new Array(len);
let i, sum = 0; var i, sum = 0;
for (i = 0; i < len; ++i) { for (i = 0; i < len; ++i) {
sum += kernel[i]; sum += kernel[i];
} }
@@ -76,8 +76,8 @@ function normalize(kernel) {
return normal; return normal;
} }
const select = document.getElementById('kernel'); var select = document.getElementById('kernel');
let selectedKernel = normalize(kernels[select.value]); var selectedKernel = normalize(kernels[select.value]);
/** /**
@@ -104,37 +104,37 @@ imagery.on('postcompose', function(event) {
* @param {Array.<number>} kernel Kernel. * @param {Array.<number>} kernel Kernel.
*/ */
function convolve(context, kernel) { function convolve(context, kernel) {
const canvas = context.canvas; var canvas = context.canvas;
const width = canvas.width; var width = canvas.width;
const height = canvas.height; var height = canvas.height;
const size = Math.sqrt(kernel.length); var size = Math.sqrt(kernel.length);
const half = Math.floor(size / 2); var half = Math.floor(size / 2);
const inputData = context.getImageData(0, 0, width, height).data; var inputData = context.getImageData(0, 0, width, height).data;
const output = context.createImageData(width, height); var output = context.createImageData(width, height);
const outputData = output.data; var outputData = output.data;
for (let pixelY = 0; pixelY < height; ++pixelY) { for (var pixelY = 0; pixelY < height; ++pixelY) {
const pixelsAbove = pixelY * width; var pixelsAbove = pixelY * width;
for (let pixelX = 0; pixelX < width; ++pixelX) { for (var pixelX = 0; pixelX < width; ++pixelX) {
let r = 0, g = 0, b = 0, a = 0; var r = 0, g = 0, b = 0, a = 0;
for (let kernelY = 0; kernelY < size; ++kernelY) { for (var kernelY = 0; kernelY < size; ++kernelY) {
for (let kernelX = 0; kernelX < size; ++kernelX) { for (var kernelX = 0; kernelX < size; ++kernelX) {
const weight = kernel[kernelY * size + kernelX]; var weight = kernel[kernelY * size + kernelX];
const neighborY = Math.min( var neighborY = Math.min(
height - 1, Math.max(0, pixelY + kernelY - half)); height - 1, Math.max(0, pixelY + kernelY - half));
const neighborX = Math.min( var 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; var inputIndex = (neighborY * width + neighborX) * 4;
r += inputData[inputIndex] * weight; r += inputData[inputIndex] * weight;
g += inputData[inputIndex + 1] * weight; g += inputData[inputIndex + 1] * weight;
b += inputData[inputIndex + 2] * weight; b += inputData[inputIndex + 2] * weight;
a += inputData[inputIndex + 3] * weight; a += inputData[inputIndex + 3] * weight;
} }
} }
const outputIndex = (pixelsAbove + pixelX) * 4; var outputIndex = (pixelsAbove + pixelX) * 4;
outputData[outputIndex] = r; outputData[outputIndex] = r;
outputData[outputIndex + 1] = g; outputData[outputIndex + 1] = g;
outputData[outputIndex + 2] = b; outputData[outputIndex + 2] = b;
+13 -12
View File
@@ -1,7 +1,7 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import ImageLayer from '../src/ol/layer/Image.js'; goog.require('ol.layer.Image');
import ImageWMS from '../src/ol/source/ImageWMS.js'; goog.require('ol.source.ImageWMS');
/** /**
@@ -32,7 +32,7 @@ Progress.prototype.addLoading = function() {
* Increment the count of loaded tiles. * Increment the count of loaded tiles.
*/ */
Progress.prototype.addLoaded = function() { Progress.prototype.addLoaded = function() {
const this_ = this; var this_ = this;
setTimeout(function() { setTimeout(function() {
++this_.loaded; ++this_.loaded;
this_.update(); this_.update();
@@ -44,12 +44,12 @@ Progress.prototype.addLoaded = function() {
* Update the progress bar. * Update the progress bar.
*/ */
Progress.prototype.update = function() { Progress.prototype.update = function() {
const width = (this.loaded / this.loading * 100).toFixed(1) + '%'; var width = (this.loaded / this.loading * 100).toFixed(1) + '%';
this.el.style.width = width; this.el.style.width = width;
if (this.loading === this.loaded) { if (this.loading === this.loaded) {
this.loading = 0; this.loading = 0;
this.loaded = 0; this.loaded = 0;
const this_ = this; var this_ = this;
setTimeout(function() { setTimeout(function() {
this_.hide(); this_.hide();
}, 500); }, 500);
@@ -75,9 +75,9 @@ Progress.prototype.hide = function() {
} }
}; };
const progress = new Progress(document.getElementById('progress')); var progress = new Progress(document.getElementById('progress'));
const source = new ImageWMS({ var source = new ol.source.ImageWMS({
url: 'https://ahocevar.com/geoserver/wms', url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'topp:states'}, params: {'LAYERS': 'topp:states'},
serverType: 'geoserver' serverType: 'geoserver'
@@ -94,12 +94,13 @@ source.on('imageloaderror', function() {
progress.addLoaded(); progress.addLoaded();
}); });
const map = new Map({ var map = new ol.Map({
logo: false,
layers: [ layers: [
new ImageLayer({source: source}) new ol.layer.Image({source: source})
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [-10997148, 4569099], center: [-10997148, 4569099],
zoom: 4 zoom: 4
}) })
+28 -28
View File
@@ -1,32 +1,32 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
import Text from '../src/ol/style/Text.js'; goog.require('ol.style.Text');
const style = new Style({ var style = new ol.style.Style({
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.6)' color: 'rgba(255, 255, 255, 0.6)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#319FD3', color: '#319FD3',
width: 1 width: 1
}), }),
text: new Text() text: new ol.style.Text()
}); });
const map = new Map({ var map = new ol.Map({
layers: [ layers: [
new VectorLayer({ new ol.layer.Vector({
renderMode: 'image', renderMode: 'image',
source: new VectorSource({ source: new ol.source.Vector({
url: 'data/geojson/countries.geojson', url: 'data/geojson/countries.geojson',
format: new GeoJSON() format: new ol.format.GeoJSON()
}), }),
style: function(feature) { style: function(feature) {
style.getText().setText(feature.get('name')); style.getText().setText(feature.get('name'));
@@ -35,34 +35,34 @@ const map = new Map({
}) })
], ],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 1 zoom: 1
}) })
}); });
const featureOverlay = new VectorLayer({ var featureOverlay = new ol.layer.Vector({
source: new VectorSource(), source: new ol.source.Vector(),
map: map, map: map,
style: new Style({ style: new ol.style.Style({
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: '#f00', color: '#f00',
width: 1 width: 1
}), }),
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.1)' color: 'rgba(255,0,0,0.1)'
}) })
}) })
}); });
let highlight; var highlight;
const displayFeatureInfo = function(pixel) { var displayFeatureInfo = function(pixel) {
const feature = map.forEachFeatureAtPixel(pixel, function(feature) { var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature; return feature;
}); });
const info = document.getElementById('info'); var info = document.getElementById('info');
if (feature) { if (feature) {
info.innerHTML = feature.getId() + ': ' + feature.get('name'); info.innerHTML = feature.getId() + ': ' + feature.get('name');
} else { } else {
@@ -85,7 +85,7 @@ map.on('pointermove', function(evt) {
if (evt.dragging) { if (evt.dragging) {
return; return;
} }
const pixel = map.getEventPixel(evt.originalEvent); var pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel); displayFeatureInfo(pixel);
}); });
+22 -22
View File
@@ -1,31 +1,31 @@
// NOCOMPILE // NOCOMPILE
// this example uses JSTS for which we don't have an externs file. // this example uses JSTS for which we don't have an externs file.
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import GeoJSON from '../src/ol/format/GeoJSON.js'; goog.require('ol.format.GeoJSON');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import {fromLonLat} from '../src/ol/proj.js'; goog.require('ol.proj');
import OSM from '../src/ol/source/OSM.js'; goog.require('ol.source.OSM');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
const source = new VectorSource(); var source = new ol.source.Vector();
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(); var format = new ol.format.GeoJSON();
const features = format.readFeatures(json, {featureProjection: 'EPSG:3857'}); var features = format.readFeatures(json, {featureProjection: 'EPSG:3857'});
const parser = new jsts.io.OL3Parser(); var parser = new jsts.io.OL3Parser();
for (let i = 0; i < features.length; i++) { for (var i = 0; i < features.length; i++) {
const feature = features[i]; var feature = features[i];
// convert the OpenLayers geometry to a JSTS geometry // convert the OpenLayers geometry to a JSTS geometry
const jstsGeom = parser.read(feature.getGeometry()); var jstsGeom = parser.read(feature.getGeometry());
// create a buffer of 40 meters around each line // create a buffer of 40 meters around each line
const buffered = jstsGeom.buffer(40); var buffered = jstsGeom.buffer(40);
// convert back from JSTS and replace the geometry on the feature // convert back from JSTS and replace the geometry on the feature
feature.setGeometry(parser.write(buffered)); feature.setGeometry(parser.write(buffered));
@@ -33,19 +33,19 @@ fetch('data/geojson/roads-seoul.geojson').then(function(response) {
source.addFeatures(features); source.addFeatures(features);
}); });
const vectorLayer = new VectorLayer({ var vectorLayer = new ol.layer.Vector({
source: source source: source
}); });
const rasterLayer = new TileLayer({ var rasterLayer = new ol.layer.Tile({
source: new OSM() source: new ol.source.OSM()
}); });
const map = new Map({ var map = new ol.Map({
layers: [rasterLayer, vectorLayer], layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'), target: document.getElementById('map'),
view: new View({ view: new ol.View({
center: fromLonLat([126.979293, 37.528787]), center: ol.proj.fromLonLat([126.979293, 37.528787]),
zoom: 15 zoom: 15
}) })
}); });
+34 -34
View File
@@ -1,33 +1,33 @@
import Map from '../src/ol/Map.js'; goog.require('ol.Map');
import View from '../src/ol/View.js'; goog.require('ol.View');
import KML from '../src/ol/format/KML.js'; goog.require('ol.format.KML');
import TileLayer from '../src/ol/layer/Tile.js'; goog.require('ol.layer.Tile');
import VectorLayer from '../src/ol/layer/Vector.js'; goog.require('ol.layer.Vector');
import Stamen from '../src/ol/source/Stamen.js'; goog.require('ol.source.Stamen');
import VectorSource from '../src/ol/source/Vector.js'; goog.require('ol.source.Vector');
import CircleStyle from '../src/ol/style/Circle.js'; goog.require('ol.style.Circle');
import Fill from '../src/ol/style/Fill.js'; goog.require('ol.style.Fill');
import Stroke from '../src/ol/style/Stroke.js'; goog.require('ol.style.Stroke');
import Style from '../src/ol/style/Style.js'; goog.require('ol.style.Style');
const styleCache = {}; var styleCache = {};
const styleFunction = function(feature) { var styleFunction = function(feature) {
// 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a
// standards-violating <magnitude> tag in each Placemark. We extract it from // standards-violating <magnitude> tag in each Placemark. We extract it from
// the Placemark's name instead. // the Placemark's name instead.
const name = feature.get('name'); var name = feature.get('name');
const magnitude = parseFloat(name.substr(2)); var magnitude = parseFloat(name.substr(2));
const radius = 5 + 20 * (magnitude - 5); var radius = 5 + 20 * (magnitude - 5);
let style = styleCache[radius]; var style = styleCache[radius];
if (!style) { if (!style) {
style = new Style({ style = new ol.style.Style({
image: new CircleStyle({ image: new ol.style.Circle({
radius: radius, radius: radius,
fill: new Fill({ fill: new ol.style.Fill({
color: 'rgba(255, 153, 0, 0.4)' color: 'rgba(255, 153, 0, 0.4)'
}), }),
stroke: new Stroke({ stroke: new ol.style.Stroke({
color: 'rgba(255, 204, 0, 0.2)', color: 'rgba(255, 204, 0, 0.2)',
width: 1 width: 1
}) })
@@ -38,50 +38,50 @@ const styleFunction = function(feature) {
return style; return style;
}; };
const vector = new VectorLayer({ var vector = new ol.layer.Vector({
source: new VectorSource({ source: new ol.source.Vector({
url: 'data/kml/2012_Earthquakes_Mag5.kml', url: 'data/kml/2012_Earthquakes_Mag5.kml',
format: new KML({ format: new ol.format.KML({
extractStyles: false extractStyles: false
}) })
}), }),
style: styleFunction style: styleFunction
}); });
const raster = new TileLayer({ var raster = new ol.layer.Tile({
source: new Stamen({ source: new ol.source.Stamen({
layer: 'toner' layer: 'toner'
}) })
}); });
const map = new Map({ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
target: 'map', target: 'map',
view: new View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 2 zoom: 2
}) })
}); });
const info = $('#info'); var info = $('#info');
info.tooltip({ info.tooltip({
animation: false, animation: false,
trigger: 'manual' trigger: 'manual'
}); });
const displayFeatureInfo = function(pixel) { var 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) { var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature; return feature;
}); });
if (feature) { if (feature) {
info.tooltip('hide') info.tooltip('hide')
.attr('data-original-title', feature.get('name')) .attr('data-original-title', feature.get('name'))
.tooltip('fixTitle') .tooltip('fixTitle')
.tooltip('show'); .tooltip('show');
} else { } else {
info.tooltip('hide'); info.tooltip('hide');
} }

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