Compare commits

..

1 Commits

Author SHA1 Message Date
Andreas Hocevar
1cf01037aa Set version and tag for v4.3.0-beta.2 2017-07-15 11:33:05 +02:00
101 changed files with 567 additions and 2580 deletions

View File

@@ -1,7 +0,0 @@
This issue tracker is for reporting bugs or feature requests, not for asking questions. For usage questions, refer to the (documentation)[http://openlayers.org/en/latest/doc/].
Ready to submit your bug or feature request? Make sure these boxes are checked before submitting your issue. Thank you!
- [ ] I have searched GitHub to see if a similar bug or feature request has already been reported.
- [ ] If reporting a bug, I have tried with the latest version of OpenLayers (see 'LATEST' on https://openlayers.org/)
- [ ] If reporting a bug, I have created a [CodePen](https://codepen.io) or prepared a stack trace (using the latest version and unminified code, so e.g. `ol-debug.js`, not `ol.js`) that shows the issue.

View File

@@ -1,5 +0,0 @@
Make sure these boxes are checked before submitting your pull request. Thank you!
- [ ] This pull request addresses an issue that has been marked with the 'Pull request accepted' label.
- [ ] It contains one or more small, incremental, logically separate commits, with no merge commits.
- [ ] I have used clear commit messages.

View File

@@ -9,16 +9,9 @@
## Getting Started ## Getting Started
Use one of the following methods to use OpenLayers in your project: - Download the [latest release](https://openlayers.org/download/)
- Install with npm: `npm install openlayers`
* For use with webpack, Rollup, Browserify, or other module bundlers, install the [`ol` package](https://www.npmjs.com/package/ol): - Clone the repo: `git clone git@github.com:openlayers/openlayers.git`
```
npm install ol
```
* If you just want to add a `<script>` tag to test things out, you can link directly to one of the full builds from [cdnjs](https://cdnjs.com/libraries/openlayers) (not recommended for production)
* For use with Closure Library (rare), install the [`openlayers` package](https://npmjs.com/package/openlayers) and read the [tutorial](http://openlayers.org/en/latest/doc/tutorials/closure.html).
## Supported Browsers ## Supported Browsers
@@ -40,3 +33,4 @@ Please see our guide on [contributing](CONTRIBUTING.md) if you're interested in
- Need help? Find it on [Stack Overflow using the tag 'openlayers'](http://stackoverflow.com/questions/tagged/openlayers) - Need help? Find it on [Stack Overflow using the tag 'openlayers'](http://stackoverflow.com/questions/tagged/openlayers)
- Follow [@openlayers](https://twitter.com/openlayers) on Twitter - Follow [@openlayers](https://twitter.com/openlayers) on Twitter
- Discuss with openlayers users on IRC in `#openlayers` at `chat.freenode`

View File

@@ -1,53 +1,6 @@
## Upgrade notes ## Upgrade notes
### Next Release ### Next release
### v4.3.0
#### `ol.source.VectorTile` no longer requires a `tileGrid` option
By default, the `ol.source.VectorTile` constructor creates an XYZ tile grid (in Web Mercator) for 512 pixel tiles and assumes a max zoom level of 22. If you were creating a vector tile source with an explicit `tileGrid` option, you can now remove this.
Before:
```js
var source = new ol.source.VectorTile({
tileGrid: ol.tilegrid.createXYZ({tileSize: 512, maxZoom: 22}),
url: url
});
```
After:
```js
var source = new ol.source.VectorTile({
url: url
});
```
If you need to change the max zoom level, you can pass the source a `maxZoom` option. If you need to change the tile size, you can pass the source a `tileSize` option. If you need a completely custom tile grid, you can still pass the source a `tileGrid` option.
#### `ol.interaction.Modify` deletes with `alt` key only
To delete features with the modify interaction, press the `alt` key while clicking on an existing vertex. If you want to configure the modify interaction with a different delete condition, use the `deleteCondition` option. For example, to allow deletion on a single click with no modifier keys, configure the interaction like this:
```js
var interaction = new ol.interaction.Modify({
source: source,
deleteCondition: function(event) {
return ol.events.condition.noModifierKeys(event) && ol.events.condition.singleClick(event);
}
});
```
The motivation for this change is to make the modify, draw, and snap interactions all work well together. Previously, the use of these interactions with the default configuration would make it so you couldn't reliably add new vertices (click with no modifier) and delete existing vertices (click with no modifier).
#### `ol.source.VectorTile` no longer has a `tilePixelRatio` option
The `tilePixelRatio` option was only used for tiles in projections with `tile-pixels` as units. For tiles read with `ol.format.MVT` and the default tile loader, or tiles with the default pixel size of 4096 pixels, no changes are necessary. For the very rare cases that do not fall under these categories, a custom `tileLoadFunction` now needs to be configured on the `ol.source.VectorTile`. In addition to calling `tile.setFeatures()` and `tile.setProjection()`, it also needs to contain code like the following:
```js
var extent = tile.getFormat() instanceof ol.format.MVT ?
tile.getLastExtent() :
[0, 0, tilePixelRatio * tileSize, tilePixelRatio * tileSize];
tile.setExtent(extent);
```
#### `ol.animate` now takes the shortest arc for rotation animation #### `ol.animate` now takes the shortest arc for rotation animation

View File

@@ -1,216 +0,0 @@
# 4.3.0
## Summary
The v4.3.0 release includes features and fixes from 92 pull requests.
#### New `map.getFeaturesAtPixel()` method
When you want to get all features at a given pixel, use the new `map.getFeaturesAtPixel()` method.
Before:
```js
var features = [];
map.forEachFeatureAtPixel(pixel, function(feature) {
features.push(feature);
});
```
After:
```js
var features = map.getFeaturesAtPixel(pixel);
```
#### `ol.Sphere` functions for spherical measures
The new `ol.Sphere.getArea()` and `ol.Sphere.getLength()` methods can be used to calculate spherical measures on geometries. This is the recommended over using the `geometry.getArea()` or `geometry.getLength()` methods.
Bad:
```js
geometry.getArea();
```
Good:
```js
ol.Sphere.getArea(geometry);
```
#### `ol.interaction.DragAndDrop` can be configured with a vector source
It is now possible to configure the drag and drop interaction with a vector source:
```js
var dragAndDrop = new ol.interaction.DragAndDrop({source: source});
```
Any dropped features will replace all existing features on the source.
#### `ol.interaction.Modify` can be configured with a vector source
It is now possible to configure the modify interaction with a vector source (in addition to a feature collection):
```js
var modify = new ol.interaction.Modify({source: source});
```
With this configuration, all features on the source are eligible for modification while the interaction is active.
#### `ol.interaction.Modify` deletes with `alt` key only
To delete features with the modify interaction, press the `alt` key while clicking on an existing vertex. If you want to configure the modify interaction with a different delete condition, use the `deleteCondition` option. For example, to allow deletion on a single click with no modifier keys, configure the interaction like this:
```js
var interaction = new ol.interaction.Modify({
source: source,
deleteCondition: function(event) {
return ol.events.condition.noModifierKeys(event) && ol.events.condition.singleClick(event);
}
});
```
The motivation for this change is to make the modify, draw, and snap interactions all work well together. Previously, the use of these interactions with the default configuration would make it so you couldn't reliably add new vertices (click with no modifier) and delete existing vertices (click with no modifier).
#### `ol.source.VectorTile` no longer requires a `tileGrid` option
By default, the `ol.source.VectorTile` constructor creates an XYZ tile grid (in Web Mercator) for 512 pixel tiles and assumes a max zoom level of 22. If you were creating a vector tile source with an explicit `tileGrid` option, you can now remove this.
Before:
```js
var source = new ol.source.VectorTile({
tileGrid: ol.tilegrid.createXYZ({tileSize: 512, maxZoom: 22}),
url: url
});
```
After:
```js
var source = new ol.source.VectorTile({
url: url
});
```
If you need to change the max zoom level, you can pass the source a `maxZoom` option. If you need to change the tile size, you can pass the source a `tileSize` option. If you need a completely custom tile grid, you can still pass the source a `tileGrid` option.
#### `ol.source.VectorTile` no longer has a `tilePixelRatio` option
The `tilePixelRatio` option was only used for tiles in projections with `tile-pixels` as units. For tiles read with `ol.format.MVT` and the default tile loader, or tiles with the default pixel size of 4096 pixels, no changes are necessary. For the very rare cases that do not fall under these categories, a custom `tileLoadFunction` now needs to be configured on the `ol.source.VectorTile`. In addition to calling `tile.setFeatures()` and `tile.setProjection()`, it also needs to contain code like the following:
```js
var extent = tile.getFormat() instanceof ol.format.MVT ?
tile.getLastExtent() :
[0, 0, tilePixelRatio * tileSize, tilePixelRatio * tileSize];
tile.setExtent(extent);
```
#### `ol.animate` now takes the shortest arc for rotation animation
Usually rotation animations should animate along the shortest arc. There are rare occasions where a spinning animation effect is desired. So if you previously had something like
```js
map.getView().animate({
rotation: 2 * Math.PI,
duration: 2000
});
```
we recommend to split the animation into two parts and use different easing functions. The code below results in the same effect as the snippet above did with previous versions:
```js
map.getView().animate({
rotation: Math.PI,
easing: ol.easing.easeIn
}, {
rotation: 2 * Math.PI,
easing: ol.easing.easeOut
});
```
## Full List of Changes
* [#7117](https://github.com/openlayers/openlayers/pull/7117) - Sensible default tilegrid for vector tiles ([@tschaub](https://github.com/tschaub))
* [#7116](https://github.com/openlayers/openlayers/pull/7116) - fix(package): update rollup to version 0.47.2 ([@openlayers](https://github.com/openlayers))
* [#7111](https://github.com/openlayers/openlayers/pull/7111) - Remove broken wrapX handling from ol.Graticule ([@ahocevar](https://github.com/ahocevar))
* [#7107](https://github.com/openlayers/openlayers/pull/7107) - Update rollup to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7106](https://github.com/openlayers/openlayers/pull/7106) - Update proj4 to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7105](https://github.com/openlayers/openlayers/pull/7105) - Functions for spherical calculations ([@tschaub](https://github.com/tschaub))
* [#7104](https://github.com/openlayers/openlayers/pull/7104) - Update sinon to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#6807](https://github.com/openlayers/openlayers/pull/6807) - Initialize hasZ in the constructor of GML3 ([@Jenselme](https://github.com/Jenselme))
* [#7102](https://github.com/openlayers/openlayers/pull/7102) - Allow drag and drop interaction to be configured with a source ([@tschaub](https://github.com/tschaub))
* [#6825](https://github.com/openlayers/openlayers/pull/6825) - Read/write Tessellate tag in KML format ([@oterral](https://github.com/oterral))
* [#7098](https://github.com/openlayers/openlayers/pull/7098) - Use fractional coordinates for CSS positioning ([@ahocevar](https://github.com/ahocevar))
* [#7064](https://github.com/openlayers/openlayers/pull/7064) - Do not use Array.prototype.forEach when dealing with potentially large arrays ([@ahocevar](https://github.com/ahocevar))
* [#7093](https://github.com/openlayers/openlayers/pull/7093) - Allow modify interaction to be configured with a source ([@tschaub](https://github.com/tschaub))
* [#7096](https://github.com/openlayers/openlayers/pull/7096) - Add new Map#getFeaturesAtPixel method ([@ahocevar](https://github.com/ahocevar))
* [#7094](https://github.com/openlayers/openlayers/pull/7094) - Add missing zIndex options ([@icholy](https://github.com/icholy))
* [#7087](https://github.com/openlayers/openlayers/pull/7087) - Fix scale line for EPSG:4326 maps ([@ahocevar](https://github.com/ahocevar))
* [#7088](https://github.com/openlayers/openlayers/pull/7088) - Update sinon to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7085](https://github.com/openlayers/openlayers/pull/7085) - Update eslint to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7084](https://github.com/openlayers/openlayers/pull/7084) - Fix a typo in the street-labels example ([@ahocevar](https://github.com/ahocevar))
* [#7082](https://github.com/openlayers/openlayers/pull/7082) - Update eslint to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7079](https://github.com/openlayers/openlayers/pull/7079) - Optimize custom renderer code, examples and API ([@ahocevar](https://github.com/ahocevar))
* [#7080](https://github.com/openlayers/openlayers/pull/7080) - Update jsdoc to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7078](https://github.com/openlayers/openlayers/pull/7078) - Fix return type annotation of ol.layer.VectorTile.getSource ([@geosense](https://github.com/geosense))
* [#7073](https://github.com/openlayers/openlayers/pull/7073) - Make ol.layer.Group change handling consistent ([@gberaudo](https://github.com/gberaudo))
* [#7075](https://github.com/openlayers/openlayers/pull/7075) - Update sinon to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7072](https://github.com/openlayers/openlayers/pull/7072) - Improve API docs for ol.VectorTile ([@ahocevar](https://github.com/ahocevar))
* [#7070](https://github.com/openlayers/openlayers/pull/7070) - Get tilePixelRatio from MVT tiles ([@ahocevar](https://github.com/ahocevar))
* [#7069](https://github.com/openlayers/openlayers/pull/7069) - Update mocha to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7068](https://github.com/openlayers/openlayers/pull/7068) - Update fs-extra to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7066](https://github.com/openlayers/openlayers/pull/7066) - Fix ol.interaction.Extent event type and documentation ([@ahocevar](https://github.com/ahocevar))
* [#7032](https://github.com/openlayers/openlayers/pull/7032) - Fix KML Export Icon Anchor ([@raiyni](https://github.com/raiyni))
* [#7065](https://github.com/openlayers/openlayers/pull/7065) - Only use API functions in example ([@ahocevar](https://github.com/ahocevar))
* [#7022](https://github.com/openlayers/openlayers/pull/7022) - Allow styles to configure a custom renderer ([@ahocevar](https://github.com/ahocevar))
* [#7061](https://github.com/openlayers/openlayers/pull/7061) - Update docs and issue and pull request instructions ([@ahocevar](https://github.com/ahocevar))
* [#7059](https://github.com/openlayers/openlayers/pull/7059) - Allow to configure Extent interaction with an extent ([@ahocevar](https://github.com/ahocevar))
* [#7060](https://github.com/openlayers/openlayers/pull/7060) - Removing invalid urn ([@wnordmann](https://github.com/wnordmann))
* [#7051](https://github.com/openlayers/openlayers/pull/7051) - Changing the EPSG3857.PROJECTION array assignment and adding urn:ogc:… ([@wnordmann](https://github.com/wnordmann))
* [#7045](https://github.com/openlayers/openlayers/pull/7045) - Respect pixelRatio when scaling images ([@ahocevar](https://github.com/ahocevar))
* [#7023](https://github.com/openlayers/openlayers/pull/7023) - Update tile size and resolutions of vector tile examples ([@ahocevar](https://github.com/ahocevar))
* [#7005](https://github.com/openlayers/openlayers/pull/7005) - Add spatial reference inside geometry in EsriFormat ([@Sol1du2](https://github.com/Sol1du2))
* [#7034](https://github.com/openlayers/openlayers/pull/7034) - Move non-build dependencies to devDependencies ([@probins](https://github.com/probins))
* [#7050](https://github.com/openlayers/openlayers/pull/7050) - Update sinon to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#6976](https://github.com/openlayers/openlayers/pull/6976) - Example - Earthquake Clusters - Change evt.type of interaction ([@ehanoj](https://github.com/ehanoj))
* [#7048](https://github.com/openlayers/openlayers/pull/7048) - Update sinon to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7041](https://github.com/openlayers/openlayers/pull/7041) - Update eslint to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7042](https://github.com/openlayers/openlayers/pull/7042) - Line dash offset ([@gkresic](https://github.com/gkresic))
* [#6980](https://github.com/openlayers/openlayers/pull/6980) - Added tileClass to TileWMS ([@ZachTRice](https://github.com/ZachTRice))
* [#7028](https://github.com/openlayers/openlayers/pull/7028) - Fix Graticule use of incorrect min/maxLon values ([@greggian](https://github.com/greggian))
* [#7021](https://github.com/openlayers/openlayers/pull/7021) - Update fs-extra to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7018](https://github.com/openlayers/openlayers/pull/7018) - Update jsdoc to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7015](https://github.com/openlayers/openlayers/pull/7015) - Update sinon to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7014](https://github.com/openlayers/openlayers/pull/7014) - Update jsdoc to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7013](https://github.com/openlayers/openlayers/pull/7013) - Remove ol.sphere.WGS84 and ol.sphere.NORMAL ([@tschaub](https://github.com/tschaub))
* [#6981](https://github.com/openlayers/openlayers/pull/6981) - Render transparent vector layers to an intermediate canvas ([@gberaudo](https://github.com/gberaudo))
* [#6899](https://github.com/openlayers/openlayers/pull/6899) - Use number literal for sphere radius ([@probins](https://github.com/probins))
* [#7011](https://github.com/openlayers/openlayers/pull/7011) - Update jsdoc to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7008](https://github.com/openlayers/openlayers/pull/7008) - Update sinon to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7007](https://github.com/openlayers/openlayers/pull/7007) - fix(package): update rollup to version 0.45.0 ([@openlayers](https://github.com/openlayers))
* [#6996](https://github.com/openlayers/openlayers/pull/6996) - 6987: Memory leak with WMS time source with reprojection ([@ch08532](https://github.com/ch08532))
* [#7003](https://github.com/openlayers/openlayers/pull/7003) - Update jsdoc to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#7004](https://github.com/openlayers/openlayers/pull/7004) - Use https for bing and stamen attributions ([@fredj](https://github.com/fredj))
* [#6998](https://github.com/openlayers/openlayers/pull/6998) - Update eslint to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#6999](https://github.com/openlayers/openlayers/pull/6999) - Make VectorTile source work with multiple layers ([@ahocevar](https://github.com/ahocevar))
* [#6988](https://github.com/openlayers/openlayers/pull/6988) - Add missing type annotations ([@ahocevar](https://github.com/ahocevar))
* [#6984](https://github.com/openlayers/openlayers/pull/6984) - Update closure-util to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#6970](https://github.com/openlayers/openlayers/pull/6970) - Fix Bug when adding/removing layer with no cache ([@cmortazavi](https://github.com/cmortazavi))
* [#6972](https://github.com/openlayers/openlayers/pull/6972) - Handle error tiles properly ([@ahocevar](https://github.com/ahocevar))
* [#6973](https://github.com/openlayers/openlayers/pull/6973) - Update clean-css-cli to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#6971](https://github.com/openlayers/openlayers/pull/6971) - Update sinon to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#6968](https://github.com/openlayers/openlayers/pull/6968) - Shortest arc rotation animation improvements and upgrade notes ([@ahocevar](https://github.com/ahocevar))
* [#6966](https://github.com/openlayers/openlayers/pull/6966) - Add getResolutionForZoom method for ol.View ([@ahocevar](https://github.com/ahocevar))
* [#6965](https://github.com/openlayers/openlayers/pull/6965) - Use shortest rotation delta for animation ([@ahocevar](https://github.com/ahocevar))
* [#6967](https://github.com/openlayers/openlayers/pull/6967) - Add RoadOnDemand imagery set to Bing example ([@ahocevar](https://github.com/ahocevar))
* [#6964](https://github.com/openlayers/openlayers/pull/6964) - Fix KML ExtendedData reading ([@fredj](https://github.com/fredj))
* [#6958](https://github.com/openlayers/openlayers/pull/6958) - Remove error tiles after loading is finished ([@ahocevar](https://github.com/ahocevar))
* [#6793](https://github.com/openlayers/openlayers/pull/6793) - Webgl text ([@GaborFarkas](https://github.com/GaborFarkas))
* [#6960](https://github.com/openlayers/openlayers/pull/6960) - Queue tiles before loading ([@tschaub](https://github.com/tschaub))
* [#6957](https://github.com/openlayers/openlayers/pull/6957) - Greenkeeper/eslint 4.1.1 ([@openlayers](https://github.com/openlayers))
* [#6955](https://github.com/openlayers/openlayers/pull/6955) - Update async to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#6916](https://github.com/openlayers/openlayers/pull/6916) - Upgrade eslint to v4.0.0 ([@marcjansen](https://github.com/marcjansen))
* [#6943](https://github.com/openlayers/openlayers/pull/6943) - Update sinon to the latest version 🚀 ([@openlayers](https://github.com/openlayers))
* [#6939](https://github.com/openlayers/openlayers/pull/6939) - Abort loading when tile is disposed ([@ahocevar](https://github.com/ahocevar))
* [#6930](https://github.com/openlayers/openlayers/pull/6930) - Handle setActive(false) on an interaction without map ([@openlayers](https://github.com/openlayers))
* [#6936](https://github.com/openlayers/openlayers/pull/6936) - Do not stop the render loop when all wanted tiles are aborted ([@ahocevar](https://github.com/ahocevar))
* [#6920](https://github.com/openlayers/openlayers/pull/6920) - Fix minor type strength inconsistency ([@klokantech](https://github.com/klokantech))
* [#6935](https://github.com/openlayers/openlayers/pull/6935) - Use transparent image from canvas context ([@ahocevar](https://github.com/ahocevar))
* [#6933](https://github.com/openlayers/openlayers/pull/6933) - Improve proj.get() logic ([@probins](https://github.com/probins))
* [#6931](https://github.com/openlayers/openlayers/pull/6931) - Make sure we use the default featurePrefix ([@bartvde](https://github.com/bartvde))
* [#6928](https://github.com/openlayers/openlayers/pull/6928) - Only adjust resolution when center within projection extent ([@ahocevar](https://github.com/ahocevar))
* [#6923](https://github.com/openlayers/openlayers/pull/6923) - Load tasks/build-ext.js in strict mode ([@fredj](https://github.com/fredj))
* [#6918](https://github.com/openlayers/openlayers/pull/6918) - Remove unnecessary pixelRatio check ([@ahocevar](https://github.com/ahocevar))
* [#6917](https://github.com/openlayers/openlayers/pull/6917) - Correct typo in graticule docs ([@probins](https://github.com/probins))

View File

@@ -1,9 +0,0 @@
# 4.3.1
The v4.3.1 release includes a few fixes that didn't make it into v4.3.0. No special upgrade considerations.
## Fixes
* [#7122](https://github.com/openlayers/openlayers/pull/7122) - Immediately complete no-op animations ([@tschaub](https://github.com/tschaub))
* [#7120](https://github.com/openlayers/openlayers/pull/7120) - Fix hit detection for overzoomed vector tiles ([@ahocevar](https://github.com/ahocevar))
* [#7114](https://github.com/openlayers/openlayers/pull/7114) - Immediate WebGL text renderer and other improvements ([@GaborFarkas](https://github.com/GaborFarkas))

View File

@@ -11,7 +11,7 @@ For a more in-depth overview of OpenLayers core concepts, check out the [tutoria
Make sure to also check out the [OpenLayers workshop](/workshop/). Make sure to also check out the [OpenLayers workshop](/workshop/).
Find additional reference material in the [API docs](../apidoc) and [examples](../examples). Find additional reference material in the [API docs](../apidoc).
# Frequently Asked Questions (FAQ) # Frequently Asked Questions (FAQ)
@@ -19,4 +19,4 @@ We have put together a document that lists [Frequently Asked Questions (FAQ)](fa
# More questions? # More questions?
If you cannot find an answer in the documentation or the FAQ, you can search [Stack Overflow](http://stackoverflow.com/questions/tagged/openlayers). If you cannot find an answer there, ask a new question there, using the tag 'openlayers'. If you cannot find an answer in the documentation or the FAQ, you can ask your question on [Stack Overflow using the tag 'openlayers'](http://stackoverflow.com/questions/tagged/openlayers).

View File

@@ -5,56 +5,57 @@ layout: doc.hbs
# Introduction # Introduction
When going beyond modifying existing examples you might be looking for a way to setup your own code with dependency management together with external dependencies like OpenLayers. When going beyond modifying existing examples you might be looking for a
way to setup your own code with dependency management together with external
dependencies like OpenLayers.
This tutorial serves as a suggested project setup using NPM and Browserify for the most basic needs. There are several other options, and in particular you might be interested in a more modern one (ES2015) [using Webpack with OpenLayers](https://gist.github.com/tschaub/79025aef325cd2837364400a105405b8). This tutorial serves as a suggested project setup using NPM and Browserify
for the most basic needs. There are several other options and in particular
you might be interested in
[compiling your own code together with OpenLayers](closure.html).
## Initial steps ## Initial steps
Create a new empty directory for your project and navigate to it by running `mkdir new-project && cd new-project`. Initialize your project using `npm init` and answer the questions asked. Create a new empty directory for your project and navigate to it by running
`mkdir new-project && cd new-project`. Initialize your project using `npm init`
and answer the questions asked.
Add OpenLayers as dependency to your application with `npm install --save ol`. At this point you can ask NPM to add required dependencies by running
`npm install --save-dev openlayers browserify watchify uglify-js`. Watchify and
At this point you can ask NPM to add required development dependencies by running Uglify will be used to monitor for changes and to build into a minified
``` bundle.
npm install --save-dev cssify browserify cssify http-server uglify-js watchify
npm install --save-dev babelify babel-plugin-transform-es2015-modules-commonjs
```
We will be using `cssify` to include the css definitions required by OpenLayers in our bundle. `watchify`, `http-server` and `uglify-js` are used to monitor for changes and to build into a minified bundle. `babelify` and `babel-plugin-transform-es2015-modules-commonjs` are used to make the `ol` package, which was created using ES2015 modules, work with CommonJS.
## Application code and index.html ## Application code and index.html
Place your application code in `index.js`. Here is a simple starting point: Place your application code in `index.js`. Here is a simple starting point:
```js ```js
require('ol/ol.css'); var ol = require('openlayers');
var ol_Map = require('ol/map').default;
var ol_layer_Tile = require('ol/layer/tile').default;
var ol_source_OSM = require('ol/source/osm').default;
var ol_View = require('ol/view').default;
var map = new ol_Map({ var map = new ol.Map({
target: 'map', target: 'map',
layers: [ layers: [
new ol_layer_Tile({ new ol.layer.Tile({
source: new ol_source_OSM() source: new ol.source.OSM()
}) })
], ],
view: new ol_View({ view: new ol.View({
center: [0, 0], center: [0, 0],
zoom: 0 zoom: 0
}) })
}); });
``` ```
You will also need an `ìndex.html` file that will use your bundle. Here is a simple example: You will also need an `ìndex.html` file that will use your bundle. Here is a simple
example:
```html ```html
<!DOCTYPE html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>Using Browserify with OpenLayers</title> <title>Using Browserify with OpenLayers</title>
<link rel="stylesheet" href="node_modules/openlayers/dist/ol.css" type="text/css">
<style> <style>
#map { #map {
width: 400px; width: 400px;
@@ -71,17 +72,18 @@ You will also need an `ìndex.html` file that will use your bundle. Here is a si
## Creating a bundle ## Creating a bundle
With simple scripts you can introduce the commands `npm run build` and `npm start` to manually build your bundle and watch for changes, respectively. Add the following to the script section in `package.json`: With simple scripts you can introduce the commands `npm run build` and `npm start` to
manually build your bundle and watch for changes, respectively. Add the following
to the script section in `package.json`:
```json ```json
"scripts": { "scripts": {
"start": "watchify index.js -g cssify --outfile bundle.js & http-server", "start": "watchify index.js --outfile bundle.js",
"build": "browserify -g cssify index.js | uglifyjs --compress --output bundle.js" "build": "browserify index.js | uglifyjs --compress --output bundle.js"
} }
``` ```
Now to test your application open http://localhost:8080/ in your browser. `watchify` will update `bundle.js` whenever you change something. You simply need to reload the page in your browser to see the changes.
```
$ npm start
```
Note that `bundle.js` will contain your application code and all dependencies used in your application. From OpenLayers, it only contains the required components. Note that `bundle.js` will contain your application code and all dependencies
used in your application, in this case the official full build of OpenLayers.
If you only need parts of OpenLayers you can create
[custom builds](../../builder).

View File

@@ -5,15 +5,11 @@ layout: doc.hbs
# Compiling Application with Closure Compiler # Compiling Application with Closure Compiler
**Note**: When building an application with dependencies that are available as [npm](https://npmjs.com/) packages, it will probably be easier to use the [ol](https://npmjs.com/package/ol) package and follow the instructions there.
The OpenLayers code uses the Closure Library, and it is compiled with the The OpenLayers code uses the Closure Library, and it is compiled with the
Closure Compiler. Using OpenLayers in an application does not require using Closure Compiler. Using OpenLayers in an application does not require using
Closure. But using Closure in an OpenLayers application is possible. And this Closure. But using Closure in an OpenLayers application is possible. And this
is what this tutorial is about. is what this tutorial is about.
When you want to include OpenLayers as separate script without bundling with your application, follow the [Creating custom builds](./custom-builds.html) tutorial instead.
This tutorial will teach you how to set up an OpenLayers application based on This tutorial will teach you how to set up an OpenLayers application based on
the [`closure-util`](https://github.com/openlayers/closure-util) node package, the [`closure-util`](https://github.com/openlayers/closure-util) node package,
which provides utilities for working with Closure. Using `closure-util` is one which provides utilities for working with Closure. Using `closure-util` is one

View File

@@ -45,7 +45,7 @@ The easiest way to use a custom projection is to add the [Proj4js](http://proj4j
Following example shows definition of a [British National Grid](https://epsg.io/27700): Following example shows definition of a [British National Grid](https://epsg.io/27700):
``` html ``` html
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.3/proj4.js"></script>
``` ```
``` javascript ``` javascript

View File

@@ -1,8 +1,9 @@
goog.require('ol.Collection');
goog.require('ol.Map'); goog.require('ol.Map');
goog.require('ol.View'); goog.require('ol.View');
goog.require('ol.events.condition');
goog.require('ol.interaction.Draw'); goog.require('ol.interaction.Draw');
goog.require('ol.interaction.Modify'); goog.require('ol.interaction.Modify');
goog.require('ol.interaction.Snap');
goog.require('ol.layer.Tile'); goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector'); goog.require('ol.layer.Vector');
goog.require('ol.source.OSM'); goog.require('ol.source.OSM');
@@ -16,9 +17,18 @@ var raster = new ol.layer.Tile({
source: new ol.source.OSM() source: new ol.source.OSM()
}); });
var source = new ol.source.Vector(); var map = new ol.Map({
var vector = new ol.layer.Vector({ layers: [raster],
source: source, target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var features = new ol.Collection();
var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector({features: features}),
style: new ol.style.Style({ style: new ol.style.Style({
fill: new ol.style.Fill({ fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)' color: 'rgba(255, 255, 255, 0.2)'
@@ -35,40 +45,38 @@ var vector = new ol.layer.Vector({
}) })
}) })
}); });
featureOverlay.setMap(map);
var map = new ol.Map({ var modify = new ol.interaction.Modify({
layers: [raster, vector], features: features,
target: 'map', // the SHIFT key must be pressed to delete vertices, so
view: new ol.View({ // that new vertices can be drawn at the same position
center: [-11000000, 4600000], // of existing vertices
zoom: 4 deleteCondition: function(event) {
}) return ol.events.condition.shiftKeyOnly(event) &&
ol.events.condition.singleClick(event);
}
}); });
var modify = new ol.interaction.Modify({source: source});
map.addInteraction(modify); map.addInteraction(modify);
var draw, snap; // global so we can remove them later var draw; // global so we can remove it later
var typeSelect = document.getElementById('type'); var typeSelect = document.getElementById('type');
function addInteractions() { function addInteraction() {
draw = new ol.interaction.Draw({ draw = new ol.interaction.Draw({
source: source, features: features,
type: /** @type {ol.geom.GeometryType} */ (typeSelect.value) type: /** @type {ol.geom.GeometryType} */ (typeSelect.value)
}); });
map.addInteraction(draw); map.addInteraction(draw);
snap = new ol.interaction.Snap({source: source});
map.addInteraction(snap);
} }
/** /**
* Handle change event. * Handle change event.
*/ */
typeSelect.onchange = function() { typeSelect.onchange = function() {
map.removeInteraction(draw); map.removeInteraction(draw);
map.removeInteraction(snap); addInteraction();
addInteractions();
}; };
addInteractions(); addInteraction();

View File

@@ -144,7 +144,7 @@ var map = new ol.Map({
layers: [raster, vector], layers: [raster, vector],
interactions: ol.interaction.defaults().extend([new ol.interaction.Select({ interactions: ol.interaction.defaults().extend([new ol.interaction.Select({
condition: function(evt) { condition: function(evt) {
return evt.type == 'pointermove' || return evt.originalEvent.type == 'mousemove' ||
evt.type == 'singleclick'; evt.type == 'singleclick';
}, },
style: selectStyleFunction style: selectStyleFunction

View File

@@ -6,6 +6,7 @@ goog.require('ol.source.OSM');
goog.require('ol.source.VectorTile'); goog.require('ol.source.VectorTile');
goog.require('ol.layer.Tile'); goog.require('ol.layer.Tile');
goog.require('ol.layer.VectorTile'); goog.require('ol.layer.VectorTile');
goog.require('ol.tilegrid');
goog.require('ol.proj.Projection'); goog.require('ol.proj.Projection');
@@ -76,6 +77,8 @@ fetch(url).then(function(response) {
}); });
var vectorSource = new ol.source.VectorTile({ var vectorSource = new ol.source.VectorTile({
format: new ol.format.GeoJSON(), format: new ol.format.GeoJSON(),
tileGrid: ol.tilegrid.createXYZ(),
tilePixelRatio: 16,
tileLoadFunction: function(tile) { tileLoadFunction: function(tile) {
var format = tile.getFormat(); var format = tile.getFormat();
var tileCoord = tile.getTileCoord(); var tileCoord = tile.getTileCoord();

View File

@@ -10,15 +10,12 @@ goog.require('ol.style.Stroke');
var map = new ol.Map({ var map = new ol.Map({
layers: [ layers: [
new ol.layer.Tile({ new ol.layer.Tile({
source: new ol.source.OSM({ source: new ol.source.OSM()
wrapX: false
})
}) })
], ],
target: 'map', target: 'map',
view: new ol.View({ view: new ol.View({
center: ol.proj.fromLonLat([4.8, 47.75]), center: ol.proj.fromLonLat([4.8, 47.75]),
extent: ol.proj.get('EPSG:3857').getExtent(),
zoom: 5 zoom: 5
}) })
}); });

View File

@@ -17,7 +17,7 @@ var key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiRk1kMWZaSSJ9.E5BkluenyWQMsBLsuByrmg';
// Calculation of resolutions that match zoom levels 1, 3, 5, 7, 9, 11, 13, 15. // Calculation of resolutions that match zoom levels 1, 3, 5, 7, 9, 11, 13, 15.
var resolutions = []; var resolutions = [];
for (var i = 0; i <= 8; ++i) { for (var i = 0; i <= 7; ++i) {
resolutions.push(156543.03392804097 / Math.pow(2, i * 2)); resolutions.push(156543.03392804097 / Math.pow(2, i * 2));
} }
// Calculation of tile urls for zoom levels 1, 3, 5, 7, 9, 11, 13, 15. // Calculation of tile urls for zoom levels 1, 3, 5, 7, 9, 11, 13, 15.
@@ -44,6 +44,7 @@ var map = new ol.Map({
resolutions: resolutions, resolutions: resolutions,
tileSize: 512 tileSize: 512
}), }),
tilePixelRatio: 8,
tileUrlFunction: tileUrlFunction tileUrlFunction: tileUrlFunction
}), }),
style: createMapboxStreetsV6Style() style: createMapboxStreetsV6Style()

View File

@@ -10,6 +10,7 @@ goog.require('ol.style.Icon');
goog.require('ol.style.Stroke'); goog.require('ol.style.Stroke');
goog.require('ol.style.Style'); goog.require('ol.style.Style');
goog.require('ol.style.Text'); goog.require('ol.style.Text');
goog.require('ol.tilegrid');
var key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiRk1kMWZaSSJ9.E5BkluenyWQMsBLsuByrmg'; var key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiRk1kMWZaSSJ9.E5BkluenyWQMsBLsuByrmg';
@@ -22,6 +23,8 @@ var map = new ol.Map({
'© <a href="https://www.openstreetmap.org/copyright">' + '© <a href="https://www.openstreetmap.org/copyright">' +
'OpenStreetMap contributors</a>', 'OpenStreetMap contributors</a>',
format: new ol.format.MVT(), format: new ol.format.MVT(),
tileGrid: ol.tilegrid.createXYZ({maxZoom: 22}),
tilePixelRatio: 16,
url: 'https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' + url: 'https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' +
'{z}/{x}/{y}.vector.pbf?access_token=' + key '{z}/{x}/{y}.vector.pbf?access_token=' + key
}), }),

View File

@@ -1,24 +1,20 @@
--- ---
layout: example.html layout: example.html
title: Measure title: Measure
shortdesc: Using a draw interaction to measure lengths and areas. shortdesc: Example of using the ol.interaction.Draw interaction to create a simple measuring application.
docs: > docs: >
<p>The <code>ol.Sphere.getLength()</code> and <code>ol.Sphere.getArea()</code> <p><i>NOTE: By default, length and area are calculated using the projected coordinates. This is not accurate for projections like Mercator where the projected meters do not correspond to meters on the ground. To get a standarized measurement across all projections, use the geodesic measures.</i></p>
functions calculate spherical lengths and areas for geometries. Lengths are
calculated by assuming great circle segments between geometry coordinates.
Areas are calculated as if edges of polygons were great circle segments.</p>
<p>Note that the <code>geometry.getLength()</code> and <code>geometry.getArea()</code>
methods return measures of projected (planar) geometries. These can be very
different than on-the-ground measures in certain situations — in northern
and southern latitudes using Web Mercator for example. For better results,
use the functions on <code>ol.Sphere</code>.</p>
tags: "draw, edit, measure, vector" tags: "draw, edit, measure, vector"
--- ---
<div id="map" class="map"></div> <div id="map" class="map"></div>
<form class="form-inline"> <form class="form-inline">
<label>Measurement type &nbsp;</label> <label>Measurement type &nbsp;</label>
<select id="type"> <select id="type">
<option value="length">Length (LineString)</option> <option value="length">Length (LineString)</option>
<option value="area">Area (Polygon)</option> <option value="area">Area (Polygon)</option>
</select> </select>
<label class="checkbox">
<input type="checkbox" id="geodesic">
use geodesic measures
</label>
</form> </form>

View File

@@ -8,6 +8,7 @@ goog.require('ol.geom.Polygon');
goog.require('ol.interaction.Draw'); goog.require('ol.interaction.Draw');
goog.require('ol.layer.Tile'); goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector'); goog.require('ol.layer.Vector');
goog.require('ol.proj');
goog.require('ol.source.OSM'); goog.require('ol.source.OSM');
goog.require('ol.source.Vector'); goog.require('ol.source.Vector');
goog.require('ol.style.Circle'); goog.require('ol.style.Circle');
@@ -16,6 +17,8 @@ goog.require('ol.style.Stroke');
goog.require('ol.style.Style'); goog.require('ol.style.Style');
var wgs84Sphere = new ol.Sphere(6378137);
var raster = new ol.layer.Tile({ var raster = new ol.layer.Tile({
source: new ol.source.OSM() source: new ol.source.OSM()
}); });
@@ -134,6 +137,7 @@ map.getViewport().addEventListener('mouseout', function() {
}); });
var typeSelect = document.getElementById('type'); var typeSelect = document.getElementById('type');
var geodesicCheckbox = document.getElementById('geodesic');
var draw; // global so we can remove it later var draw; // global so we can remove it later
@@ -144,7 +148,19 @@ var draw; // global so we can remove it later
* @return {string} The formatted length. * @return {string} The formatted length.
*/ */
var formatLength = function(line) { var formatLength = function(line) {
var length = ol.Sphere.getLength(line); var length;
if (geodesicCheckbox.checked) {
var coordinates = line.getCoordinates();
length = 0;
var sourceProj = map.getView().getProjection();
for (var i = 0, ii = coordinates.length - 1; i < ii; ++i) {
var c1 = ol.proj.transform(coordinates[i], sourceProj, 'EPSG:4326');
var c2 = ol.proj.transform(coordinates[i + 1], sourceProj, 'EPSG:4326');
length += wgs84Sphere.haversineDistance(c1, c2);
}
} else {
length = Math.round(line.getLength() * 100) / 100;
}
var output; var output;
if (length > 100) { if (length > 100) {
output = (Math.round(length / 1000 * 100) / 100) + output = (Math.round(length / 1000 * 100) / 100) +
@@ -163,7 +179,16 @@ var formatLength = function(line) {
* @return {string} Formatted area. * @return {string} Formatted area.
*/ */
var formatArea = function(polygon) { var formatArea = function(polygon) {
var area = ol.Sphere.getArea(polygon); var area;
if (geodesicCheckbox.checked) {
var sourceProj = map.getView().getProjection();
var geom = /** @type {ol.geom.Polygon} */(polygon.clone().transform(
sourceProj, 'EPSG:4326'));
var coordinates = geom.getLinearRing(0).getCoordinates();
area = Math.abs(wgs84Sphere.geodesicArea(coordinates));
} else {
area = polygon.getArea();
}
var output; var output;
if (area > 10000) { if (area > 10000) {
output = (Math.round(area / 1000000 * 100) / 100) + output = (Math.round(area / 1000000 * 100) / 100) +

View File

@@ -7,6 +7,8 @@ goog.require('ol.source.VectorTile');
goog.require('ol.style.Fill'); goog.require('ol.style.Fill');
goog.require('ol.style.Stroke'); goog.require('ol.style.Stroke');
goog.require('ol.style.Style'); goog.require('ol.style.Style');
goog.require('ol.tilegrid');
var key = 'vector-tiles-5eJz6JX'; var key = 'vector-tiles-5eJz6JX';
@@ -68,7 +70,7 @@ var map = new ol.Map({
layerName: 'layer', layerName: 'layer',
layers: ['water', 'roads', 'buildings'] layers: ['water', 'roads', 'buildings']
}), }),
maxZoom: 19, tileGrid: ol.tilegrid.createXYZ({maxZoom: 19}),
url: 'https://tile.mapzen.com/mapzen/vector/v1/all/{z}/{x}/{y}.topojson?api_key=' + key url: 'https://tile.mapzen.com/mapzen/vector/v1/all/{z}/{x}/{y}.topojson?api_key=' + key
}), }),
style: function(feature, resolution) { style: function(feature, resolution) {

View File

@@ -8,7 +8,7 @@ docs: >
in <a href="https://epsg.io/">EPSG.io</a> database. in <a href="https://epsg.io/">EPSG.io</a> database.
tags: "reprojection, projection, proj4js, epsg.io" tags: "reprojection, projection, proj4js, epsg.io"
resources: resources:
- https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js - https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.3/proj4.js
--- ---
<div id="map" class="map"></div> <div id="map" class="map"></div>
<form class="form-inline"> <form class="form-inline">

View File

@@ -6,6 +6,6 @@ docs: >
This example shows client-side reprojection of single image source. This example shows client-side reprojection of single image source.
tags: "reprojection, projection, proj4js, image, imagestatic" tags: "reprojection, projection, proj4js, image, imagestatic"
resources: resources:
- https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js - https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.3/proj4.js
--- ---
<div id="map" class="map"></div> <div id="map" class="map"></div>

View File

@@ -6,7 +6,7 @@ docs: >
This example shows client-side raster reprojection between various projections. This example shows client-side raster reprojection between various projections.
tags: "reprojection, projection, proj4js, osm, wms, wmts, hidpi" tags: "reprojection, projection, proj4js, osm, wms, wmts, hidpi"
resources: resources:
- https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js - https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.3/proj4.js
--- ---
<div id="map" class="map"></div> <div id="map" class="map"></div>
<form class="form-inline"> <form class="form-inline">

View File

@@ -6,6 +6,6 @@ docs: >
This example shows client-side reprojection of OpenStreetMap to NAD83 Indiana East, including a ScaleLine control with US units. This example shows client-side reprojection of OpenStreetMap to NAD83 Indiana East, including a ScaleLine control with US units.
tags: "reprojection, projection, openstreetmap, nad83, tile, scaleline" tags: "reprojection, projection, openstreetmap, nad83, tile, scaleline"
resources: resources:
- https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js - https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.3/proj4.js
--- ---
<div id="map" class="map"></div> <div id="map" class="map"></div>

View File

@@ -6,6 +6,6 @@ docs: >
Example of a Sphere Mollweide map with a Graticule component. Example of a Sphere Mollweide map with a Graticule component.
tags: "graticule, Mollweide, projection, proj4js" tags: "graticule, Mollweide, projection, proj4js"
resources: resources:
- https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js - https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.3/proj4.js
--- ---
<div id="map" class="map"></div> <div id="map" class="map"></div>

View File

@@ -1,17 +0,0 @@
---
layout: example.html
title: Street Labels
shortdesc: Render street names with a custom render.
docs: >
Example showing the use of a custom renderer to render text along a path. [Labelgun](https://github.com/Geovation/labelgun) is used to avoid label collisions. [label-segment](https://github.com/ahocevar/label-segment) makes sure that labels are placed on suitable street segments. [textpath](https://github.com/ahocevar/textpath) arranges the letters of a label along the geometry. The data is fetched from OSM using the [Overpass API](https://overpass-api.de).
tags: "vector, label, collision detection, labelgun, linelabel, overpass"
resources:
- https://cdn.polyfill.io/v2/polyfill.min.js?features=Set"
- https://unpkg.com/rbush@2.0.1/rbush.min.js
- https://unpkg.com/labelgun@0.1.1/lib/labelgun.min.js
- https://unpkg.com/textpath@1.0.1/dist/textpath.js
- https://unpkg.com/label-segment@1.0.0/dist/label-segment.js
cloak:
As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5: Your Bing Maps Key from http://www.bingmapsportal.com/ here
---
<div id="map" class="map"></div>

View File

@@ -1,115 +0,0 @@
// NOCOMPILE
/* global labelgun, labelSegment, textPath */
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.extent');
goog.require('ol.format.OSMXML');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.BingMaps');
goog.require('ol.source.Vector');
goog.require('ol.style.Style');
var emptyFn = function() {};
var labelEngine = new labelgun['default'](emptyFn, emptyFn);
var context, pixelRatio; // Will be set in the map's postcompose listener
function measureText(text) {
return context.measureText(text).width * pixelRatio;
}
var extent, letters; // Will be set in the style's renderer function
function collectDrawData(letter, x, y, angle) {
ol.extent.extend(extent, [x, y, x, y]);
letters.push([x, y, angle, letter]);
}
var style = new ol.style.Style({
renderer: function(coords, context) {
var feature = context.feature;
var text = feature.get('name');
// Only create label when geometry has a long and straight segment
var path = labelSegment(coords, Math.PI / 8, measureText(text));
if (path) {
extent = ol.extent.createEmpty();
letters = [];
textPath(text, path, measureText, collectDrawData);
ol.extent.buffer(extent, 5 * pixelRatio, extent);
var bounds = {
bottomLeft: ol.extent.getBottomLeft(extent),
topRight: ol.extent.getTopRight(extent)
};
labelEngine.ingestLabel(bounds, feature.getId(), 1, letters, text, false);
}
}
});
var rasterLayer = new ol.layer.Tile({
source: new ol.source.BingMaps({
key: 'As1HiMj1PvLPlqc_gtM7AqZfBL8ZL3VrjaS3zIb22Uvb9WKhuJObROC-qUpa81U5',
imagerySet: 'Aerial'
})
});
var source = new ol.source.Vector();
// Request streets from OSM, using the Overpass API
fetch('https://overpass-api.de/api/interpreter', {
method: 'POST',
body: '(way["highway"](48.19642,16.32580,48.22050,16.41986));(._;>;);out meta;'
}).then(function(response) {
return response.text();
}).then(function(responseText) {
var features = new ol.format.OSMXML().readFeatures(responseText, {
featureProjection: 'EPSG:3857'
});
source.addFeatures(features);
});
var vectorLayer = new ol.layer.Vector({
source: source,
style: function(feature) {
if (feature.getGeometry().getType() == 'LineString' && feature.get('name')) {
return style;
}
}
});
var viewExtent = [1817379, 6139595, 1827851, 6143616];
var map = new ol.Map({
layers: [rasterLayer, vectorLayer],
target: 'map',
view: new ol.View({
extent: viewExtent,
center: ol.extent.getCenter(viewExtent),
zoom: 17,
minZoom: 14
})
});
vectorLayer.on('precompose', function() {
labelEngine.destroy();
});
vectorLayer.on('postcompose', function(e) {
context = e.context;
pixelRatio = e.frameState.pixelRatio;
context.save();
context.font = 'normal 11px "Open Sans", "Arial Unicode MS"';
context.fillStyle = 'white';
context.textBaseline = 'middle';
context.textAlign = 'center';
var labels = labelEngine.getShown();
for (var i = 0, ii = labels.length; i < ii; ++i) {
// Render label letter by letter
var letters = labels[i].labelObject;
for (var j = 0, jj = letters.length; j < jj; ++j) {
var labelData = letters[j];
context.save();
context.translate(labelData[0], labelData[1]);
context.rotate(labelData[2]);
context.scale(pixelRatio, pixelRatio);
context.fillText(labelData[3], 0, 0);
context.restore();
}
}
context.restore();
});

View File

@@ -1,13 +0,0 @@
---
layout: example.html
title: Vector Label Decluttering
shortdesc: Label decluttering with a custom renderer.
resources:
- https://cdn.polyfill.io/v2/polyfill.min.js?features=Set"
- https://unpkg.com/rbush@2.0.1/rbush.min.js
- https://unpkg.com/labelgun@0.1.1/lib/labelgun.min.js
docs: >
A custom `renderer` function is used instead of an `ol.style.Text` to label the countries of the world. Only texts that are not wider than their country's bounding box are considered and handed over to [Labelgun](https://github.com/Geovation/labelgun) for decluttering.
tags: "vector, renderer, labelgun, label"
---
<div id="map" class="map"></div>

View File

@@ -1,125 +0,0 @@
// NOCOMPILE
/* global labelgun */
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.extent');
goog.require('ol.format.GeoJSON');
goog.require('ol.layer.Vector');
goog.require('ol.source.Vector');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
goog.require('ol.style.Style');
// Style for labels
function setStyle(context) {
context.font = '12px Calibri,sans-serif';
context.fillStyle = '#000';
context.strokeStyle = '#fff';
context.lineWidth = 3;
context.textBaseline = 'hanging';
context.textAlign = 'start';
}
// A separate canvas context for measuring label width and height.
var textMeasureContext = document.createElement('CANVAS').getContext('2d');
setStyle(textMeasureContext);
// The label height is approximated by the width of the text 'WI'.
var height = textMeasureContext.measureText('WI').width;
// A cache for reusing label images once they have been created.
var textCache = {};
var map = new ol.Map({
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 1
})
});
var emptyFn = function() {};
var labelEngine = new labelgun['default'](emptyFn, emptyFn);
function createLabel(canvas, text, coord) {
var halfWidth = canvas.width / 2;
var halfHeight = canvas.height / 2;
var bounds = {
bottomLeft: [Math.round(coord[0] - halfWidth), Math.round(coord[1] - halfHeight)],
topRight: [Math.round(coord[0] + halfWidth), Math.round(coord[1] + halfHeight)]
};
labelEngine.ingestLabel(bounds, coord.toString(), 1, canvas, text, false);
}
// For multi-polygons, we only label the widest polygon. This is done by sorting
// by extent width in descending order, and take the first from the array.
function sortByWidth(a, b) {
return ol.extent.getWidth(b.getExtent()) - ol.extent.getWidth(a.getExtent());
}
var labelStyle = new ol.style.Style({
renderer: function(coords, state) {
var text = state.feature.get('name');
createLabel(textCache[text], text, coords);
}
});
var countryStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.6)'
}),
stroke: new ol.style.Stroke({
color: '#319FD3',
width: 1
})
});
var styleWithLabel = [countryStyle, labelStyle];
var styleWithoutLabel = [countryStyle];
var pixelRatio; // This is set by the map's precompose listener
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: 'data/geojson/countries.geojson',
format: new ol.format.GeoJSON()
}),
style: function(feature, resolution) {
var text = feature.get('name');
var width = textMeasureContext.measureText(text).width;
var geometry = feature.getGeometry();
if (geometry.getType() == 'MultiPolygon') {
geometry = geometry.getPolygons().sort(sortByWidth)[0];
}
var extentWidth = ol.extent.getWidth(geometry.getExtent());
if (extentWidth / resolution > width) {
// Only consider label when it fits its geometry's extent
if (!(text in textCache)) {
// Draw the label to its own canvas and cache it.
var canvas = textCache[text] = document.createElement('CANVAS');
canvas.width = width * pixelRatio;
canvas.height = height * pixelRatio;
var context = canvas.getContext('2d');
context.scale(pixelRatio, pixelRatio);
setStyle(context);
context.strokeText(text, 0, 0);
context.fillText(text, 0, 0);
}
labelStyle.setGeometry(geometry.getInteriorPoint());
return styleWithLabel;
} else {
return styleWithoutLabel;
}
}
});
vectorLayer.on('precompose', function(e) {
pixelRatio = e.frameState.pixelRatio;
labelEngine.destroy();
});
vectorLayer.on('postcompose', function(e) {
var labels = labelEngine.getShown();
for (var i = 0, ii = labels.length; i < ii; ++i) {
var label = labels[i];
// Draw label to the map canvas
e.context.drawImage(label.labelObject, label.minX, label.minY);
}
});
map.addLayer(vectorLayer);

View File

@@ -6,7 +6,7 @@ docs: >
With [Proj4js](http://proj4js.org/) integration, OpenLayers can transform coordinates between arbitrary projections. With [Proj4js](http://proj4js.org/) integration, OpenLayers can transform coordinates between arbitrary projections.
tags: "wms, single image, proj4js, projection" tags: "wms, single image, proj4js, projection"
resources: resources:
- https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js - https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.3/proj4.js
- https://epsg.io/21781-1753.js - https://epsg.io/21781-1753.js
--- ---
<div id="map" class="map"></div> <div id="map" class="map"></div>

View File

@@ -91,17 +91,6 @@ oli.DrawEvent = function() {};
oli.DrawEvent.prototype.feature; oli.DrawEvent.prototype.feature;
/**
* @interface
*/
oli.ExtentEvent = function() {};
/**
* @type {ol.Extent}
*/
oli.ExtentEvent.prototype.extent;
/** /**
* @interface * @interface
*/ */

View File

@@ -436,33 +436,6 @@ olx.MapOptions.prototype.target;
olx.MapOptions.prototype.view; olx.MapOptions.prototype.view;
/**
* Object literal with options for the {@link ol.Sphere.getLength} or
* {@link ol.Sphere.getArea} functions.
* @typedef {{projection: (ol.ProjectionLike|undefined),
* radius: (number|undefined)}}
*/
olx.SphereMetricOptions;
/**
* Projection of the geometry. By default, the geometry is assumed to be in
* EPSG:3857 (Web Mercator).
* @type {(ol.ProjectionLike|undefined)}
* @api
*/
olx.SphereMetricOptions.prototype.projection;
/**
* Sphere radius. By default, the radius of the earth is used (Clarke 1866
* Authalic Sphere).
* @type {(number|undefined)}
* @api
*/
olx.SphereMetricOptions.prototype.radius;
/** /**
* Object literal with options for the {@link ol.Map#forEachFeatureAtPixel} and * Object literal with options for the {@link ol.Map#forEachFeatureAtPixel} and
* {@link ol.Map#hasFeatureAtPixel} methods. * {@link ol.Map#hasFeatureAtPixel} methods.
@@ -2737,7 +2710,6 @@ olx.interaction.DoubleClickZoomOptions.prototype.delta;
/** /**
* @typedef {{formatConstructors: (Array.<function(new: ol.format.Feature)>|undefined), * @typedef {{formatConstructors: (Array.<function(new: ol.format.Feature)>|undefined),
* source: (ol.source.Vector|undefined),
* projection: ol.ProjectionLike, * projection: ol.ProjectionLike,
* target: (Element|undefined)}} * target: (Element|undefined)}}
*/ */
@@ -2752,18 +2724,6 @@ olx.interaction.DragAndDropOptions;
olx.interaction.DragAndDropOptions.prototype.formatConstructors; olx.interaction.DragAndDropOptions.prototype.formatConstructors;
/**
* Optional vector source where features will be added. If a source is provided
* all existing features will be removed and new features will be added when
* they are dropped on the target. If you want to add features to a vector
* source without removing the existing features (append only), instead of
* providing the source option listen for the "addfeatures" event.
* @type {ol.source.Vector|undefined}
* @api
*/
olx.interaction.DragAndDropOptions.prototype.source;
/** /**
* Target projection. By default, the map's view's projection is used. * Target projection. By default, the map's view's projection is used.
* @type {ol.ProjectionLike} * @type {ol.ProjectionLike}
@@ -3259,8 +3219,7 @@ olx.interaction.KeyboardZoomOptions.prototype.delta;
* insertVertexCondition: (ol.EventsConditionType|undefined), * insertVertexCondition: (ol.EventsConditionType|undefined),
* pixelTolerance: (number|undefined), * pixelTolerance: (number|undefined),
* style: (ol.style.Style|Array.<ol.style.Style>|ol.StyleFunction|undefined), * style: (ol.style.Style|Array.<ol.style.Style>|ol.StyleFunction|undefined),
* source: (ol.source.Vector|undefined), * features: ol.Collection.<ol.Feature>,
* features: (ol.Collection.<ol.Feature>|undefined),
* wrapX: (boolean|undefined) * wrapX: (boolean|undefined)
* }} * }}
*/ */
@@ -3318,18 +3277,8 @@ olx.interaction.ModifyOptions.prototype.style;
/** /**
* The vector source with features to modify. If a vector source is not * The features the interaction works on.
* provided, a feature collection must be provided with the features option. * @type {ol.Collection.<ol.Feature>}
* @type {ol.source.Vector|undefined}
* @api
*/
olx.interaction.ModifyOptions.prototype.source;
/**
* The features the interaction works on. If a feature collection is not
* provided, a vector source must be provided with the source option.
* @type {ol.Collection.<ol.Feature>|undefined}
* @api * @api
*/ */
olx.interaction.ModifyOptions.prototype.features; olx.interaction.ModifyOptions.prototype.features;
@@ -3902,8 +3851,7 @@ olx.layer.GroupOptions.prototype.layers;
* maxResolution: (number|undefined), * maxResolution: (number|undefined),
* opacity: (number|undefined), * opacity: (number|undefined),
* source: (ol.source.Vector|undefined), * source: (ol.source.Vector|undefined),
* visible: (boolean|undefined), * visible: (boolean|undefined)}}
* zIndex: (number|undefined)}}
*/ */
olx.layer.HeatmapOptions; olx.layer.HeatmapOptions;
@@ -4000,15 +3948,6 @@ olx.layer.HeatmapOptions.prototype.source;
olx.layer.HeatmapOptions.prototype.visible; olx.layer.HeatmapOptions.prototype.visible;
/**
* The z-index for layer rendering. At rendering time, the layers will be
* ordered, first by Z-index and then by position. The default Z-index is 0.
* @type {number|undefined}
* @api
*/
olx.layer.HeatmapOptions.prototype.zIndex;
/** /**
* @typedef {{opacity: (number|undefined), * @typedef {{opacity: (number|undefined),
* map: (ol.Map|undefined), * map: (ol.Map|undefined),
@@ -4016,8 +3955,7 @@ olx.layer.HeatmapOptions.prototype.zIndex;
* visible: (boolean|undefined), * visible: (boolean|undefined),
* extent: (ol.Extent|undefined), * extent: (ol.Extent|undefined),
* minResolution: (number|undefined), * minResolution: (number|undefined),
* maxResolution: (number|undefined), * maxResolution: (number|undefined)}}
* zIndex: (number|undefined)}}
*/ */
olx.layer.ImageOptions; olx.layer.ImageOptions;
@@ -4082,15 +4020,6 @@ olx.layer.ImageOptions.prototype.minResolution;
olx.layer.ImageOptions.prototype.maxResolution; olx.layer.ImageOptions.prototype.maxResolution;
/**
* The z-index for layer rendering. At rendering time, the layers will be
* ordered, first by Z-index and then by position. The default Z-index is 0.
* @type {number|undefined}
* @api
*/
olx.layer.ImageOptions.prototype.zIndex;
/** /**
* @typedef {{opacity: (number|undefined), * @typedef {{opacity: (number|undefined),
* preload: (number|undefined), * preload: (number|undefined),
@@ -4100,8 +4029,7 @@ olx.layer.ImageOptions.prototype.zIndex;
* extent: (ol.Extent|undefined), * extent: (ol.Extent|undefined),
* minResolution: (number|undefined), * minResolution: (number|undefined),
* maxResolution: (number|undefined), * maxResolution: (number|undefined),
* useInterimTilesOnError: (boolean|undefined), * useInterimTilesOnError: (boolean|undefined)}}
* zIndex: (number|undefined)}}
*/ */
olx.layer.TileOptions; olx.layer.TileOptions;
@@ -4183,15 +4111,6 @@ olx.layer.TileOptions.prototype.maxResolution;
olx.layer.TileOptions.prototype.useInterimTilesOnError; olx.layer.TileOptions.prototype.useInterimTilesOnError;
/**
* The z-index for layer rendering. At rendering time, the layers will be
* ordered, first by Z-index and then by position. The default Z-index is 0.
* @type {number|undefined}
* @api
*/
olx.layer.TileOptions.prototype.zIndex;
/** /**
* @typedef {{renderOrder: (ol.RenderOrderFunction|null|undefined), * @typedef {{renderOrder: (ol.RenderOrderFunction|null|undefined),
* minResolution: (number|undefined), * minResolution: (number|undefined),
@@ -4203,8 +4122,7 @@ olx.layer.TileOptions.prototype.zIndex;
* style: (ol.style.Style|Array.<ol.style.Style>|ol.StyleFunction|undefined), * style: (ol.style.Style|Array.<ol.style.Style>|ol.StyleFunction|undefined),
* updateWhileAnimating: (boolean|undefined), * updateWhileAnimating: (boolean|undefined),
* updateWhileInteracting: (boolean|undefined), * updateWhileInteracting: (boolean|undefined),
* visible: (boolean|undefined), * visible: (boolean|undefined)}}
* zIndex: (number|undefined)}}
*/ */
olx.layer.VectorOptions; olx.layer.VectorOptions;
@@ -4319,15 +4237,6 @@ olx.layer.VectorOptions.prototype.updateWhileInteracting;
olx.layer.VectorOptions.prototype.visible; olx.layer.VectorOptions.prototype.visible;
/**
* The z-index for layer rendering. At rendering time, the layers will be
* ordered, first by Z-index and then by position. The default Z-index is 0.
* @type {number|undefined}
* @api
*/
olx.layer.VectorOptions.prototype.zIndex;
/** /**
* @typedef {{extent: (ol.Extent|undefined), * @typedef {{extent: (ol.Extent|undefined),
* map: (ol.Map|undefined), * map: (ol.Map|undefined),
@@ -4342,8 +4251,7 @@ olx.layer.VectorOptions.prototype.zIndex;
* style: (ol.style.Style|Array.<ol.style.Style>|ol.StyleFunction|undefined), * style: (ol.style.Style|Array.<ol.style.Style>|ol.StyleFunction|undefined),
* updateWhileAnimating: (boolean|undefined), * updateWhileAnimating: (boolean|undefined),
* updateWhileInteracting: (boolean|undefined), * updateWhileInteracting: (boolean|undefined),
* visible: (boolean|undefined), * visible: (boolean|undefined)}}
* zIndex: (number|undefined)}}
*/ */
olx.layer.VectorTileOptions; olx.layer.VectorTileOptions;
@@ -4485,15 +4393,6 @@ olx.layer.VectorTileOptions.prototype.updateWhileInteracting;
olx.layer.VectorTileOptions.prototype.visible; olx.layer.VectorTileOptions.prototype.visible;
/**
* The z-index for layer rendering. At rendering time, the layers will be
* ordered, first by Z-index and then by position. The default Z-index is 0.
* @type {number|undefined}
* @api
*/
olx.layer.VectorOptions.prototype.zIndex;
/** /**
* Namespace. * Namespace.
* @type {Object} * @type {Object}
@@ -4501,50 +4400,6 @@ olx.layer.VectorOptions.prototype.zIndex;
olx.render; olx.render;
/**
* @typedef {{context: CanvasRenderingContext2D,
* feature: (ol.Feature|ol.render.Feature),
* geometry: ol.geom.SimpleGeometry,
* pixelRatio: number,
* resolution: number,
* rotation: number}}
*/
olx.render.State;
/**
* Canvas context that the layer is being rendered to.
* @type {CanvasRenderingContext2D}
* @api
*/
olx.render.State.prototype.context;
/**
* Pixel ratio used by the layer renderer.
* @type {number}
* @api
*/
olx.render.State.prototype.pixelRatio;
/**
* Resolution that the render batch was created and optimized for. This is
* not the view's resolution that is being rendered.
* @type {number}
* @api
*/
olx.render.State.prototype.resolution;
/**
* Rotation of the rendered layer in radians.
* @type {number}
* @api
*/
olx.render.State.prototype.rotation;
/** /**
* @typedef {{size: (ol.Size|undefined), * @typedef {{size: (ol.Size|undefined),
* pixelRatio: (number|undefined)}} * pixelRatio: (number|undefined)}}
@@ -5001,6 +4856,7 @@ olx.source.TileImageOptions.prototype.wrapX;
* ol.TileLoadFunctionType)|undefined), * ol.TileLoadFunctionType)|undefined),
* tileGrid: (ol.tilegrid.TileGrid|undefined), * tileGrid: (ol.tilegrid.TileGrid|undefined),
* tileLoadFunction: (ol.TileLoadFunctionType|undefined), * tileLoadFunction: (ol.TileLoadFunctionType|undefined),
* tilePixelRatio: (number|undefined),
* tileUrlFunction: (ol.TileUrlFunctionType|undefined), * tileUrlFunction: (ol.TileUrlFunctionType|undefined),
* url: (string|undefined), * url: (string|undefined),
* urls: (Array.<string>|undefined), * urls: (Array.<string>|undefined),
@@ -5096,8 +4952,6 @@ olx.source.VectorTileOptions.prototype.tileGrid;
* var format = tile.getFormat(); * var format = tile.getFormat();
* tile.setFeatures(format.readFeatures(data)); * tile.setFeatures(format.readFeatures(data));
* tile.setProjection(format.readProjection(data)); * tile.setProjection(format.readProjection(data));
* // uncomment the line below for ol.format.MVT only
* //tile.setExtent(format.getLastExtent());
* }; * };
* }); * });
* ``` * ```
@@ -5107,6 +4961,17 @@ olx.source.VectorTileOptions.prototype.tileGrid;
olx.source.VectorTileOptions.prototype.tileLoadFunction; olx.source.VectorTileOptions.prototype.tileLoadFunction;
/**
* The pixel ratio used by the tile service. For example, if the tile
* service advertizes 256px by 256px tiles but actually sends 512px
* by 512px tiles (for retina/hidpi devices) then `tilePixelRatio`
* should be set to `2`. Default is `1`.
* @type {number|undefined}
* @api
*/
olx.source.VectorTileOptions.prototype.tilePixelRatio;
/** /**
* Optional function to get tile URL given a tile coordinate and the projection. * Optional function to get tile URL given a tile coordinate and the projection.
* @type {ol.TileUrlFunctionType|undefined} * @type {ol.TileUrlFunctionType|undefined}
@@ -6290,9 +6155,6 @@ olx.source.TileJSONOptions.prototype.wrapX;
* gutter: (number|undefined), * gutter: (number|undefined),
* hidpi: (boolean|undefined), * hidpi: (boolean|undefined),
* logo: (string|olx.LogoOptions|undefined), * logo: (string|olx.LogoOptions|undefined),
* tileClass: (function(new: ol.ImageTile, ol.TileCoord,
* ol.TileState, string, ?string,
* ol.TileLoadFunctionType)|undefined),
* tileGrid: (ol.tilegrid.TileGrid|undefined), * tileGrid: (ol.tilegrid.TileGrid|undefined),
* projection: ol.ProjectionLike, * projection: ol.ProjectionLike,
* reprojectionErrorThreshold: (number|undefined), * reprojectionErrorThreshold: (number|undefined),
@@ -6375,16 +6237,6 @@ olx.source.TileWMSOptions.prototype.hidpi;
olx.source.TileWMSOptions.prototype.logo; olx.source.TileWMSOptions.prototype.logo;
/**
* Class used to instantiate image tiles. Default is {@link ol.ImageTile}.
* @type {function(new: ol.ImageTile, ol.TileCoord,
* ol.TileState, string, ?string,
* ol.TileLoadFunctionType)|undefined}
* @api
*/
olx.source.TileWMSOptions.prototype.tileClass;
/** /**
* Tile grid. Base this on the resolutions, tilesize and extent supported by the * Tile grid. Base this on the resolutions, tilesize and extent supported by the
* server. * server.
@@ -7756,7 +7608,6 @@ olx.style.TextOptions.prototype.stroke;
* @typedef {{geometry: (undefined|string|ol.geom.Geometry|ol.StyleGeometryFunction), * @typedef {{geometry: (undefined|string|ol.geom.Geometry|ol.StyleGeometryFunction),
* fill: (ol.style.Fill|undefined), * fill: (ol.style.Fill|undefined),
* image: (ol.style.Image|undefined), * image: (ol.style.Image|undefined),
* renderer: (ol.StyleRenderFunction|undefined),
* stroke: (ol.style.Stroke|undefined), * stroke: (ol.style.Stroke|undefined),
* text: (ol.style.Text|undefined), * text: (ol.style.Text|undefined),
* zIndex: (number|undefined)}} * zIndex: (number|undefined)}}
@@ -7789,16 +7640,6 @@ olx.style.StyleOptions.prototype.fill;
olx.style.StyleOptions.prototype.image; olx.style.StyleOptions.prototype.image;
/**
* Custom renderer. When configured, `fill`, `stroke` and `image` will be
* ignored, and the provided function will be called with each render frame for
* each geometry.
*
* @type {ol.StyleRenderFunction|undefined}
*/
olx.style.StyleOptions.prototype.renderer;
/** /**
* Stroke style. * Stroke style.
* @type {ol.style.Stroke|undefined} * @type {ol.style.Stroke|undefined}

View File

@@ -1,6 +1,6 @@
{ {
"name": "openlayers", "name": "openlayers",
"version": "4.3.1", "version": "4.3.0-beta.2",
"description": "Build tools and sources for developing OpenLayers based mapping applications", "description": "Build tools and sources for developing OpenLayers based mapping applications",
"keywords": [ "keywords": [
"map", "map",
@@ -33,13 +33,19 @@
"dependencies": { "dependencies": {
"async": "2.5.0", "async": "2.5.0",
"closure-util": "1.22.0", "closure-util": "1.22.0",
"fs-extra": "4.0.1", "derequire": "2.0.6",
"jsdoc": "3.5.4", "fs-extra": "4.0.0",
"glob": "7.1.1",
"handlebars": "4.0.10",
"jsdoc": "3.5.3",
"marked": "0.3.6",
"metalsmith": "2.3.0",
"metalsmith-layouts": "1.8.1",
"nomnom": "1.8.1", "nomnom": "1.8.1",
"pbf": "3.0.5", "pbf": "3.0.5",
"pixelworks": "1.1.0", "pixelworks": "1.1.0",
"rbush": "2.0.1", "rbush": "2.0.1",
"rollup": "^0.47.2", "rollup": "^0.45.0",
"rollup-plugin-cleanup": "^1.0.0", "rollup-plugin-cleanup": "^1.0.0",
"rollup-plugin-commonjs": "^8.0.2", "rollup-plugin-commonjs": "^8.0.2",
"rollup-plugin-node-resolve": "^3.0.0", "rollup-plugin-node-resolve": "^3.0.0",
@@ -51,27 +57,22 @@
"clean-css-cli": "4.1.6", "clean-css-cli": "4.1.6",
"coveralls": "2.13.1", "coveralls": "2.13.1",
"debounce": "^1.0.0", "debounce": "^1.0.0",
"eslint": "4.4.1", "eslint": "4.2.0",
"eslint-config-openlayers": "7.0.0", "eslint-config-openlayers": "7.0.0",
"eslint-plugin-openlayers-internal": "^3.1.0", "eslint-plugin-openlayers-internal": "^3.1.0",
"expect.js": "0.3.1", "expect.js": "0.3.1",
"gaze": "^1.0.0", "gaze": "^1.0.0",
"glob": "7.1.1",
"handlebars": "4.0.10",
"istanbul": "0.4.5", "istanbul": "0.4.5",
"jquery": "3.2.1", "jquery": "3.2.1",
"jscodeshift": "^0.3.30", "jscodeshift": "^0.3.30",
"marked": "0.3.6", "mocha": "3.4.2",
"metalsmith": "2.3.0",
"metalsmith-layouts": "1.8.1",
"mocha": "3.5.0",
"mocha-phantomjs-core": "^2.1.0", "mocha-phantomjs-core": "^2.1.0",
"mustache": "2.3.0", "mustache": "2.3.0",
"phantomjs-prebuilt": "2.1.14", "phantomjs-prebuilt": "2.1.14",
"proj4": "2.4.4", "proj4": "2.4.3",
"resemblejs": "2.2.4", "resemblejs": "2.2.4",
"serve-files": "1.0.1", "serve-files": "1.0.1",
"sinon": "3.2.0", "sinon": "2.3.8",
"slimerjs": "0.10.3" "slimerjs": "0.10.3"
}, },
"eslintConfig": { "eslintConfig": {

View File

@@ -1,6 +1,6 @@
{ {
"name": "ol", "name": "ol",
"version": "4.3.1", "version": "4.3.0-beta.2",
"description": "OpenLayers as ES2015 modules", "description": "OpenLayers as ES2015 modules",
"main": "index.js", "main": "index.js",
"module": "index.js", "module": "index.js",

View File

@@ -23,7 +23,7 @@ goog.require('ol.events.Event');
* @constructor * @constructor
* @extends {ol.Object} * @extends {ol.Object}
* @fires ol.Collection.Event * @fires ol.Collection.Event
* @param {Array.<T>=} opt_array Array. * @param {!Array.<T>=} opt_array Array.
* @param {olx.CollectionOptions=} opt_options Collection options. * @param {olx.CollectionOptions=} opt_options Collection options.
* @template T * @template T
* @api * @api
@@ -95,11 +95,7 @@ ol.Collection.prototype.extend = function(arr) {
* @api * @api
*/ */
ol.Collection.prototype.forEach = function(f, opt_this) { ol.Collection.prototype.forEach = function(f, opt_this) {
var fn = (opt_this) ? f.bind(opt_this) : f; this.array_.forEach(f, opt_this);
var array = this.array_;
for (var i = 0, ii = array.length; i < ii; ++i) {
fn(array[i], i, array);
}
}; };

View File

@@ -168,22 +168,17 @@ ol.control.ScaleLine.prototype.updateElement_ = function() {
var center = viewState.center; var center = viewState.center;
var projection = viewState.projection; var projection = viewState.projection;
var units = this.getUnits(); var metersPerUnit = projection.getMetersPerUnit();
var pointResolutionUnits = units == ol.control.ScaleLineUnits.DEGREES ?
ol.proj.Units.DEGREES :
ol.proj.Units.METERS;
var pointResolution = var pointResolution =
ol.proj.getPointResolution(projection, viewState.resolution, center, pointResolutionUnits); ol.proj.getPointResolution(projection, viewState.resolution, center) *
metersPerUnit;
var nominalCount = this.minWidth_ * pointResolution; var nominalCount = this.minWidth_ * pointResolution;
var suffix = ''; var suffix = '';
var units = this.getUnits();
if (units == ol.control.ScaleLineUnits.DEGREES) { if (units == ol.control.ScaleLineUnits.DEGREES) {
var metersPerDegree = ol.proj.METERS_PER_UNIT[ol.proj.Units.DEGREES]; var metersPerDegree = ol.proj.METERS_PER_UNIT[ol.proj.Units.DEGREES];
if (projection.getUnits() == ol.proj.Units.DEGREES) { pointResolution /= metersPerDegree;
nominalCount *= metersPerDegree;
} else {
pointResolution /= metersPerDegree;
}
if (nominalCount < metersPerDegree / 60) { if (nominalCount < metersPerDegree / 60) {
suffix = '\u2033'; // seconds suffix = '\u2033'; // seconds
pointResolution *= 3600; pointResolution *= 3600;

View File

@@ -8,7 +8,7 @@ goog.require('ol.xml');
/** /**
* @param {string|ol.FeatureUrlFunction} url Feature URL service. * @param {string|ol.FeatureUrlFunction} url Feature URL service.
* @param {ol.format.Feature} format Feature format. * @param {ol.format.Feature} format Feature format.
* @param {function(this:ol.VectorTile, Array.<ol.Feature>, ol.proj.Projection, ol.Extent)|function(this:ol.source.Vector, Array.<ol.Feature>)} success * @param {function(this:ol.VectorTile, Array.<ol.Feature>, ol.proj.Projection)|function(this:ol.source.Vector, Array.<ol.Feature>)} success
* Function called with the loaded features and optionally with the data * Function called with the loaded features and optionally with the data
* projection. Called with the vector tile or source as `this`. * projection. Called with the vector tile or source as `this`.
* @param {function(this:ol.VectorTile)|function(this:ol.source.Vector)} failure * @param {function(this:ol.VectorTile)|function(this:ol.source.Vector)} failure
@@ -56,7 +56,7 @@ ol.featureloader.loadFeaturesXhr = function(url, format, success, failure) {
if (source) { if (source) {
success.call(this, format.readFeatures(source, success.call(this, format.readFeatures(source,
{featureProjection: projection}), {featureProjection: projection}),
format.readProjection(source), format.getLastExtent()); format.readProjection(source));
} else { } else {
failure.call(this); failure.call(this);
} }

View File

@@ -290,9 +290,9 @@ ol.format.EsriJSON.getHasZM_ = function(geometry) {
var layout = geometry.getLayout(); var layout = geometry.getLayout();
return { return {
hasZ: (layout === ol.geom.GeometryLayout.XYZ || hasZ: (layout === ol.geom.GeometryLayout.XYZ ||
layout === ol.geom.GeometryLayout.XYZM), layout === ol.geom.GeometryLayout.XYZM),
hasM: (layout === ol.geom.GeometryLayout.XYM || hasM: (layout === ol.geom.GeometryLayout.XYM ||
layout === ol.geom.GeometryLayout.XYZM) layout === ol.geom.GeometryLayout.XYZM)
}; };
}; };
@@ -304,7 +304,7 @@ ol.format.EsriJSON.getHasZM_ = function(geometry) {
* @return {EsriJSONPolyline} EsriJSON geometry. * @return {EsriJSONPolyline} EsriJSON geometry.
*/ */
ol.format.EsriJSON.writeLineStringGeometry_ = function(geometry, opt_options) { ol.format.EsriJSON.writeLineStringGeometry_ = function(geometry, opt_options) {
var hasZM = ol.format.EsriJSON.getHasZM_(/** @type {ol.geom.LineString} */(geometry)); var hasZM = ol.format.EsriJSON.getHasZM_(/** @type {ol.geom.LineString} */ (geometry));
return /** @type {EsriJSONPolyline} */ ({ return /** @type {EsriJSONPolyline} */ ({
hasZ: hasZM.hasZ, hasZ: hasZM.hasZ,
hasM: hasZM.hasM, hasM: hasZM.hasM,
@@ -323,7 +323,7 @@ ol.format.EsriJSON.writeLineStringGeometry_ = function(geometry, opt_options) {
*/ */
ol.format.EsriJSON.writePolygonGeometry_ = function(geometry, opt_options) { ol.format.EsriJSON.writePolygonGeometry_ = function(geometry, opt_options) {
// Esri geometries use the left-hand rule // Esri geometries use the left-hand rule
var hasZM = ol.format.EsriJSON.getHasZM_(/** @type {ol.geom.Polygon} */(geometry)); var hasZM = ol.format.EsriJSON.getHasZM_(/** @type {ol.geom.Polygon} */ (geometry));
return /** @type {EsriJSONPolygon} */ ({ return /** @type {EsriJSONPolygon} */ ({
hasZ: hasZM.hasZ, hasZ: hasZM.hasZ,
hasM: hasZM.hasM, hasM: hasZM.hasM,
@@ -339,7 +339,7 @@ ol.format.EsriJSON.writePolygonGeometry_ = function(geometry, opt_options) {
* @return {EsriJSONPolyline} EsriJSON geometry. * @return {EsriJSONPolyline} EsriJSON geometry.
*/ */
ol.format.EsriJSON.writeMultiLineStringGeometry_ = function(geometry, opt_options) { ol.format.EsriJSON.writeMultiLineStringGeometry_ = function(geometry, opt_options) {
var hasZM = ol.format.EsriJSON.getHasZM_(/** @type {ol.geom.MultiLineString} */(geometry)); var hasZM = ol.format.EsriJSON.getHasZM_(/** @type {ol.geom.MultiLineString} */ (geometry));
return /** @type {EsriJSONPolyline} */ ({ return /** @type {EsriJSONPolyline} */ ({
hasZ: hasZM.hasZ, hasZ: hasZM.hasZ,
hasM: hasZM.hasM, hasM: hasZM.hasM,
@@ -355,7 +355,7 @@ ol.format.EsriJSON.writeMultiLineStringGeometry_ = function(geometry, opt_option
* @return {EsriJSONMultipoint} EsriJSON geometry. * @return {EsriJSONMultipoint} EsriJSON geometry.
*/ */
ol.format.EsriJSON.writeMultiPointGeometry_ = function(geometry, opt_options) { ol.format.EsriJSON.writeMultiPointGeometry_ = function(geometry, opt_options) {
var hasZM = ol.format.EsriJSON.getHasZM_(/** @type {ol.geom.MultiPoint} */(geometry)); var hasZM = ol.format.EsriJSON.getHasZM_(/** @type {ol.geom.MultiPoint} */ (geometry));
return /** @type {EsriJSONMultipoint} */ ({ return /** @type {EsriJSONMultipoint} */ ({
hasZ: hasZM.hasZ, hasZ: hasZM.hasZ,
hasM: hasZM.hasM, hasM: hasZM.hasM,
@@ -372,7 +372,7 @@ ol.format.EsriJSON.writeMultiPointGeometry_ = function(geometry, opt_options) {
*/ */
ol.format.EsriJSON.writeMultiPolygonGeometry_ = function(geometry, ol.format.EsriJSON.writeMultiPolygonGeometry_ = function(geometry,
opt_options) { opt_options) {
var hasZM = ol.format.EsriJSON.getHasZM_(/** @type {ol.geom.MultiPolygon} */(geometry)); var hasZM = ol.format.EsriJSON.getHasZM_(/** @type {ol.geom.MultiPolygon} */ (geometry));
var coordinates = /** @type {ol.geom.MultiPolygon} */ (geometry).getCoordinates(false); var coordinates = /** @type {ol.geom.MultiPolygon} */ (geometry).getCoordinates(false);
var output = []; var output = [];
for (var i = 0; i < coordinates.length; i++) { for (var i = 0; i < coordinates.length; i++) {
@@ -395,17 +395,17 @@ ol.format.EsriJSON.writeMultiPolygonGeometry_ = function(geometry,
*/ */
ol.format.EsriJSON.GEOMETRY_READERS_ = {}; ol.format.EsriJSON.GEOMETRY_READERS_ = {};
ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.POINT] = ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.POINT] =
ol.format.EsriJSON.readPointGeometry_; ol.format.EsriJSON.readPointGeometry_;
ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.LINE_STRING] = ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.LINE_STRING] =
ol.format.EsriJSON.readLineStringGeometry_; ol.format.EsriJSON.readLineStringGeometry_;
ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.POLYGON] = ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.POLYGON] =
ol.format.EsriJSON.readPolygonGeometry_; ol.format.EsriJSON.readPolygonGeometry_;
ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_POINT] = ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_POINT] =
ol.format.EsriJSON.readMultiPointGeometry_; ol.format.EsriJSON.readMultiPointGeometry_;
ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_LINE_STRING] = ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_LINE_STRING] =
ol.format.EsriJSON.readMultiLineStringGeometry_; ol.format.EsriJSON.readMultiLineStringGeometry_;
ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_POLYGON] = ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_POLYGON] =
ol.format.EsriJSON.readMultiPolygonGeometry_; ol.format.EsriJSON.readMultiPolygonGeometry_;
/** /**
@@ -415,17 +415,17 @@ ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_POLYGON] =
*/ */
ol.format.EsriJSON.GEOMETRY_WRITERS_ = {}; ol.format.EsriJSON.GEOMETRY_WRITERS_ = {};
ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.POINT] = ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.POINT] =
ol.format.EsriJSON.writePointGeometry_; ol.format.EsriJSON.writePointGeometry_;
ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.LINE_STRING] = ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.LINE_STRING] =
ol.format.EsriJSON.writeLineStringGeometry_; ol.format.EsriJSON.writeLineStringGeometry_;
ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.POLYGON] = ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.POLYGON] =
ol.format.EsriJSON.writePolygonGeometry_; ol.format.EsriJSON.writePolygonGeometry_;
ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_POINT] = ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_POINT] =
ol.format.EsriJSON.writeMultiPointGeometry_; ol.format.EsriJSON.writeMultiPointGeometry_;
ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_LINE_STRING] = ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_LINE_STRING] =
ol.format.EsriJSON.writeMultiLineStringGeometry_; ol.format.EsriJSON.writeMultiLineStringGeometry_;
ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_POLYGON] = ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_POLYGON] =
ol.format.EsriJSON.writeMultiPolygonGeometry_; ol.format.EsriJSON.writeMultiPolygonGeometry_;
/** /**
@@ -468,7 +468,7 @@ ol.format.EsriJSON.prototype.readFeatureFromObject = function(
} }
feature.setGeometry(geometry); feature.setGeometry(geometry);
if (opt_options && opt_options.idField && if (opt_options && opt_options.idField &&
esriJSONFeature.attributes[opt_options.idField]) { esriJSONFeature.attributes[opt_options.idField]) {
feature.setId(/** @type {number} */( feature.setId(/** @type {number} */(
esriJSONFeature.attributes[opt_options.idField])); esriJSONFeature.attributes[opt_options.idField]));
} }
@@ -488,7 +488,7 @@ ol.format.EsriJSON.prototype.readFeaturesFromObject = function(
var options = opt_options ? opt_options : {}; var options = opt_options ? opt_options : {};
if (esriJSONObject.features) { if (esriJSONObject.features) {
var esriJSONFeatureCollection = /** @type {EsriJSONFeatureCollection} */ var esriJSONFeatureCollection = /** @type {EsriJSONFeatureCollection} */
(object); (object);
/** @type {Array.<ol.Feature>} */ /** @type {Array.<ol.Feature>} */
var features = []; var features = [];
var esriJSONFeatures = esriJSONFeatureCollection.features; var esriJSONFeatures = esriJSONFeatureCollection.features;
@@ -523,7 +523,7 @@ ol.format.EsriJSON.prototype.readGeometry;
ol.format.EsriJSON.prototype.readGeometryFromObject = function( ol.format.EsriJSON.prototype.readGeometryFromObject = function(
object, opt_options) { object, opt_options) {
return ol.format.EsriJSON.readGeometry_( return ol.format.EsriJSON.readGeometry_(
/** @type {EsriJSONGeometry} */(object), opt_options); /** @type {EsriJSONGeometry} */ (object), opt_options);
}; };
@@ -560,7 +560,7 @@ ol.format.EsriJSON.prototype.readProjectionFromObject = function(object) {
*/ */
ol.format.EsriJSON.writeGeometry_ = function(geometry, opt_options) { ol.format.EsriJSON.writeGeometry_ = function(geometry, opt_options) {
var geometryWriter = ol.format.EsriJSON.GEOMETRY_WRITERS_[geometry.getType()]; var geometryWriter = ol.format.EsriJSON.GEOMETRY_WRITERS_[geometry.getType()];
return geometryWriter(/** @type {ol.geom.Geometry} */( return geometryWriter(/** @type {ol.geom.Geometry} */ (
ol.format.Feature.transformWithOptions(geometry, true, opt_options)), ol.format.Feature.transformWithOptions(geometry, true, opt_options)),
opt_options); opt_options);
}; };
@@ -622,13 +622,7 @@ ol.format.EsriJSON.prototype.writeFeatureObject = function(
var geometry = feature.getGeometry(); var geometry = feature.getGeometry();
if (geometry) { if (geometry) {
object['geometry'] = object['geometry'] =
ol.format.EsriJSON.writeGeometry_(geometry, opt_options); ol.format.EsriJSON.writeGeometry_(geometry, opt_options);
if (opt_options && opt_options.featureProjection) {
object['geometry']['spatialReference'] = /** @type {EsriJSONCRS} */({
wkid: ol.proj.get(
opt_options.featureProjection).getCode().split(':').pop()
});
}
} }
var properties = feature.getProperties(); var properties = feature.getProperties();
delete properties[feature.getGeometryName()]; delete properties[feature.getGeometryName()];
@@ -637,6 +631,12 @@ ol.format.EsriJSON.prototype.writeFeatureObject = function(
} else { } else {
object['attributes'] = {}; object['attributes'] = {};
} }
if (opt_options && opt_options.featureProjection) {
object['spatialReference'] = /** @type {EsriJSONCRS} */({
wkid: ol.proj.get(
opt_options.featureProjection).getCode().split(':').pop()
});
}
return object; return object;
}; };

View File

@@ -72,15 +72,6 @@ ol.format.Feature.prototype.adaptOptions = function(options) {
}; };
/**
* Get the extent from the source of the last {@link readFeatures} call.
* @return {ol.Extent} Tile extent.
*/
ol.format.Feature.prototype.getLastExtent = function() {
return null;
};
/** /**
* @abstract * @abstract
* @return {ol.format.FormatType} Format. * @return {ol.format.FormatType} Format.

View File

@@ -67,13 +67,6 @@ ol.format.GML3 = function(opt_options) {
this.schemaLocation = options.schemaLocation ? this.schemaLocation = options.schemaLocation ?
options.schemaLocation : ol.format.GML3.schemaLocation_; options.schemaLocation : ol.format.GML3.schemaLocation_;
/**
* @private
* @type {boolean}
*/
this.hasZ = options.hasZ !== undefined ?
options.hasZ : false;
}; };
ol.inherits(ol.format.GML3, ol.format.GMLBase); ol.inherits(ol.format.GML3, ol.format.GMLBase);

View File

@@ -1065,25 +1065,19 @@ ol.format.KML.setCommonGeometryProperties_ = function(multiGeometry,
geometries) { geometries) {
var ii = geometries.length; var ii = geometries.length;
var extrudes = new Array(geometries.length); var extrudes = new Array(geometries.length);
var tessellates = new Array(geometries.length);
var altitudeModes = new Array(geometries.length); var altitudeModes = new Array(geometries.length);
var geometry, i, hasExtrude, hasTessellate, hasAltitudeMode; var geometry, i, hasExtrude, hasAltitudeMode;
hasExtrude = hasTessellate = hasAltitudeMode = false; hasExtrude = hasAltitudeMode = false;
for (i = 0; i < ii; ++i) { for (i = 0; i < ii; ++i) {
geometry = geometries[i]; geometry = geometries[i];
extrudes[i] = geometry.get('extrude'); extrudes[i] = geometry.get('extrude');
tessellates[i] = geometry.get('tessellate');
altitudeModes[i] = geometry.get('altitudeMode'); altitudeModes[i] = geometry.get('altitudeMode');
hasExtrude = hasExtrude || extrudes[i] !== undefined; hasExtrude = hasExtrude || extrudes[i] !== undefined;
hasTessellate = hasTessellate || tessellates[i] !== undefined;
hasAltitudeMode = hasAltitudeMode || altitudeModes[i]; hasAltitudeMode = hasAltitudeMode || altitudeModes[i];
} }
if (hasExtrude) { if (hasExtrude) {
multiGeometry.set('extrude', extrudes); multiGeometry.set('extrude', extrudes);
} }
if (hasTessellate) {
multiGeometry.set('tessellate', tessellates);
}
if (hasAltitudeMode) { if (hasAltitudeMode) {
multiGeometry.set('altitudeMode', altitudeModes); multiGeometry.set('altitudeMode', altitudeModes);
} }
@@ -1377,7 +1371,6 @@ ol.format.KML.LOD_PARSERS_ = ol.xml.makeStructureNS(
ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_ = ol.xml.makeStructureNS( ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_ = ol.xml.makeStructureNS(
ol.format.KML.NAMESPACE_URIS_, { ol.format.KML.NAMESPACE_URIS_, {
'extrude': ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean), 'extrude': ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),
'tessellate': ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),
'altitudeMode': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString) 'altitudeMode': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)
}); });
@@ -2267,7 +2260,7 @@ ol.format.KML.writeIconStyle_ = function(node, style, objectStack) {
iconProperties['y'] = iconImageSize[1] - (origin[1] + size[1]); iconProperties['y'] = iconImageSize[1] - (origin[1] + size[1]);
} }
if (anchor && (anchor[0] !== size[0] / 2 || anchor[1] !== size[1] / 2)) { if (anchor && anchor[0] !== 0 && anchor[1] !== size[1]) {
var /** @type {ol.KMLVec2_} */ hotSpot = { var /** @type {ol.KMLVec2_} */ hotSpot = {
x: anchor[0], x: anchor[0],
xunits: ol.style.IconAnchorUnits.PIXELS, xunits: ol.style.IconAnchorUnits.PIXELS,
@@ -2475,16 +2468,10 @@ ol.format.KML.writePrimitiveGeometry_ = function(node, geometry, objectStack) {
var /** @type {ol.XmlNodeStackItem} */ context = {node: node}; var /** @type {ol.XmlNodeStackItem} */ context = {node: node};
context['layout'] = geometry.getLayout(); context['layout'] = geometry.getLayout();
context['stride'] = geometry.getStride(); context['stride'] = geometry.getStride();
ol.xml.pushSerializeAndPop(context,
// serialize properties (properties unknown to KML are not serialized) ol.format.KML.PRIMITIVE_GEOMETRY_SERIALIZERS_,
var properties = geometry.getProperties(); ol.format.KML.COORDINATES_NODE_FACTORY_,
properties.coordinates = flatCoordinates; [flatCoordinates], objectStack);
var parentNode = objectStack[objectStack.length - 1].node;
var orderedKeys = ol.format.KML.PRIMITIVE_GEOMETRY_SEQUENCE_[parentNode.namespaceURI];
var values = ol.xml.makeSequence(properties, orderedKeys);
ol.xml.pushSerializeAndPop(context, ol.format.KML.PRIMITIVE_GEOMETRY_SERIALIZERS_,
ol.xml.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys);
}; };
@@ -2645,6 +2632,7 @@ ol.format.KML.GEOMETRY_TYPE_TO_NODENAME_ = {
'GeometryCollection': 'MultiGeometry' 'GeometryCollection': 'MultiGeometry'
}; };
/** /**
* @const * @const
* @type {Object.<string, Array.<string>>} * @type {Object.<string, Array.<string>>}
@@ -2820,17 +2808,6 @@ ol.format.KML.PLACEMARK_SERIALIZERS_ = ol.xml.makeStructureNS(
}); });
/**
* @const
* @type {Object.<string, Array.<string>>}
* @private
*/
ol.format.KML.PRIMITIVE_GEOMETRY_SEQUENCE_ = ol.xml.makeStructureNS(
ol.format.KML.NAMESPACE_URIS_, [
'extrude', 'tessellate', 'altitudeMode', 'coordinates'
]);
/** /**
* @const * @const
* @type {Object.<string, Object.<string, ol.XmlSerializer>>} * @type {Object.<string, Object.<string, ol.XmlSerializer>>}
@@ -2838,9 +2815,6 @@ ol.format.KML.PRIMITIVE_GEOMETRY_SEQUENCE_ = ol.xml.makeStructureNS(
*/ */
ol.format.KML.PRIMITIVE_GEOMETRY_SERIALIZERS_ = ol.xml.makeStructureNS( ol.format.KML.PRIMITIVE_GEOMETRY_SERIALIZERS_ = ol.xml.makeStructureNS(
ol.format.KML.NAMESPACE_URIS_, { ol.format.KML.NAMESPACE_URIS_, {
'extrude': ol.xml.makeChildAppender(ol.format.XSD.writeBooleanTextNode),
'tessellate': ol.xml.makeChildAppender(ol.format.XSD.writeBooleanTextNode),
'altitudeMode': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
'coordinates': ol.xml.makeChildAppender( 'coordinates': ol.xml.makeChildAppender(
ol.format.KML.writeCoordinatesTextNode_) ol.format.KML.writeCoordinatesTextNode_)
}); });
@@ -2952,6 +2926,16 @@ ol.format.KML.GEOMETRY_NODE_FACTORY_ = function(value, objectStack,
ol.format.KML.COLOR_NODE_FACTORY_ = ol.xml.makeSimpleNodeFactory('color'); ol.format.KML.COLOR_NODE_FACTORY_ = ol.xml.makeSimpleNodeFactory('color');
/**
* A factory for creating coordinates nodes.
* @const
* @type {function(*, Array.<*>, string=): (Node|undefined)}
* @private
*/
ol.format.KML.COORDINATES_NODE_FACTORY_ =
ol.xml.makeSimpleNodeFactory('coordinates');
/** /**
* A factory for creating Data nodes. * A factory for creating Data nodes.
* @const * @const

View File

@@ -69,25 +69,10 @@ ol.format.MVT = function(opt_options) {
*/ */
this.layers_ = options.layers ? options.layers : null; this.layers_ = options.layers ? options.layers : null;
/**
* @private
* @type {ol.Extent}
*/
this.extent_ = null;
}; };
ol.inherits(ol.format.MVT, ol.format.Feature); ol.inherits(ol.format.MVT, ol.format.Feature);
/**
* @inheritDoc
* @api
*/
ol.format.MVT.prototype.getLastExtent = function() {
return this.extent_;
};
/** /**
* @inheritDoc * @inheritDoc
*/ */
@@ -176,17 +161,14 @@ ol.format.MVT.prototype.readFeatures = function(source, opt_options) {
} }
layer = tile.layers[name]; layer = tile.layers[name];
var rawFeature;
for (var i = 0, ii = layer.length; i < ii; ++i) { for (var i = 0, ii = layer.length; i < ii; ++i) {
rawFeature = layer.feature(i);
if (featureClass === ol.render.Feature) { if (featureClass === ol.render.Feature) {
feature = this.readRenderFeature_(rawFeature, name); feature = this.readRenderFeature_(layer.feature(i), name);
} else { } else {
feature = this.readFeature_(rawFeature, name, opt_options); feature = this.readFeature_(layer.feature(i), name, opt_options);
} }
features.push(feature); features.push(feature);
} }
this.extent_ = layer ? [0, 0, layer.extent, layer.extent] : null;
} }
return features; return features;

View File

@@ -688,14 +688,12 @@ ol.format.WFS.writeDuringFilter_ = function(node, filter, objectStack) {
ol.format.WFS.writeLogicalFilter_ = function(node, filter, objectStack) { ol.format.WFS.writeLogicalFilter_ = function(node, filter, objectStack) {
/** @type {ol.XmlNodeStackItem} */ /** @type {ol.XmlNodeStackItem} */
var item = {node: node}; var item = {node: node};
var conditions = filter.conditions; filter.conditions.forEach(function(condition) {
for (var i = 0, ii = conditions.length; i < ii; ++i) {
var condition = conditions[i];
ol.xml.pushSerializeAndPop(item, ol.xml.pushSerializeAndPop(item,
ol.format.WFS.GETFEATURE_SERIALIZERS_, ol.format.WFS.GETFEATURE_SERIALIZERS_,
ol.xml.makeSimpleNodeFactory(condition.getTagName()), ol.xml.makeSimpleNodeFactory(condition.getTagName()),
[condition], objectStack); [condition], objectStack);
} });
}; };

View File

@@ -519,7 +519,7 @@ ol.Graticule.prototype.getMeridians = function() {
ol.Graticule.prototype.getParallel_ = function(lat, minLon, maxLon, ol.Graticule.prototype.getParallel_ = function(lat, minLon, maxLon,
squaredTolerance, index) { squaredTolerance, index) {
var flatCoordinates = ol.geom.flat.geodesic.parallel(lat, var flatCoordinates = ol.geom.flat.geodesic.parallel(lat,
minLon, maxLon, this.projection_, squaredTolerance); this.minLon_, this.maxLon_, this.projection_, squaredTolerance);
var lineString = this.parallels_[index] !== undefined ? var lineString = this.parallels_[index] !== undefined ?
this.parallels_[index] : new ol.geom.LineString(null); this.parallels_[index] : new ol.geom.LineString(null);
lineString.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates); lineString.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates);
@@ -560,6 +560,23 @@ ol.Graticule.prototype.handlePostCompose_ = function(e) {
this.updateProjectionInfo_(projection); this.updateProjectionInfo_(projection);
} }
//Fix the extent if wrapped.
//(note: this is the same extent as vectorContext.extent_)
var offsetX = 0;
if (projection.canWrapX()) {
var projectionExtent = projection.getExtent();
var worldWidth = ol.extent.getWidth(projectionExtent);
var x = frameState.focus[0];
if (x < projectionExtent[0] || x > projectionExtent[2]) {
var worldsAway = Math.ceil((projectionExtent[0] - x) / worldWidth);
offsetX = worldWidth * worldsAway;
extent = [
extent[0] + offsetX, extent[1],
extent[2] + offsetX, extent[3]
];
}
}
this.createGraticule_(extent, center, resolution, squaredTolerance); this.createGraticule_(extent, center, resolution, squaredTolerance);
// Draw the lines // Draw the lines

View File

@@ -49,12 +49,6 @@ ol.interaction.DragAndDrop = function(opt_options) {
*/ */
this.dropListenKeys_ = null; this.dropListenKeys_ = null;
/**
* @private
* @type {ol.source.Vector}
*/
this.source_ = options.source || null;
/** /**
* @private * @private
* @type {Element} * @type {Element}
@@ -128,10 +122,6 @@ ol.interaction.DragAndDrop.prototype.handleResult_ = function(file, event) {
break; break;
} }
} }
if (this.source_) {
this.source_.clear();
this.source_.addFeatures(features);
}
this.dispatchEvent( this.dispatchEvent(
new ol.interaction.DragAndDrop.Event( new ol.interaction.DragAndDrop.Event(
ol.interaction.DragAndDrop.EventType_.ADD_FEATURES, file, ol.interaction.DragAndDrop.EventType_.ADD_FEATURES, file,

View File

@@ -10,7 +10,6 @@ goog.require('ol.extent');
goog.require('ol.geom.GeometryType'); goog.require('ol.geom.GeometryType');
goog.require('ol.geom.Point'); goog.require('ol.geom.Point');
goog.require('ol.geom.Polygon'); goog.require('ol.geom.Polygon');
goog.require('ol.interaction.ExtentEventType');
goog.require('ol.interaction.Pointer'); goog.require('ol.interaction.Pointer');
goog.require('ol.layer.Vector'); goog.require('ol.layer.Vector');
goog.require('ol.source.Vector'); goog.require('ol.source.Vector');
@@ -77,6 +76,10 @@ ol.interaction.Extent = function(opt_options) {
opt_options = {}; opt_options = {};
} }
if (opt_options.extent) {
this.setExtent(opt_options.extent);
}
/* Inherit ol.interaction.Pointer */ /* Inherit ol.interaction.Pointer */
ol.interaction.Pointer.call(this, { ol.interaction.Pointer.call(this, {
handleDownEvent: ol.interaction.Extent.handleDownEvent_, handleDownEvent: ol.interaction.Extent.handleDownEvent_,
@@ -114,10 +117,6 @@ ol.interaction.Extent = function(opt_options) {
updateWhileAnimating: true, updateWhileAnimating: true,
updateWhileInteracting: true updateWhileInteracting: true
}); });
if (opt_options.extent) {
this.setExtent(opt_options.extent);
}
}; };
ol.inherits(ol.interaction.Extent, ol.interaction.Pointer); ol.inherits(ol.interaction.Extent, ol.interaction.Pointer);
@@ -446,19 +445,31 @@ ol.interaction.Extent.prototype.setExtent = function(extent) {
* this type. * this type.
* *
* @constructor * @constructor
* @implements {oli.ExtentEvent}
* @param {ol.Extent} extent the new extent * @param {ol.Extent} extent the new extent
* @extends {ol.events.Event} * @extends {ol.events.Event}
*/ */
ol.interaction.Extent.Event = function(extent) { ol.interaction.Extent.Event = function(extent) {
ol.events.Event.call(this, ol.interaction.ExtentEventType.EXTENTCHANGED); ol.events.Event.call(this, ol.interaction.Extent.EventType_.EXTENTCHANGED);
/** /**
* The current extent. * The current extent.
* @type {ol.Extent} * @type {ol.Extent}
* @api * @api
*/ */
this.extent = extent; this.extent_ = extent;
}; };
ol.inherits(ol.interaction.Extent.Event, ol.events.Event); ol.inherits(ol.interaction.Extent.Event, ol.events.Event);
/**
* @enum {string}
* @private
*/
ol.interaction.Extent.EventType_ = {
/**
* Triggered after the extent is changed
* @event ol.interaction.Extent.Event
* @api
*/
EXTENTCHANGED: 'extentchanged'
};

View File

@@ -1,14 +0,0 @@
goog.provide('ol.interaction.ExtentEventType');
/**
* @enum {string}
*/
ol.interaction.ExtentEventType = {
/**
* Triggered after the extent is changed
* @event ol.interaction.Extent.Event#extentchanged
* @api
*/
EXTENTCHANGED: 'extentchanged'
};

View File

@@ -1,7 +1,6 @@
goog.provide('ol.interaction.Modify'); goog.provide('ol.interaction.Modify');
goog.require('ol'); goog.require('ol');
goog.require('ol.Collection');
goog.require('ol.CollectionEventType'); goog.require('ol.CollectionEventType');
goog.require('ol.Feature'); goog.require('ol.Feature');
goog.require('ol.MapBrowserEventType'); goog.require('ol.MapBrowserEventType');
@@ -20,22 +19,13 @@ goog.require('ol.interaction.ModifyEventType');
goog.require('ol.interaction.Pointer'); goog.require('ol.interaction.Pointer');
goog.require('ol.layer.Vector'); goog.require('ol.layer.Vector');
goog.require('ol.source.Vector'); goog.require('ol.source.Vector');
goog.require('ol.source.VectorEventType');
goog.require('ol.structs.RBush'); goog.require('ol.structs.RBush');
goog.require('ol.style.Style'); goog.require('ol.style.Style');
/** /**
* @classdesc * @classdesc
* Interaction for modifying feature geometries. To modify features that have * Interaction for modifying feature geometries.
* been added to an existing source, construct the modify interaction with the
* `source` option. If you want to modify features in a collection (for example,
* the collection used by a select interaction), construct the interaction with
* the `features` option. The interaction must be constructed with either a
* `source` or `features` option.
*
* By default, the interaction will allow deletion of vertices when the `alt`
* key is pressed. To configure the interaction with a different condition
* for deletion, use the `deleteCondition` option.
* *
* @constructor * @constructor
* @extends {ol.interaction.Pointer} * @extends {ol.interaction.Pointer}
@@ -66,7 +56,7 @@ ol.interaction.Modify = function(options) {
* @return {boolean} Combined condition result. * @return {boolean} Combined condition result.
*/ */
this.defaultDeleteCondition_ = function(mapBrowserEvent) { this.defaultDeleteCondition_ = function(mapBrowserEvent) {
return ol.events.condition.altKeyOnly(mapBrowserEvent) && return ol.events.condition.noModifierKeys(mapBrowserEvent) &&
ol.events.condition.singleClick(mapBrowserEvent); ol.events.condition.singleClick(mapBrowserEvent);
}; };
@@ -185,33 +175,11 @@ ol.interaction.Modify = function(options) {
'GeometryCollection': this.writeGeometryCollectionGeometry_ 'GeometryCollection': this.writeGeometryCollectionGeometry_
}; };
/**
* @type {ol.source.Vector}
* @private
*/
this.source_ = null;
var features;
if (options.source) {
this.source_ = options.source;
features = new ol.Collection(this.source_.getFeatures());
ol.events.listen(this.source_, ol.source.VectorEventType.ADDFEATURE,
this.handleSourceAdd_, this);
ol.events.listen(this.source_, ol.source.VectorEventType.REMOVEFEATURE,
this.handleSourceRemove_, this);
} else {
features = options.features;
}
if (!features) {
throw new Error('The modify interaction requires features or a source');
}
/** /**
* @type {ol.Collection.<ol.Feature>} * @type {ol.Collection.<ol.Feature>}
* @private * @private
*/ */
this.features_ = features; this.features_ = options.features;
this.features_.forEach(this.addFeature_, this); this.features_.forEach(this.addFeature_, this);
ol.events.listen(this.features_, ol.CollectionEventType.ADD, ol.events.listen(this.features_, ol.CollectionEventType.ADD,
@@ -333,28 +301,6 @@ ol.interaction.Modify.prototype.setMap = function(map) {
}; };
/**
* @param {ol.source.Vector.Event} event Event.
* @private
*/
ol.interaction.Modify.prototype.handleSourceAdd_ = function(event) {
if (event.feature) {
this.features_.push(event.feature);
}
};
/**
* @param {ol.source.Vector.Event} event Event.
* @private
*/
ol.interaction.Modify.prototype.handleSourceRemove_ = function(event) {
if (event.feature) {
this.features_.remove(event.feature);
}
};
/** /**
* @param {ol.Collection.Event} evt Event. * @param {ol.Collection.Event} evt Event.
* @private * @private

View File

@@ -80,7 +80,9 @@ ol.layer.Group.prototype.createRenderer = function(mapRenderer) {};
* @private * @private
*/ */
ol.layer.Group.prototype.handleLayerChange_ = function() { ol.layer.Group.prototype.handleLayerChange_ = function() {
this.changed(); if (this.getVisible()) {
this.changed();
}
}; };

View File

@@ -116,12 +116,3 @@ ol.layer.VectorTile.prototype.setUseInterimTilesOnError = function(useInterimTil
this.set( this.set(
ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError); ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError);
}; };
/**
* Return the associated {@link ol.source.VectorTile vectortilesource} of the layer.
* @function
* @return {ol.source.VectorTile} Source.
* @api
*/
ol.layer.VectorTile.prototype.getSource;

View File

@@ -541,7 +541,7 @@ ol.Map.prototype.disposeInternal = function() {
/** /**
* Detect features that intersect a pixel on the viewport, and execute a * Detect features that intersect a pixel on the viewport, and execute a
* callback with each intersecting feature. Layers included in the detection can * callback with each intersecting feature. Layers included in the detection can
* be configured through the `layerFilter` option in `opt_options`. * be configured through `opt_layerFilter`.
* @param {ol.Pixel} pixel Pixel. * @param {ol.Pixel} pixel Pixel.
* @param {function(this: S, (ol.Feature|ol.render.Feature), * @param {function(this: S, (ol.Feature|ol.render.Feature),
* ol.layer.Layer): T} callback Feature callback. The callback will be * ol.layer.Layer): T} callback Feature callback. The callback will be
@@ -573,25 +573,6 @@ ol.Map.prototype.forEachFeatureAtPixel = function(pixel, callback, opt_options)
}; };
/**
* Get all features that intersect a pixel on the viewport.
* @param {ol.Pixel} pixel Pixel.
* @param {olx.AtPixelOptions=} opt_options Optional options.
* @return {Array.<ol.Feature|ol.render.Feature>} The detected features or
* `null` if none were found.
* @api
*/
ol.Map.prototype.getFeaturesAtPixel = function(pixel, opt_options) {
var features = null;
this.forEachFeatureAtPixel(pixel, function(feature) {
if (!features) {
features = [];
}
features.push(feature);
}, opt_options);
return features;
};
/** /**
* Detect layers that have a color value at a pixel on the viewport, and * Detect layers that have a color value at a pixel on the viewport, and
* execute a callback with each matching layer. Layers included in the * execute a callback with each matching layer. Layers included in the

View File

@@ -475,7 +475,7 @@ ol.Overlay.prototype.updateRenderedPosition = function(pixel, mapSize) {
if (this.rendered_.left_ !== '') { if (this.rendered_.left_ !== '') {
this.rendered_.left_ = style.left = ''; this.rendered_.left_ = style.left = '';
} }
var right = (mapSize[0] - pixel[0] - offsetX) + 'px'; var right = Math.round(mapSize[0] - pixel[0] - offsetX) + 'px';
if (this.rendered_.right_ != right) { if (this.rendered_.right_ != right) {
this.rendered_.right_ = style.right = right; this.rendered_.right_ = style.right = right;
} }
@@ -488,7 +488,7 @@ ol.Overlay.prototype.updateRenderedPosition = function(pixel, mapSize) {
positioning == ol.OverlayPositioning.TOP_CENTER) { positioning == ol.OverlayPositioning.TOP_CENTER) {
offsetX -= this.element_.offsetWidth / 2; offsetX -= this.element_.offsetWidth / 2;
} }
var left = (pixel[0] + offsetX) + 'px'; var left = Math.round(pixel[0] + offsetX) + 'px';
if (this.rendered_.left_ != left) { if (this.rendered_.left_ != left) {
this.rendered_.left_ = style.left = left; this.rendered_.left_ = style.left = left;
} }
@@ -499,7 +499,7 @@ ol.Overlay.prototype.updateRenderedPosition = function(pixel, mapSize) {
if (this.rendered_.top_ !== '') { if (this.rendered_.top_ !== '') {
this.rendered_.top_ = style.top = ''; this.rendered_.top_ = style.top = '';
} }
var bottom = (mapSize[1] - pixel[1] - offsetY) + 'px'; var bottom = Math.round(mapSize[1] - pixel[1] - offsetY) + 'px';
if (this.rendered_.bottom_ != bottom) { if (this.rendered_.bottom_ != bottom) {
this.rendered_.bottom_ = style.bottom = bottom; this.rendered_.bottom_ = style.bottom = bottom;
} }
@@ -512,7 +512,7 @@ ol.Overlay.prototype.updateRenderedPosition = function(pixel, mapSize) {
positioning == ol.OverlayPositioning.CENTER_RIGHT) { positioning == ol.OverlayPositioning.CENTER_RIGHT) {
offsetY -= this.element_.offsetHeight / 2; offsetY -= this.element_.offsetHeight / 2;
} }
var top = (pixel[1] + offsetY) + 'px'; var top = Math.round(pixel[1] + offsetY) + 'px';
if (this.rendered_.top_ != top) { if (this.rendered_.top_ != top) {
this.rendered_.top_ = style.top = top; this.rendered_.top_ = style.top = top;
} }

View File

@@ -22,11 +22,11 @@ ol.proj.METERS_PER_UNIT = ol.proj.Units.METERS_PER_UNIT;
/** /**
* A place to store the mean radius of the Earth. * A place to store the radius of the Clarke 1866 Authalic Sphere.
* @private * @private
* @type {ol.Sphere} * @type {ol.Sphere}
*/ */
ol.proj.SPHERE_ = new ol.Sphere(ol.Sphere.DEFAULT_RADIUS); ol.proj.AUTHALIC_SPHERE_ = new ol.Sphere(6370997);
if (ol.ENABLE_PROJ4JS) { if (ol.ENABLE_PROJ4JS) {
@@ -63,12 +63,10 @@ if (ol.ENABLE_PROJ4JS) {
* @param {ol.ProjectionLike} projection The projection. * @param {ol.ProjectionLike} projection The projection.
* @param {number} resolution Nominal resolution in projection units. * @param {number} resolution Nominal resolution in projection units.
* @param {ol.Coordinate} point Point to find adjusted resolution at. * @param {ol.Coordinate} point Point to find adjusted resolution at.
* @param {ol.proj.Units=} opt_units Units to get the point resolution in. * @return {number} Point resolution at point in projection units.
* Default is the projection's units.
* @return {number} Point resolution.
* @api * @api
*/ */
ol.proj.getPointResolution = function(projection, resolution, point, opt_units) { ol.proj.getPointResolution = function(projection, resolution, point) {
projection = ol.proj.get(projection); projection = ol.proj.get(projection);
var pointResolution; var pointResolution;
var getter = projection.getPointResolutionFunc(); var getter = projection.getPointResolutionFunc();
@@ -76,7 +74,7 @@ ol.proj.getPointResolution = function(projection, resolution, point, opt_units)
pointResolution = getter(resolution, point); pointResolution = getter(resolution, point);
} else { } else {
var units = projection.getUnits(); var units = projection.getUnits();
if (units == ol.proj.Units.DEGREES && !opt_units || opt_units == ol.proj.Units.DEGREES) { if (units == ol.proj.Units.DEGREES) {
pointResolution = resolution; pointResolution = resolution;
} else { } else {
// Estimate point resolution by transforming the center pixel to EPSG:4326, // Estimate point resolution by transforming the center pixel to EPSG:4326,
@@ -90,14 +88,12 @@ ol.proj.getPointResolution = function(projection, resolution, point, opt_units)
point[0], point[1] + resolution / 2 point[0], point[1] + resolution / 2
]; ];
vertices = toEPSG4326(vertices, vertices, 2); vertices = toEPSG4326(vertices, vertices, 2);
var width = ol.proj.SPHERE_.haversineDistance( var width = ol.proj.AUTHALIC_SPHERE_.haversineDistance(
vertices.slice(0, 2), vertices.slice(2, 4)); vertices.slice(0, 2), vertices.slice(2, 4));
var height = ol.proj.SPHERE_.haversineDistance( var height = ol.proj.AUTHALIC_SPHERE_.haversineDistance(
vertices.slice(4, 6), vertices.slice(6, 8)); vertices.slice(4, 6), vertices.slice(6, 8));
pointResolution = (width + height) / 2; pointResolution = (width + height) / 2;
var metersPerUnit = opt_units ? var metersPerUnit = projection.getMetersPerUnit();
ol.proj.Units.METERS_PER_UNIT[opt_units] :
projection.getMetersPerUnit();
if (metersPerUnit !== undefined) { if (metersPerUnit !== undefined) {
pointResolution /= metersPerUnit; pointResolution /= metersPerUnit;
} }

View File

@@ -63,21 +63,31 @@ ol.proj.EPSG3857.EXTENT = [
ol.proj.EPSG3857.WORLD_EXTENT = [-180, -85, 180, 85]; ol.proj.EPSG3857.WORLD_EXTENT = [-180, -85, 180, 85];
/**
* Lists several projection codes with the same meaning as EPSG:3857.
*
* @type {Array.<string>}
*/
ol.proj.EPSG3857.CODES = [
'EPSG:3857',
'EPSG:102100',
'EPSG:102113',
'EPSG:900913',
'urn:ogc:def:crs:EPSG:6.18:3:3857',
'urn:ogc:def:crs:EPSG::3857',
'http://www.opengis.net/gml/srs/epsg.xml#3857'
];
/** /**
* Projections equal to EPSG:3857. * Projections equal to EPSG:3857.
* *
* @const * @const
* @type {Array.<ol.proj.Projection>} * @type {Array.<ol.proj.Projection>}
*/ */
ol.proj.EPSG3857.PROJECTIONS = [ ol.proj.EPSG3857.PROJECTIONS = ol.proj.EPSG3857.CODES.map(function(code) {
new ol.proj.EPSG3857.Projection_('EPSG:3857'), return new ol.proj.EPSG3857.Projection_(code);
new ol.proj.EPSG3857.Projection_('EPSG:102100'), });
new ol.proj.EPSG3857.Projection_('EPSG:102113'),
new ol.proj.EPSG3857.Projection_('EPSG:900913'),
new ol.proj.EPSG3857.Projection_('urn:ogc:def:crs:EPSG:6.18:3:3857'),
new ol.proj.EPSG3857.Projection_('urn:ogc:def:crs:EPSG::3857'),
new ol.proj.EPSG3857.Projection_('http://www.opengis.net/gml/srs/epsg.xml#3857')
];
/** /**

View File

@@ -735,7 +735,6 @@ ol.render.canvas.Immediate.prototype.setContextStrokeState_ = function(strokeSta
context.lineCap = strokeState.lineCap; context.lineCap = strokeState.lineCap;
if (ol.has.CANVAS_LINE_DASH) { if (ol.has.CANVAS_LINE_DASH) {
context.setLineDash(strokeState.lineDash); context.setLineDash(strokeState.lineDash);
context.lineDashOffset = strokeState.lineDashOffset;
} }
context.lineJoin = strokeState.lineJoin; context.lineJoin = strokeState.lineJoin;
context.lineWidth = strokeState.lineWidth; context.lineWidth = strokeState.lineWidth;
@@ -744,7 +743,6 @@ ol.render.canvas.Immediate.prototype.setContextStrokeState_ = function(strokeSta
this.contextStrokeState_ = { this.contextStrokeState_ = {
lineCap: strokeState.lineCap, lineCap: strokeState.lineCap,
lineDash: strokeState.lineDash, lineDash: strokeState.lineDash,
lineDashOffset: strokeState.lineDashOffset,
lineJoin: strokeState.lineJoin, lineJoin: strokeState.lineJoin,
lineWidth: strokeState.lineWidth, lineWidth: strokeState.lineWidth,
miterLimit: strokeState.miterLimit, miterLimit: strokeState.miterLimit,
@@ -759,10 +757,6 @@ ol.render.canvas.Immediate.prototype.setContextStrokeState_ = function(strokeSta
contextStrokeState.lineDash, strokeState.lineDash)) { contextStrokeState.lineDash, strokeState.lineDash)) {
context.setLineDash(contextStrokeState.lineDash = strokeState.lineDash); context.setLineDash(contextStrokeState.lineDash = strokeState.lineDash);
} }
if (contextStrokeState.lineDashOffset != strokeState.lineDashOffset) {
contextStrokeState.lineDashOffset = context.lineDashOffset =
strokeState.lineDashOffset;
}
} }
if (contextStrokeState.lineJoin != strokeState.lineJoin) { if (contextStrokeState.lineJoin != strokeState.lineJoin) {
contextStrokeState.lineJoin = context.lineJoin = strokeState.lineJoin; contextStrokeState.lineJoin = context.lineJoin = strokeState.lineJoin;
@@ -886,7 +880,7 @@ ol.render.canvas.Immediate.prototype.setImageStyle = function(imageStyle) {
this.imageOriginY_ = imageOrigin[1]; this.imageOriginY_ = imageOrigin[1];
this.imageRotateWithView_ = imageStyle.getRotateWithView(); this.imageRotateWithView_ = imageStyle.getRotateWithView();
this.imageRotation_ = imageStyle.getRotation(); this.imageRotation_ = imageStyle.getRotation();
this.imageScale_ = imageStyle.getScale() * this.pixelRatio_; this.imageScale_ = imageStyle.getScale();
this.imageSnapToPixel_ = imageStyle.getSnapToPixel(); this.imageSnapToPixel_ = imageStyle.getSnapToPixel();
this.imageWidth_ = imageSize[0]; this.imageWidth_ = imageSize[0];
} }

View File

@@ -8,14 +8,13 @@ ol.render.canvas.Instruction = {
BEGIN_PATH: 1, BEGIN_PATH: 1,
CIRCLE: 2, CIRCLE: 2,
CLOSE_PATH: 3, CLOSE_PATH: 3,
CUSTOM: 4, DRAW_IMAGE: 4,
DRAW_IMAGE: 5, DRAW_TEXT: 5,
DRAW_TEXT: 6, END_GEOMETRY: 6,
END_GEOMETRY: 7, FILL: 7,
FILL: 8, MOVE_TO_LINE_TO: 8,
MOVE_TO_LINE_TO: 9, SET_FILL_STYLE: 9,
SET_FILL_STYLE: 10, SET_STROKE_STYLE: 10,
SET_STROKE_STYLE: 11, SET_TEXT_STYLE: 11,
SET_TEXT_STYLE: 12, STROKE: 12
STROKE: 13
}; };

View File

@@ -37,7 +37,7 @@ ol.render.canvas.LineStringReplay = function(tolerance, maxExtent, resolution, o
* currentLineJoin: (string|undefined), * currentLineJoin: (string|undefined),
* currentLineWidth: (number|undefined), * currentLineWidth: (number|undefined),
* currentMiterLimit: (number|undefined), * currentMiterLimit: (number|undefined),
* lastStroke: (number|undefined), * lastStroke: number,
* strokeStyle: (ol.ColorLike|undefined), * strokeStyle: (ol.ColorLike|undefined),
* lineCap: (string|undefined), * lineCap: (string|undefined),
* lineDash: Array.<number>, * lineDash: Array.<number>,
@@ -54,7 +54,7 @@ ol.render.canvas.LineStringReplay = function(tolerance, maxExtent, resolution, o
currentLineJoin: undefined, currentLineJoin: undefined,
currentLineWidth: undefined, currentLineWidth: undefined,
currentMiterLimit: undefined, currentMiterLimit: undefined,
lastStroke: undefined, lastStroke: 0,
strokeStyle: undefined, strokeStyle: undefined,
lineCap: undefined, lineCap: undefined,
lineDash: null, lineDash: null,
@@ -122,11 +122,10 @@ ol.render.canvas.LineStringReplay.prototype.setStrokeStyle_ = function() {
state.currentLineJoin != lineJoin || state.currentLineJoin != lineJoin ||
state.currentLineWidth != lineWidth || state.currentLineWidth != lineWidth ||
state.currentMiterLimit != miterLimit) { state.currentMiterLimit != miterLimit) {
if (state.lastStroke != undefined && state.lastStroke != this.coordinates.length) { if (state.lastStroke != this.coordinates.length) {
this.instructions.push([ol.render.canvas.Instruction.STROKE]); this.instructions.push([ol.render.canvas.Instruction.STROKE]);
state.lastStroke = this.coordinates.length; state.lastStroke = this.coordinates.length;
} }
state.lastStroke = 0;
this.instructions.push([ this.instructions.push([
ol.render.canvas.Instruction.SET_STROKE_STYLE, ol.render.canvas.Instruction.SET_STROKE_STYLE,
strokeStyle, lineWidth, lineCap, lineJoin, miterLimit, lineDash, lineDashOffset, true, 1 strokeStyle, lineWidth, lineCap, lineJoin, miterLimit, lineDash, lineDashOffset, true, 1
@@ -209,7 +208,7 @@ ol.render.canvas.LineStringReplay.prototype.drawMultiLineString = function(multi
*/ */
ol.render.canvas.LineStringReplay.prototype.finish = function() { ol.render.canvas.LineStringReplay.prototype.finish = function() {
var state = this.state_; var state = this.state_;
if (state.lastStroke != undefined && state.lastStroke != this.coordinates.length) { if (state.lastStroke != this.coordinates.length) {
this.instructions.push([ol.render.canvas.Instruction.STROKE]); this.instructions.push([ol.render.canvas.Instruction.STROKE]);
} }
this.reverseHitDetectionInstructions(); this.reverseHitDetectionInstructions();

View File

@@ -4,8 +4,6 @@ goog.require('ol');
goog.require('ol.array'); goog.require('ol.array');
goog.require('ol.extent'); goog.require('ol.extent');
goog.require('ol.extent.Relationship'); goog.require('ol.extent.Relationship');
goog.require('ol.geom.GeometryType');
goog.require('ol.geom.flat.inflate');
goog.require('ol.geom.flat.transform'); goog.require('ol.geom.flat.transform');
goog.require('ol.has'); goog.require('ol.has');
goog.require('ol.obj'); goog.require('ol.obj');
@@ -88,12 +86,6 @@ ol.render.canvas.Replay = function(tolerance, maxExtent, resolution, overlaps) {
*/ */
this.coordinates = []; this.coordinates = [];
/**
* @private
* @type {Object.<number,ol.Coordinate|Array.<ol.Coordinate>|Array.<Array.<ol.Coordinate>>>}
*/
this.coordinateCache_ = {};
/** /**
* @private * @private
* @type {!ol.Transform} * @type {!ol.Transform}
@@ -182,75 +174,6 @@ ol.render.canvas.Replay.prototype.appendFlatCoordinates = function(flatCoordinat
}; };
/**
* @param {Array.<number>} flatCoordinates Flat coordinates.
* @param {number} offset Offset.
* @param {Array.<number>} ends Ends.
* @param {number} stride Stride.
* @param {Array.<number>} replayEnds Replay ends.
* @return {number} Offset.
*/
ol.render.canvas.Replay.prototype.drawCustomCoordinates_ = function(flatCoordinates, offset, ends, stride, replayEnds) {
for (var i = 0, ii = ends.length; i < ii; ++i) {
var end = ends[i];
var replayEnd = this.appendFlatCoordinates(flatCoordinates, offset, end, stride, false, false);
replayEnds.push(replayEnd);
offset = end;
}
return offset;
};
/**
* @inheritDoc.
*/
ol.render.canvas.Replay.prototype.drawCustom = function(geometry, feature, renderer) {
this.beginGeometry(geometry, feature);
var type = geometry.getType();
var stride = geometry.getStride();
var replayBegin = this.coordinates.length;
var flatCoordinates, replayEnd, replayEnds, replayEndss;
var offset;
if (type == ol.geom.GeometryType.MULTI_POLYGON) {
geometry = /** @type {ol.geom.MultiPolygon} */ (geometry);
flatCoordinates = geometry.getOrientedFlatCoordinates();
replayEndss = [];
var endss = geometry.getEndss();
offset = 0;
for (var i = 0, ii = endss.length; i < ii; ++i) {
var myEnds = [];
offset = this.drawCustomCoordinates_(flatCoordinates, offset, endss[i], stride, myEnds);
replayEndss.push(myEnds);
}
this.instructions.push([ol.render.canvas.Instruction.CUSTOM,
replayBegin, replayEndss, geometry, renderer, ol.geom.flat.inflate.coordinatesss]);
} else if (type == ol.geom.GeometryType.POLYGON || type == ol.geom.GeometryType.MULTI_LINE_STRING) {
replayEnds = [];
flatCoordinates = (type == ol.geom.GeometryType.POLYGON) ?
/** @type {ol.geom.Polygon} */ (geometry).getOrientedFlatCoordinates() :
geometry.getFlatCoordinates();
offset = this.drawCustomCoordinates_(flatCoordinates, 0,
/** @type {ol.geom.Polygon|ol.geom.MultiLineString} */ (geometry).getEnds(),
stride, replayEnds);
this.instructions.push([ol.render.canvas.Instruction.CUSTOM,
replayBegin, replayEnds, geometry, renderer, ol.geom.flat.inflate.coordinatess]);
} else if (type == ol.geom.GeometryType.LINE_STRING || type == ol.geom.GeometryType.MULTI_POINT) {
flatCoordinates = geometry.getFlatCoordinates();
replayEnd = this.appendFlatCoordinates(
flatCoordinates, 0, flatCoordinates.length, stride, false, false);
this.instructions.push([ol.render.canvas.Instruction.CUSTOM,
replayBegin, replayEnd, geometry, renderer, ol.geom.flat.inflate.coordinates]);
} else if (type == ol.geom.GeometryType.POINT) {
flatCoordinates = geometry.getFlatCoordinates();
this.coordinates.push(flatCoordinates[0], flatCoordinates[1]);
replayEnd = this.coordinates.length;
this.instructions.push([ol.render.canvas.Instruction.CUSTOM,
replayBegin, replayEnd, geometry, renderer]);
}
this.endGeometry(geometry, feature);
};
/** /**
* @protected * @protected
* @param {ol.geom.Geometry|ol.render.Feature} geometry Geometry. * @param {ol.geom.Geometry|ol.render.Feature} geometry Geometry.
@@ -326,15 +249,6 @@ ol.render.canvas.Replay.prototype.replay_ = function(
var prevX, prevY, roundX, roundY; var prevX, prevY, roundX, roundY;
var pendingFill = 0; var pendingFill = 0;
var pendingStroke = 0; var pendingStroke = 0;
var coordinateCache = this.coordinateCache_;
var state = /** @type {olx.render.State} */ ({
context: context,
pixelRatio: pixelRatio,
resolution: this.resolution,
rotation: viewRotation
});
// When the batch size gets too big, performance decreases. 200 is a good // When the batch size gets too big, performance decreases. 200 is a good
// balance between batch size and number of fill/stroke instructions. // balance between batch size and number of fill/stroke instructions.
var batchSize = var batchSize =
@@ -342,7 +256,7 @@ ol.render.canvas.Replay.prototype.replay_ = function(
while (i < ii) { while (i < ii) {
var instruction = instructions[i]; var instruction = instructions[i];
var type = /** @type {ol.render.canvas.Instruction} */ (instruction[0]); var type = /** @type {ol.render.canvas.Instruction} */ (instruction[0]);
var /** @type {ol.Feature|ol.render.Feature} */ feature, fill, stroke, text, x, y; var feature, fill, stroke, text, x, y;
switch (type) { switch (type) {
case ol.render.canvas.Instruction.BEGIN_GEOMETRY: case ol.render.canvas.Instruction.BEGIN_GEOMETRY:
feature = /** @type {ol.Feature|ol.render.Feature} */ (instruction[1]); feature = /** @type {ol.Feature|ol.render.Feature} */ (instruction[1]);
@@ -389,28 +303,6 @@ ol.render.canvas.Replay.prototype.replay_ = function(
context.closePath(); context.closePath();
++i; ++i;
break; break;
case ol.render.canvas.Instruction.CUSTOM:
d = /** @type {number} */ (instruction[1]);
dd = instruction[2];
var geometry = /** @type {ol.geom.SimpleGeometry} */ (instruction[3]);
var renderer = instruction[4];
var fn = instruction.length == 6 ? instruction[5] : undefined;
state.geometry = geometry;
state.feature = feature;
if (!(i in coordinateCache)) {
coordinateCache[i] = [];
}
var coords = coordinateCache[i];
if (fn) {
fn(pixelCoordinates, d, dd, 2, coords);
} else {
coords[0] = pixelCoordinates[d];
coords[1] = pixelCoordinates[d + 1];
coords.length = 2;
}
renderer(coords, state);
++i;
break;
case ol.render.canvas.Instruction.DRAW_IMAGE: case ol.render.canvas.Instruction.DRAW_IMAGE:
d = /** @type {number} */ (instruction[1]); d = /** @type {number} */ (instruction[1]);
dd = /** @type {number} */ (instruction[2]); dd = /** @type {number} */ (instruction[2]);
@@ -522,7 +414,8 @@ ol.render.canvas.Replay.prototype.replay_ = function(
break; break;
case ol.render.canvas.Instruction.END_GEOMETRY: case ol.render.canvas.Instruction.END_GEOMETRY:
if (featureCallback !== undefined) { if (featureCallback !== undefined) {
feature = /** @type {ol.Feature|ol.render.Feature} */ (instruction[1]); feature =
/** @type {ol.Feature|ol.render.Feature} */ (instruction[1]);
var result = featureCallback(feature); var result = featureCallback(feature);
if (result) { if (result) {
return result; return result;

View File

@@ -7,7 +7,6 @@ goog.require('ol.extent');
goog.require('ol.geom.flat.transform'); goog.require('ol.geom.flat.transform');
goog.require('ol.obj'); goog.require('ol.obj');
goog.require('ol.render.ReplayGroup'); goog.require('ol.render.ReplayGroup');
goog.require('ol.render.canvas.Replay');
goog.require('ol.render.canvas.ImageReplay'); goog.require('ol.render.canvas.ImageReplay');
goog.require('ol.render.canvas.LineStringReplay'); goog.require('ol.render.canvas.LineStringReplay');
goog.require('ol.render.canvas.PolygonReplay'); goog.require('ol.render.canvas.PolygonReplay');
@@ -162,24 +161,6 @@ ol.render.canvas.ReplayGroup.getCircleArray_ = function(radius) {
return arr; return arr;
}; };
/**
* @param {Array.<ol.render.ReplayType>} replays Replays.
* @return {boolean} Has replays of the provided types.
*/
ol.render.canvas.ReplayGroup.prototype.hasReplays = function(replays) {
for (var zIndex in this.replaysByZIndex_) {
var candidates = this.replaysByZIndex_[zIndex];
for (var i = 0, ii = replays.length; i < ii; ++i) {
if (replays[i] in candidates) {
return true;
}
}
}
return false;
};
/** /**
* FIXME empty description for jsdoc * FIXME empty description for jsdoc
*/ */
@@ -406,7 +387,6 @@ ol.render.canvas.ReplayGroup.prototype.replayHitDetection_ = function(
*/ */
ol.render.canvas.ReplayGroup.BATCH_CONSTRUCTORS_ = { ol.render.canvas.ReplayGroup.BATCH_CONSTRUCTORS_ = {
'Circle': ol.render.canvas.PolygonReplay, 'Circle': ol.render.canvas.PolygonReplay,
'Default': ol.render.canvas.Replay,
'Image': ol.render.canvas.ImageReplay, 'Image': ol.render.canvas.ImageReplay,
'LineString': ol.render.canvas.LineStringReplay, 'LineString': ol.render.canvas.LineStringReplay,
'Polygon': ol.render.canvas.PolygonReplay, 'Polygon': ol.render.canvas.PolygonReplay,

View File

@@ -12,6 +12,5 @@ ol.render.replay.ORDER = [
ol.render.ReplayType.CIRCLE, ol.render.ReplayType.CIRCLE,
ol.render.ReplayType.LINE_STRING, ol.render.ReplayType.LINE_STRING,
ol.render.ReplayType.IMAGE, ol.render.ReplayType.IMAGE,
ol.render.ReplayType.TEXT, ol.render.ReplayType.TEXT
ol.render.ReplayType.DEFAULT
]; ];

View File

@@ -6,7 +6,6 @@ goog.provide('ol.render.ReplayType');
*/ */
ol.render.ReplayType = { ol.render.ReplayType = {
CIRCLE: 'Circle', CIRCLE: 'Circle',
DEFAULT: 'Default',
IMAGE: 'Image', IMAGE: 'Image',
LINE_STRING: 'LineString', LINE_STRING: 'LineString',
POLYGON: 'Polygon', POLYGON: 'Polygon',

View File

@@ -13,16 +13,6 @@ ol.render.VectorContext = function() {
}; };
/**
* Render a geometry with a custom renderer.
*
* @param {ol.geom.SimpleGeometry} geometry Geometry.
* @param {ol.Feature|ol.render.Feature} feature Feature.
* @param {Function} renderer Renderer.
*/
ol.render.VectorContext.prototype.drawCustom = function(geometry, feature, renderer) {};
/** /**
* Render a geometry. * Render a geometry.
* *

View File

@@ -78,44 +78,10 @@ if (ol.ENABLE_WEBGL) {
*/ */
this.strokeStyle_ = null; this.strokeStyle_ = null;
/**
* @private
* @type {ol.style.Text}
*/
this.textStyle_ = null;
}; };
ol.inherits(ol.render.webgl.Immediate, ol.render.VectorContext); ol.inherits(ol.render.webgl.Immediate, ol.render.VectorContext);
/**
* @param {ol.render.webgl.ReplayGroup} replayGroup Replay group.
* @param {Array.<number>} flatCoordinates Flat coordinates.
* @param {number} offset Offset.
* @param {number} end End.
* @param {number} stride Stride.
* @private
*/
ol.render.webgl.Immediate.prototype.drawText_ = function(replayGroup,
flatCoordinates, offset, end, stride) {
var context = this.context_;
var replay = /** @type {ol.render.webgl.TextReplay} */ (
replayGroup.getReplay(0, ol.render.ReplayType.TEXT));
replay.setTextStyle(this.textStyle_);
replay.drawText(flatCoordinates, offset, end, stride, null, null);
replay.finish(context);
// default colors
var opacity = 1;
var skippedFeatures = {};
var featureCallback;
var oneByOne = false;
replay.replay(this.context_, this.center_, this.resolution_, this.rotation_,
this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback,
oneByOne);
replay.getDeleteResourcesFunction(context)();
};
/** /**
* Set the rendering style. Note that since this is an immediate rendering API, * Set the rendering style. Note that since this is an immediate rendering API,
* any `zIndex` on the provided style will be ignored. * any `zIndex` on the provided style will be ignored.
@@ -127,7 +93,6 @@ if (ol.ENABLE_WEBGL) {
ol.render.webgl.Immediate.prototype.setStyle = function(style) { ol.render.webgl.Immediate.prototype.setStyle = function(style) {
this.setFillStrokeStyle(style.getFill(), style.getStroke()); this.setFillStrokeStyle(style.getFill(), style.getStroke());
this.setImageStyle(style.getImage()); this.setImageStyle(style.getImage());
this.setTextStyle(style.getText());
}; };
@@ -219,12 +184,6 @@ if (ol.ENABLE_WEBGL) {
this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback,
oneByOne); oneByOne);
replay.getDeleteResourcesFunction(context)(); replay.getDeleteResourcesFunction(context)();
if (this.textStyle_) {
var flatCoordinates = geometry.getFlatCoordinates();
var stride = geometry.getStride();
this.drawText_(replayGroup, flatCoordinates, 0, flatCoordinates.length, stride);
}
}; };
@@ -247,12 +206,6 @@ if (ol.ENABLE_WEBGL) {
this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback,
oneByOne); oneByOne);
replay.getDeleteResourcesFunction(context)(); replay.getDeleteResourcesFunction(context)();
if (this.textStyle_) {
var flatCoordinates = geometry.getFlatCoordinates();
var stride = geometry.getStride();
this.drawText_(replayGroup, flatCoordinates, 0, flatCoordinates.length, stride);
}
}; };
@@ -275,11 +228,6 @@ if (ol.ENABLE_WEBGL) {
this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback,
oneByOne); oneByOne);
replay.getDeleteResourcesFunction(context)(); replay.getDeleteResourcesFunction(context)();
if (this.textStyle_) {
var flatMidpoint = geometry.getFlatMidpoint();
this.drawText_(replayGroup, flatMidpoint, 0, 2, 2);
}
}; };
@@ -302,11 +250,6 @@ if (ol.ENABLE_WEBGL) {
this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback,
oneByOne); oneByOne);
replay.getDeleteResourcesFunction(context)(); replay.getDeleteResourcesFunction(context)();
if (this.textStyle_) {
var flatMidpoints = geometry.getFlatMidpoints();
this.drawText_(replayGroup, flatMidpoints, 0, flatMidpoints.length, 2);
}
}; };
@@ -329,11 +272,6 @@ if (ol.ENABLE_WEBGL) {
this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback,
oneByOne); oneByOne);
replay.getDeleteResourcesFunction(context)(); replay.getDeleteResourcesFunction(context)();
if (this.textStyle_) {
var flatInteriorPoint = geometry.getFlatInteriorPoint();
this.drawText_(replayGroup, flatInteriorPoint, 0, 2, 2);
}
}; };
@@ -356,11 +294,6 @@ if (ol.ENABLE_WEBGL) {
this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback,
oneByOne); oneByOne);
replay.getDeleteResourcesFunction(context)(); replay.getDeleteResourcesFunction(context)();
if (this.textStyle_) {
var flatInteriorPoints = geometry.getFlatInteriorPoints();
this.drawText_(replayGroup, flatInteriorPoints, 0, flatInteriorPoints.length, 2);
}
}; };
@@ -383,10 +316,6 @@ if (ol.ENABLE_WEBGL) {
this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback, this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback,
oneByOne); oneByOne);
replay.getDeleteResourcesFunction(context)(); replay.getDeleteResourcesFunction(context)();
if (this.textStyle_) {
this.drawText_(replayGroup, geometry.getCenter(), 0, 2, 2);
}
}; };
@@ -406,12 +335,4 @@ if (ol.ENABLE_WEBGL) {
this.strokeStyle_ = strokeStyle; this.strokeStyle_ = strokeStyle;
}; };
/**
* @inheritDoc
*/
ol.render.webgl.Immediate.prototype.setTextStyle = function(textStyle) {
this.textStyle_ = textStyle;
};
} }

View File

@@ -79,8 +79,7 @@ if (ol.ENABLE_WEBGL) {
var outerRing = new ol.structs.LinkedList(); var outerRing = new ol.structs.LinkedList();
var rtree = new ol.structs.RBush(); var rtree = new ol.structs.RBush();
// Initialize the outer ring // Initialize the outer ring
this.processFlatCoordinates_(flatCoordinates, stride, outerRing, rtree, true); var maxX = this.processFlatCoordinates_(flatCoordinates, stride, outerRing, rtree, true);
var maxCoords = this.getMaxCoords_(outerRing);
// Eliminate holes, if there are any // Eliminate holes, if there are any
if (holeFlatCoordinates.length) { if (holeFlatCoordinates.length) {
@@ -89,18 +88,15 @@ if (ol.ENABLE_WEBGL) {
for (i = 0, ii = holeFlatCoordinates.length; i < ii; ++i) { for (i = 0, ii = holeFlatCoordinates.length; i < ii; ++i) {
var holeList = { var holeList = {
list: new ol.structs.LinkedList(), list: new ol.structs.LinkedList(),
maxCoords: undefined, maxX: undefined,
rtree: new ol.structs.RBush() rtree: new ol.structs.RBush()
}; };
holeLists.push(holeList); holeLists.push(holeList);
this.processFlatCoordinates_(holeFlatCoordinates[i], holeList.maxX = this.processFlatCoordinates_(holeFlatCoordinates[i],
stride, holeList.list, holeList.rtree, false); stride, holeList.list, holeList.rtree, false);
this.classifyPoints_(holeList.list, holeList.rtree, true);
holeList.maxCoords = this.getMaxCoords_(holeList.list);
} }
holeLists.sort(function(a, b) { holeLists.sort(function(a, b) {
return b.maxCoords[0] === a.maxCoords[0] ? return b.maxX[0] === a.maxX[0] ? a.maxX[1] - b.maxX[1] : b.maxX[0] - a.maxX[0];
a.maxCoords[1] - b.maxCoords[1] : b.maxCoords[0] - a.maxCoords[0];
}); });
for (i = 0; i < holeLists.length; ++i) { for (i = 0; i < holeLists.length; ++i) {
var currList = holeLists[i].list; var currList = holeLists[i].list;
@@ -108,7 +104,6 @@ if (ol.ENABLE_WEBGL) {
var currItem = start; var currItem = start;
var intersection; var intersection;
do { do {
//TODO: Triangulate holes when they intersect the outer ring.
if (this.getIntersections_(currItem, rtree).length) { if (this.getIntersections_(currItem, rtree).length) {
intersection = true; intersection = true;
break; break;
@@ -116,7 +111,8 @@ if (ol.ENABLE_WEBGL) {
currItem = currList.nextItem(); currItem = currList.nextItem();
} while (start !== currItem); } while (start !== currItem);
if (!intersection) { if (!intersection) {
if (this.bridgeHole_(currList, holeLists[i].maxCoords[0], outerRing, maxCoords[0], rtree)) { this.classifyPoints_(currList, holeLists[i].rtree, true);
if (this.bridgeHole_(currList, holeLists[i].maxX[0], outerRing, maxX[0], rtree)) {
rtree.concat(holeLists[i].rtree); rtree.concat(holeLists[i].rtree);
this.classifyPoints_(outerRing, rtree, false); this.classifyPoints_(outerRing, rtree, false);
} }
@@ -137,12 +133,13 @@ if (ol.ENABLE_WEBGL) {
* @param {ol.structs.LinkedList} list Linked list. * @param {ol.structs.LinkedList} list Linked list.
* @param {ol.structs.RBush} rtree R-Tree of the polygon. * @param {ol.structs.RBush} rtree R-Tree of the polygon.
* @param {boolean} clockwise Coordinate order should be clockwise. * @param {boolean} clockwise Coordinate order should be clockwise.
* @return {Array.<number>} X and Y coords of maximum X value.
*/ */
ol.render.webgl.PolygonReplay.prototype.processFlatCoordinates_ = function( ol.render.webgl.PolygonReplay.prototype.processFlatCoordinates_ = function(
flatCoordinates, stride, list, rtree, clockwise) { flatCoordinates, stride, list, rtree, clockwise) {
var isClockwise = ol.geom.flat.orient.linearRingIsClockwise(flatCoordinates, var isClockwise = ol.geom.flat.orient.linearRingIsClockwise(flatCoordinates,
0, flatCoordinates.length, stride); 0, flatCoordinates.length, stride);
var i, ii; var i, ii, maxXX, maxXY;
var n = this.vertices.length / 2; var n = this.vertices.length / 2;
/** @type {ol.WebglPolygonVertex} */ /** @type {ol.WebglPolygonVertex} */
var start; var start;
@@ -155,11 +152,17 @@ if (ol.ENABLE_WEBGL) {
if (clockwise === isClockwise) { if (clockwise === isClockwise) {
start = this.createPoint_(flatCoordinates[0], flatCoordinates[1], n++); start = this.createPoint_(flatCoordinates[0], flatCoordinates[1], n++);
p0 = start; p0 = start;
maxXX = flatCoordinates[0];
maxXY = flatCoordinates[1];
for (i = stride, ii = flatCoordinates.length; i < ii; i += stride) { for (i = stride, ii = flatCoordinates.length; i < ii; i += stride) {
p1 = this.createPoint_(flatCoordinates[i], flatCoordinates[i + 1], n++); p1 = this.createPoint_(flatCoordinates[i], flatCoordinates[i + 1], n++);
segments.push(this.insertItem_(p0, p1, list)); segments.push(this.insertItem_(p0, p1, list));
extents.push([Math.min(p0.x, p1.x), Math.min(p0.y, p1.y), Math.max(p0.x, p1.x), extents.push([Math.min(p0.x, p1.x), Math.min(p0.y, p1.y), Math.max(p0.x, p1.x),
Math.max(p0.y, p1.y)]); Math.max(p0.y, p1.y)]);
if (flatCoordinates[i] > maxXX) {
maxXX = flatCoordinates[i];
maxXY = flatCoordinates[i + 1];
}
p0 = p1; p0 = p1;
} }
segments.push(this.insertItem_(p1, start, list)); segments.push(this.insertItem_(p1, start, list));
@@ -169,11 +172,17 @@ if (ol.ENABLE_WEBGL) {
var end = flatCoordinates.length - stride; var end = flatCoordinates.length - stride;
start = this.createPoint_(flatCoordinates[end], flatCoordinates[end + 1], n++); start = this.createPoint_(flatCoordinates[end], flatCoordinates[end + 1], n++);
p0 = start; p0 = start;
maxXX = flatCoordinates[end];
maxXY = flatCoordinates[end + 1];
for (i = end - stride, ii = 0; i >= ii; i -= stride) { for (i = end - stride, ii = 0; i >= ii; i -= stride) {
p1 = this.createPoint_(flatCoordinates[i], flatCoordinates[i + 1], n++); p1 = this.createPoint_(flatCoordinates[i], flatCoordinates[i + 1], n++);
segments.push(this.insertItem_(p0, p1, list)); segments.push(this.insertItem_(p0, p1, list));
extents.push([Math.min(p0.x, p1.x), Math.min(p0.y, p1.y), Math.max(p0.x, p1.x), extents.push([Math.min(p0.x, p1.x), Math.min(p0.y, p1.y), Math.max(p0.x, p1.x),
Math.max(p0.y, p1.y)]); Math.max(p0.y, p1.y)]);
if (flatCoordinates[i] > maxXX) {
maxXX = flatCoordinates[i];
maxXY = flatCoordinates[i + 1];
}
p0 = p1; p0 = p1;
} }
segments.push(this.insertItem_(p1, start, list)); segments.push(this.insertItem_(p1, start, list));
@@ -181,28 +190,8 @@ if (ol.ENABLE_WEBGL) {
Math.max(p0.y, p1.y)]); Math.max(p0.y, p1.y)]);
} }
rtree.load(extents, segments); rtree.load(extents, segments);
};
return [maxXX, maxXY];
/**
* Returns the rightmost coordinates of a polygon on the X axis.
* @private
* @param {ol.structs.LinkedList} list Polygons ring.
* @return {Array.<number>} Max X coordinates.
*/
ol.render.webgl.PolygonReplay.prototype.getMaxCoords_ = function(list) {
var start = list.firstItem();
var seg = start;
var maxCoords = [seg.p0.x, seg.p0.y];
do {
seg = list.nextItem();
if (seg.p0.x > maxCoords[0]) {
maxCoords = [seg.p0.x, seg.p0.y];
}
} while (seg !== start);
return maxCoords;
}; };
@@ -336,7 +325,7 @@ if (ol.ENABLE_WEBGL) {
if (!this.classifyPoints_(list, rtree, ccw)) { if (!this.classifyPoints_(list, rtree, ccw)) {
// Due to the behavior of OL's PIP algorithm, the ear clipping cannot // Due to the behavior of OL's PIP algorithm, the ear clipping cannot
// introduce touching segments. However, the original data may have some. // introduce touching segments. However, the original data may have some.
if (!this.resolveSelfIntersections_(list, rtree, true)) { if (!this.resolveLocalSelfIntersections_(list, rtree, true)) {
break; break;
} }
} }
@@ -346,7 +335,7 @@ if (ol.ENABLE_WEBGL) {
// We ran out of ears, try to reclassify. // We ran out of ears, try to reclassify.
if (!this.classifyPoints_(list, rtree, ccw)) { if (!this.classifyPoints_(list, rtree, ccw)) {
// We have a bad polygon, try to resolve local self-intersections. // We have a bad polygon, try to resolve local self-intersections.
if (!this.resolveSelfIntersections_(list, rtree)) { if (!this.resolveLocalSelfIntersections_(list, rtree)) {
simple = this.isSimple_(list, rtree); simple = this.isSimple_(list, rtree);
if (!simple) { if (!simple) {
// We have a really bad polygon, try more time consuming methods. // We have a really bad polygon, try more time consuming methods.
@@ -393,15 +382,10 @@ if (ol.ENABLE_WEBGL) {
p2 = s2.p1; p2 = s2.p1;
if (p1.reflex === false) { if (p1.reflex === false) {
// We might have a valid ear // We might have a valid ear
var variableCriterion; var diagonalIsInside = ccw ? this.diagonalIsInside_(s3.p1, p2, p1, p0,
if (simple) { s0.p0) : this.diagonalIsInside_(s0.p0, p0, p1, p2, s3.p1);
variableCriterion = this.getPointsInTriangle_(p0, p1, p2, rtree, true).length === 0;
} else {
variableCriterion = ccw ? this.diagonalIsInside_(s3.p1, p2, p1, p0,
s0.p0) : this.diagonalIsInside_(s0.p0, p0, p1, p2, s3.p1);
}
if ((simple || this.getIntersections_({p0: p0, p1: p2}, rtree).length === 0) && if ((simple || this.getIntersections_({p0: p0, p1: p2}, rtree).length === 0) &&
variableCriterion) { diagonalIsInside && this.getPointsInTriangle_(p0, p1, p2, rtree, true).length === 0) {
//The diagonal is completely inside the polygon //The diagonal is completely inside the polygon
if (simple || p0.reflex === false || p2.reflex === false || if (simple || p0.reflex === false || p2.reflex === false ||
ol.geom.flat.orient.linearRingIsClockwise([s0.p0.x, s0.p0.y, p0.x, ol.geom.flat.orient.linearRingIsClockwise([s0.p0.x, s0.p0.y, p0.x,
@@ -436,7 +420,7 @@ if (ol.ENABLE_WEBGL) {
* @param {boolean=} opt_touch Resolve touching segments. * @param {boolean=} opt_touch Resolve touching segments.
* @return {boolean} There were resolved intersections. * @return {boolean} There were resolved intersections.
*/ */
ol.render.webgl.PolygonReplay.prototype.resolveSelfIntersections_ = function( ol.render.webgl.PolygonReplay.prototype.resolveLocalSelfIntersections_ = function(
list, rtree, opt_touch) { list, rtree, opt_touch) {
var start = list.firstItem(); var start = list.firstItem();
list.nextItem(); list.nextItem();

View File

@@ -129,8 +129,8 @@ if (ol.ENABLE_WEBGL) {
var lines = this.text_.split('\n'); var lines = this.text_.split('\n');
var textSize = this.getTextSize_(lines); var textSize = this.getTextSize_(lines);
var i, ii, j, jj, currX, currY, charArr, charInfo; var i, ii, j, jj, currX, currY, charArr, charInfo;
var anchorX = Math.round(textSize[0] * this.textAlign_ - this.offsetX_); var anchorX = Math.round(textSize[0] * this.textAlign_ + this.offsetX_);
var anchorY = Math.round(textSize[1] * this.textBaseline_ - this.offsetY_); var anchorY = Math.round(textSize[1] * this.textBaseline_ + this.offsetY_);
var lineWidth = (this.state_.lineWidth / 2) * this.state_.scale; var lineWidth = (this.state_.lineWidth / 2) * this.state_.scale;
for (i = 0, ii = lines.length; i < ii; ++i) { for (i = 0, ii = lines.length; i < ii; ++i) {

View File

@@ -319,7 +319,7 @@ ol.renderer.canvas.VectorLayer.prototype.prepareFrame = function(frameState, lay
feature, resolution, pixelRatio, styles, replayGroup); feature, resolution, pixelRatio, styles, replayGroup);
this.dirty_ = this.dirty_ || dirty; this.dirty_ = this.dirty_ || dirty;
} }
}.bind(this); };
if (vectorLayerRenderOrder) { if (vectorLayerRenderOrder) {
/** @type {Array.<ol.Feature>} */ /** @type {Array.<ol.Feature>} */
var features = []; var features = [];
@@ -331,9 +331,7 @@ ol.renderer.canvas.VectorLayer.prototype.prepareFrame = function(frameState, lay
features.push(feature); features.push(feature);
}, this); }, this);
features.sort(vectorLayerRenderOrder); features.sort(vectorLayerRenderOrder);
for (var i = 0, ii = features.length; i < ii; ++i) { features.forEach(renderFeature, this);
renderFeature(features[i]);
}
} else { } else {
vectorSource.forEachFeatureInExtent(extent, renderFeature, this); vectorSource.forEachFeatureInExtent(extent, renderFeature, this);
} }

View File

@@ -13,7 +13,6 @@ goog.require('ol.render.canvas.ReplayGroup');
goog.require('ol.render.replay'); goog.require('ol.render.replay');
goog.require('ol.renderer.canvas.TileLayer'); goog.require('ol.renderer.canvas.TileLayer');
goog.require('ol.renderer.vector'); goog.require('ol.renderer.vector');
goog.require('ol.size');
goog.require('ol.transform'); goog.require('ol.transform');
@@ -62,8 +61,7 @@ ol.inherits(ol.renderer.canvas.VectorTileLayer, ol.renderer.canvas.TileLayer);
* @type {!Object.<string, Array.<ol.render.ReplayType>>} * @type {!Object.<string, Array.<ol.render.ReplayType>>}
*/ */
ol.renderer.canvas.VectorTileLayer.IMAGE_REPLAYS = { ol.renderer.canvas.VectorTileLayer.IMAGE_REPLAYS = {
'image': [ol.render.ReplayType.POLYGON, ol.render.ReplayType.CIRCLE, 'image': ol.render.replay.ORDER,
ol.render.ReplayType.LINE_STRING, ol.render.ReplayType.IMAGE, ol.render.ReplayType.TEXT],
'hybrid': [ol.render.ReplayType.POLYGON, ol.render.ReplayType.LINE_STRING] 'hybrid': [ol.render.ReplayType.POLYGON, ol.render.ReplayType.LINE_STRING]
}; };
@@ -73,8 +71,7 @@ ol.renderer.canvas.VectorTileLayer.IMAGE_REPLAYS = {
* @type {!Object.<string, Array.<ol.render.ReplayType>>} * @type {!Object.<string, Array.<ol.render.ReplayType>>}
*/ */
ol.renderer.canvas.VectorTileLayer.VECTOR_REPLAYS = { ol.renderer.canvas.VectorTileLayer.VECTOR_REPLAYS = {
'image': [ol.render.ReplayType.DEFAULT], 'hybrid': [ol.render.ReplayType.IMAGE, ol.render.ReplayType.TEXT],
'hybrid': [ol.render.ReplayType.IMAGE, ol.render.ReplayType.TEXT, ol.render.ReplayType.DEFAULT],
'vector': ol.render.replay.ORDER 'vector': ol.render.replay.ORDER
}; };
@@ -120,31 +117,30 @@ ol.renderer.canvas.VectorTileLayer.prototype.createReplayGroup_ = function(
return; return;
} }
var source = /** @type {ol.source.VectorTile} */ (layer.getSource());
var sourceTileGrid = source.getTileGrid();
var tileGrid = source.getTileGridForProjection(projection);
var resolution = tileGrid.getResolution(tile.tileCoord[0]);
var tileExtent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord);
for (var t = 0, tt = tile.tileKeys.length; t < tt; ++t) { for (var t = 0, tt = tile.tileKeys.length; t < tt; ++t) {
var sourceTile = tile.getTile(tile.tileKeys[t]); var sourceTile = tile.getTile(tile.tileKeys[t]);
replayState.dirty = false; replayState.dirty = false;
var source = /** @type {ol.source.VectorTile} */ (layer.getSource());
var sourceTileGrid = source.getTileGrid();
var sourceTileCoord = sourceTile.tileCoord; var sourceTileCoord = sourceTile.tileCoord;
var tileProjection = sourceTile.getProjection(); var tileProjection = sourceTile.getProjection();
var tileGrid = source.getTileGridForProjection(projection);
var resolution = tileGrid.getResolution(tile.tileCoord[0]);
var sourceTileResolution = sourceTileGrid.getResolution(sourceTile.tileCoord[0]); var sourceTileResolution = sourceTileGrid.getResolution(sourceTile.tileCoord[0]);
var tileExtent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord);
var sourceTileExtent = sourceTileGrid.getTileCoordExtent(sourceTileCoord); var sourceTileExtent = sourceTileGrid.getTileCoordExtent(sourceTileCoord);
var sharedExtent = ol.extent.getIntersection(tileExtent, sourceTileExtent); var sharedExtent = ol.extent.getIntersection(tileExtent, sourceTileExtent);
var extent, reproject, tileResolution; var extent, reproject, tileResolution;
if (tileProjection.getUnits() == ol.proj.Units.TILE_PIXELS) { if (tileProjection.getUnits() == ol.proj.Units.TILE_PIXELS) {
var tilePixelRatio = tileResolution = this.getTilePixelRatio_(source, sourceTile); var tilePixelRatio = tileResolution = source.getTilePixelRatio();
var transform = ol.transform.compose(this.tmpTransform_, var transform = ol.transform.compose(this.tmpTransform_,
0, 0, 0, 0,
1 / sourceTileResolution * tilePixelRatio, -1 / sourceTileResolution * tilePixelRatio, 1 / sourceTileResolution * tilePixelRatio, -1 / sourceTileResolution * tilePixelRatio,
0, 0,
-sourceTileExtent[0], -sourceTileExtent[3]); -sourceTileExtent[0], -sourceTileExtent[3]);
extent = (ol.transform.apply(transform, [sharedExtent[0], sharedExtent[3]]) extent = (ol.transform.apply(transform, [sharedExtent[0], sharedExtent[3]])
.concat(ol.transform.apply(transform, [sharedExtent[2], sharedExtent[1]]))); .concat(ol.transform.apply(transform, [sharedExtent[2], sharedExtent[1]])));
} else { } else {
tileResolution = resolution; tileResolution = resolution;
extent = sharedExtent; extent = sharedExtent;
@@ -238,7 +234,7 @@ ol.renderer.canvas.VectorTileLayer.prototype.forEachFeatureAtCoordinate = functi
var sourceTileGrid = source.getTileGrid(); var sourceTileGrid = source.getTileGrid();
var bufferedExtent, found, tileSpaceCoordinate; var bufferedExtent, found, tileSpaceCoordinate;
var i, ii, origin, replayGroup; var i, ii, origin, replayGroup;
var tile, tileCoord, tileExtent, tilePixelRatio, tileRenderResolution; var tile, tileCoord, tileExtent, tilePixelRatio, tileResolution;
for (i = 0, ii = renderedTiles.length; i < ii; ++i) { for (i = 0, ii = renderedTiles.length; i < ii; ++i) {
tile = renderedTiles[i]; tile = renderedTiles[i];
tileCoord = tile.tileCoord; tileCoord = tile.tileCoord;
@@ -253,15 +249,13 @@ ol.renderer.canvas.VectorTileLayer.prototype.forEachFeatureAtCoordinate = functi
var sourceTileCoord = sourceTile.tileCoord; var sourceTileCoord = sourceTile.tileCoord;
var sourceTileExtent = sourceTileGrid.getTileCoordExtent(sourceTileCoord, this.tmpExtent); var sourceTileExtent = sourceTileGrid.getTileCoordExtent(sourceTileCoord, this.tmpExtent);
origin = ol.extent.getTopLeft(sourceTileExtent); origin = ol.extent.getTopLeft(sourceTileExtent);
tilePixelRatio = this.getTilePixelRatio_(source, sourceTile); tilePixelRatio = source.getTilePixelRatio();
var sourceTileResolution = sourceTileGrid.getResolution(sourceTileCoord[0]); tileResolution = sourceTileGrid.getResolution(sourceTileCoord[0]) / tilePixelRatio;
tileRenderResolution = sourceTileResolution / tilePixelRatio;
tileSpaceCoordinate = [ tileSpaceCoordinate = [
(coordinate[0] - origin[0]) / tileRenderResolution, (coordinate[0] - origin[0]) / tileResolution,
(origin[1] - coordinate[1]) / tileRenderResolution (origin[1] - coordinate[1]) / tileResolution
]; ];
var upscaling = tileGrid.getResolution(tileCoord[0]) / sourceTileResolution; resolution = tilePixelRatio;
resolution = tilePixelRatio * upscaling;
} else { } else {
tileSpaceCoordinate = coordinate; tileSpaceCoordinate = coordinate;
} }
@@ -298,7 +292,7 @@ ol.renderer.canvas.VectorTileLayer.prototype.getReplayTransform_ = function(tile
var tileGrid = source.getTileGrid(); var tileGrid = source.getTileGrid();
var tileCoord = tile.tileCoord; var tileCoord = tile.tileCoord;
var tileResolution = var tileResolution =
tileGrid.getResolution(tileCoord[0]) / this.getTilePixelRatio_(source, tile); tileGrid.getResolution(tileCoord[0]) / source.getTilePixelRatio();
var viewState = frameState.viewState; var viewState = frameState.viewState;
var pixelRatio = frameState.pixelRatio; var pixelRatio = frameState.pixelRatio;
var renderResolution = viewState.resolution / pixelRatio; var renderResolution = viewState.resolution / pixelRatio;
@@ -320,18 +314,6 @@ ol.renderer.canvas.VectorTileLayer.prototype.getReplayTransform_ = function(tile
}; };
/**
* @private
* @param {ol.source.VectorTile} source Source.
* @param {ol.VectorTile} tile Tile.
* @return {number} The tile's pixel ratio.
*/
ol.renderer.canvas.VectorTileLayer.prototype.getTilePixelRatio_ = function(source, tile) {
return ol.extent.getWidth(tile.getExtent()) /
ol.size.toSize(source.getTileGrid().getTileSize(tile.tileCoord[0]))[0];
};
/** /**
* Handle changes in image style state. * Handle changes in image style state.
* @param {ol.events.Event} event Image style change event. * @param {ol.events.Event} event Image style change event.
@@ -347,65 +329,64 @@ ol.renderer.canvas.VectorTileLayer.prototype.handleStyleImageChange_ = function(
*/ */
ol.renderer.canvas.VectorTileLayer.prototype.postCompose = function(context, frameState, layerState) { ol.renderer.canvas.VectorTileLayer.prototype.postCompose = function(context, frameState, layerState) {
var layer = this.getLayer(); var layer = this.getLayer();
var source = /** @type {ol.source.VectorTile} */ (layer.getSource()); var source = layer.getSource();
var renderMode = layer.getRenderMode(); var renderMode = layer.getRenderMode();
var replays = ol.renderer.canvas.VectorTileLayer.VECTOR_REPLAYS[renderMode]; var replays = ol.renderer.canvas.VectorTileLayer.VECTOR_REPLAYS[renderMode];
var pixelRatio = frameState.pixelRatio; if (replays) {
var rotation = frameState.viewState.rotation; var pixelRatio = frameState.pixelRatio;
var size = frameState.size; var rotation = frameState.viewState.rotation;
var offsetX = Math.round(pixelRatio * size[0] / 2); var size = frameState.size;
var offsetY = Math.round(pixelRatio * size[1] / 2); var offsetX = Math.round(pixelRatio * size[0] / 2);
var tiles = this.renderedTiles; var offsetY = Math.round(pixelRatio * size[1] / 2);
var sourceTileGrid = source.getTileGrid(); var tiles = this.renderedTiles;
var tileGrid = source.getTileGridForProjection(frameState.viewState.projection); var tilePixelRatio = layer.getSource().getTilePixelRatio();
var clips = []; var sourceTileGrid = source.getTileGrid();
var zs = []; var tileGrid = source.getTileGridForProjection(frameState.viewState.projection);
for (var i = tiles.length - 1; i >= 0; --i) { var clips = [];
var tile = /** @type {ol.VectorImageTile} */ (tiles[i]); var zs = [];
if (tile.getState() == ol.TileState.ABORT) { for (var i = tiles.length - 1; i >= 0; --i) {
continue; var tile = /** @type {ol.VectorImageTile} */ (tiles[i]);
} if (tile.getState() == ol.TileState.ABORT) {
var tileCoord = tile.tileCoord;
var worldOffset = tileGrid.getTileCoordExtent(tileCoord)[0] -
tileGrid.getTileCoordExtent(tile.wrappedTileCoord)[0];
for (var t = 0, tt = tile.tileKeys.length; t < tt; ++t) {
var sourceTile = tile.getTile(tile.tileKeys[t]);
var tilePixelRatio = this.getTilePixelRatio_(source, sourceTile);
var replayGroup = sourceTile.getReplayGroup(layer, tileCoord.toString());
if (renderMode != ol.layer.VectorTileRenderType.VECTOR && !replayGroup.hasReplays(replays)) {
continue; continue;
} }
var currentZ = sourceTile.tileCoord[0]; var tileCoord = tile.tileCoord;
var sourceResolution = sourceTileGrid.getResolution(currentZ); var worldOffset = tileGrid.getTileCoordExtent(tileCoord)[0] -
var transform = this.getReplayTransform_(sourceTile, frameState); tileGrid.getTileCoordExtent(tile.wrappedTileCoord)[0];
ol.transform.translate(transform, worldOffset * tilePixelRatio / sourceResolution, 0); for (var t = 0, tt = tile.tileKeys.length; t < tt; ++t) {
var currentClip = replayGroup.getClipCoords(transform); var sourceTile = tile.getTile(tile.tileKeys[t]);
context.save(); var currentZ = sourceTile.tileCoord[0];
context.globalAlpha = layerState.opacity; var sourceResolution = sourceTileGrid.getResolution(currentZ);
ol.render.canvas.rotateAtOffset(context, -rotation, offsetX, offsetY); var transform = this.getReplayTransform_(sourceTile, frameState);
// Create a clip mask for regions in this low resolution tile that are ol.transform.translate(transform, worldOffset * tilePixelRatio / sourceResolution, 0);
// already filled by a higher resolution tile var replayGroup = sourceTile.getReplayGroup(layer, tileCoord.toString());
for (var j = 0, jj = clips.length; j < jj; ++j) { var currentClip = replayGroup.getClipCoords(transform);
var clip = clips[j]; context.save();
if (currentZ < zs[j]) { context.globalAlpha = layerState.opacity;
context.beginPath(); ol.render.canvas.rotateAtOffset(context, -rotation, offsetX, offsetY);
// counter-clockwise (outer ring) for current tile // Create a clip mask for regions in this low resolution tile that are
context.moveTo(currentClip[0], currentClip[1]); // already filled by a higher resolution tile
context.lineTo(currentClip[2], currentClip[3]); for (var j = 0, jj = clips.length; j < jj; ++j) {
context.lineTo(currentClip[4], currentClip[5]); var clip = clips[j];
context.lineTo(currentClip[6], currentClip[7]); if (currentZ < zs[j]) {
// clockwise (inner ring) for higher resolution tile context.beginPath();
context.moveTo(clip[6], clip[7]); // counter-clockwise (outer ring) for current tile
context.lineTo(clip[4], clip[5]); context.moveTo(currentClip[0], currentClip[1]);
context.lineTo(clip[2], clip[3]); context.lineTo(currentClip[2], currentClip[3]);
context.lineTo(clip[0], clip[1]); context.lineTo(currentClip[4], currentClip[5]);
context.clip(); context.lineTo(currentClip[6], currentClip[7]);
// clockwise (inner ring) for higher resolution tile
context.moveTo(clip[6], clip[7]);
context.lineTo(clip[4], clip[5]);
context.lineTo(clip[2], clip[3]);
context.lineTo(clip[0], clip[1]);
context.clip();
}
} }
replayGroup.replay(context, pixelRatio, transform, rotation, {}, replays);
context.restore();
clips.push(currentClip);
zs.push(currentZ);
} }
replayGroup.replay(context, pixelRatio, transform, rotation, {}, replays);
context.restore();
clips.push(currentClip);
zs.push(currentZ);
} }
} }
ol.renderer.canvas.TileLayer.prototype.postCompose.apply(this, arguments); ol.renderer.canvas.TileLayer.prototype.postCompose.apply(this, arguments);
@@ -457,10 +438,11 @@ ol.renderer.canvas.VectorTileLayer.prototype.renderTileImage_ = function(
var tileCoord = tile.wrappedTileCoord; var tileCoord = tile.wrappedTileCoord;
var z = tileCoord[0]; var z = tileCoord[0];
var pixelRatio = frameState.pixelRatio; var pixelRatio = frameState.pixelRatio;
var source = /** @type {ol.source.VectorTile} */ (layer.getSource()); var source = layer.getSource();
var sourceTileGrid = source.getTileGrid(); var sourceTileGrid = source.getTileGrid();
var tileGrid = source.getTileGridForProjection(frameState.viewState.projection); var tileGrid = source.getTileGridForProjection(frameState.viewState.projection);
var resolution = tileGrid.getResolution(z); var resolution = tileGrid.getResolution(z);
var tilePixelRatio = source.getTilePixelRatio();
var context = tile.getContext(layer); var context = tile.getContext(layer);
var size = source.getTilePixelSize(z, pixelRatio, frameState.viewState.projection); var size = source.getTilePixelSize(z, pixelRatio, frameState.viewState.projection);
context.canvas.width = size[0]; context.canvas.width = size[0];
@@ -468,7 +450,6 @@ ol.renderer.canvas.VectorTileLayer.prototype.renderTileImage_ = function(
var tileExtent = tileGrid.getTileCoordExtent(tileCoord); var tileExtent = tileGrid.getTileCoordExtent(tileCoord);
for (var i = 0, ii = tile.tileKeys.length; i < ii; ++i) { for (var i = 0, ii = tile.tileKeys.length; i < ii; ++i) {
var sourceTile = tile.getTile(tile.tileKeys[i]); var sourceTile = tile.getTile(tile.tileKeys[i]);
var tilePixelRatio = this.getTilePixelRatio_(source, sourceTile);
var sourceTileCoord = sourceTile.tileCoord; var sourceTileCoord = sourceTile.tileCoord;
var pixelScale = pixelRatio / resolution; var pixelScale = pixelRatio / resolution;
var transform = ol.transform.reset(this.tmpTransform_); var transform = ol.transform.reset(this.tmpTransform_);
@@ -485,7 +466,7 @@ ol.renderer.canvas.VectorTileLayer.prototype.renderTileImage_ = function(
ol.transform.translate(transform, -tileExtent[0], -tileExtent[3]); ol.transform.translate(transform, -tileExtent[0], -tileExtent[3]);
} }
var replayGroup = sourceTile.getReplayGroup(layer, tile.tileCoord.toString()); var replayGroup = sourceTile.getReplayGroup(layer, tile.tileCoord.toString());
replayGroup.replay(context, pixelRatio, transform, 0, {}, replays, true); replayGroup.replay(context, pixelRatio, transform, 0, {}, replays);
} }
} }
}; };

View File

@@ -2,7 +2,6 @@ goog.provide('ol.renderer.vector');
goog.require('ol'); goog.require('ol');
goog.require('ol.ImageState'); goog.require('ol.ImageState');
goog.require('ol.geom.GeometryType');
goog.require('ol.render.ReplayType'); goog.require('ol.render.ReplayType');
@@ -112,34 +111,9 @@ ol.renderer.vector.renderFeature_ = function(
return; return;
} }
var simplifiedGeometry = geometry.getSimplifiedGeometry(squaredTolerance); var simplifiedGeometry = geometry.getSimplifiedGeometry(squaredTolerance);
var renderer = style.getRenderer(); var geometryRenderer =
if (renderer) { ol.renderer.vector.GEOMETRY_RENDERERS_[simplifiedGeometry.getType()];
ol.renderer.vector.renderGeometry_(replayGroup, simplifiedGeometry, style, feature); geometryRenderer(replayGroup, simplifiedGeometry, style, feature);
} else {
var geometryRenderer =
ol.renderer.vector.GEOMETRY_RENDERERS_[simplifiedGeometry.getType()];
geometryRenderer(replayGroup, simplifiedGeometry, style, feature);
}
};
/**
* @param {ol.render.ReplayGroup} replayGroup Replay group.
* @param {ol.geom.Geometry} geometry Geometry.
* @param {ol.style.Style} style Style.
* @param {ol.Feature|ol.render.Feature} feature Feature.
* @private
*/
ol.renderer.vector.renderGeometry_ = function(replayGroup, geometry, style, feature) {
if (geometry.getType() == ol.geom.GeometryType.GEOMETRY_COLLECTION) {
var geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries();
for (var i = 0, ii = geometries.length; i < ii; ++i) {
ol.renderer.vector.renderGeometry_(replayGroup, geometries[i], style, feature);
}
return;
}
var replay = replayGroup.getReplay(style.getZIndex(), ol.render.ReplayType.DEFAULT);
replay.drawCustom(/** @type {ol.geom.SimpleGeometry} */ (geometry), feature, style.getRenderer());
}; };

View File

@@ -141,7 +141,7 @@ ol.source.BingMaps.prototype.handleImageryMetadataResponse = function(response)
extent: extent, extent: extent,
minZoom: resource.zoomMin, minZoom: resource.zoomMin,
maxZoom: maxZoom, maxZoom: maxZoom,
tileSize: tileSize / (this.hidpi_ ? 2 : 1) tileSize: tileSize / this.getTilePixelRatio()
}); });
this.tileGrid = tileGrid; this.tileGrid = tileGrid;

View File

@@ -74,7 +74,8 @@ ol.source.ImageWMS = function(opt_options) {
* @private * @private
* @type {ol.source.WMSServerType|undefined} * @type {ol.source.WMSServerType|undefined}
*/ */
this.serverType_ = /** @type {ol.source.WMSServerType|undefined} */ (options.serverType); this.serverType_ =
/** @type {ol.source.WMSServerType|undefined} */ (options.serverType);
/** /**
* @private * @private

View File

@@ -244,11 +244,12 @@ ol.source.Tile.prototype.getTileCacheForProjection = function(projection) {
/** /**
* Get the tile pixel ratio for this source. Subclasses may override this * Get the tile pixel ratio for this source. Subclasses may override this
* method, which is meant to return a supported pixel ratio that matches the * method, which is meant to return a supported pixel ratio that matches the
* provided `pixelRatio` as close as possible. * provided `opt_pixelRatio` as close as possible. When no `opt_pixelRatio` is
* @param {number} pixelRatio Pixel ratio. * provided, it is meant to return `this.tilePixelRatio_`.
* @param {number=} opt_pixelRatio Pixel ratio.
* @return {number} Tile pixel ratio. * @return {number} Tile pixel ratio.
*/ */
ol.source.Tile.prototype.getTilePixelRatio = function(pixelRatio) { ol.source.Tile.prototype.getTilePixelRatio = function(opt_pixelRatio) {
return this.tilePixelRatio_; return this.tilePixelRatio_;
}; };

View File

@@ -42,7 +42,6 @@ ol.source.TileWMS = function(opt_options) {
opaque: !transparent, opaque: !transparent,
projection: options.projection, projection: options.projection,
reprojectionErrorThreshold: options.reprojectionErrorThreshold, reprojectionErrorThreshold: options.reprojectionErrorThreshold,
tileClass: options.tileClass,
tileGrid: options.tileGrid, tileGrid: options.tileGrid,
tileLoadFunction: options.tileLoadFunction, tileLoadFunction: options.tileLoadFunction,
url: options.url, url: options.url,
@@ -72,7 +71,8 @@ ol.source.TileWMS = function(opt_options) {
* @private * @private
* @type {ol.source.WMSServerType|undefined} * @type {ol.source.WMSServerType|undefined}
*/ */
this.serverType_ = /** @type {ol.source.WMSServerType|undefined} */ (options.serverType); this.serverType_ =
/** @type {ol.source.WMSServerType|undefined} */ (options.serverType);
/** /**
* @private * @private

View File

@@ -27,29 +27,20 @@ goog.require('ol.source.UrlTile');
* @api * @api
*/ */
ol.source.VectorTile = function(options) { ol.source.VectorTile = function(options) {
var projection = options.projection || 'EPSG:3857';
var extent = options.extent || ol.tilegrid.extentFromProjection(projection);
var tileGrid = options.tileGrid || ol.tilegrid.createXYZ({
extent: extent,
maxZoom: options.maxZoom || 22,
minZoom: options.minZoom,
tileSize: options.tileSize || 512
});
ol.source.UrlTile.call(this, { ol.source.UrlTile.call(this, {
attributions: options.attributions, attributions: options.attributions,
cacheSize: options.cacheSize !== undefined ? options.cacheSize : 128, cacheSize: options.cacheSize !== undefined ? options.cacheSize : 128,
extent: extent, extent: options.extent,
logo: options.logo, logo: options.logo,
opaque: false, opaque: false,
projection: projection, projection: options.projection,
state: options.state, state: options.state,
tileGrid: tileGrid, tileGrid: options.tileGrid,
tileLoadFunction: options.tileLoadFunction ? tileLoadFunction: options.tileLoadFunction ?
options.tileLoadFunction : ol.VectorImageTile.defaultLoadFunction, options.tileLoadFunction : ol.VectorImageTile.defaultLoadFunction,
tileUrlFunction: options.tileUrlFunction, tileUrlFunction: options.tileUrlFunction,
tilePixelRatio: options.tilePixelRatio,
url: options.url, url: options.url,
urls: options.urls, urls: options.urls,
wrapX: options.wrapX === undefined ? true : options.wrapX wrapX: options.wrapX === undefined ? true : options.wrapX
@@ -150,8 +141,10 @@ ol.source.VectorTile.prototype.getTileGridForProjection = function(projection) {
/** /**
* @inheritDoc * @inheritDoc
*/ */
ol.source.VectorTile.prototype.getTilePixelRatio = function(pixelRatio) { ol.source.VectorTile.prototype.getTilePixelRatio = function(opt_pixelRatio) {
return pixelRatio; return opt_pixelRatio == undefined ?
ol.source.UrlTile.prototype.getTilePixelRatio.call(this, opt_pixelRatio) :
opt_pixelRatio;
}; };

View File

@@ -8,7 +8,6 @@
goog.provide('ol.Sphere'); goog.provide('ol.Sphere');
goog.require('ol.math'); goog.require('ol.math');
goog.require('ol.geom.GeometryType');
/** /**
@@ -52,7 +51,18 @@ ol.Sphere = function(radius) {
* @api * @api
*/ */
ol.Sphere.prototype.geodesicArea = function(coordinates) { ol.Sphere.prototype.geodesicArea = function(coordinates) {
return ol.Sphere.getArea_(coordinates, this.radius); var area = 0, len = coordinates.length;
var x1 = coordinates[len - 1][0];
var y1 = coordinates[len - 1][1];
for (var i = 0; i < len; i++) {
var x2 = coordinates[i][0], y2 = coordinates[i][1];
area += ol.math.toRadians(x2 - x1) *
(2 + Math.sin(ol.math.toRadians(y1)) +
Math.sin(ol.math.toRadians(y2)));
x1 = x2;
y1 = y2;
}
return area * this.radius * this.radius / 2.0;
}; };
@@ -65,7 +75,14 @@ ol.Sphere.prototype.geodesicArea = function(coordinates) {
* @api * @api
*/ */
ol.Sphere.prototype.haversineDistance = function(c1, c2) { ol.Sphere.prototype.haversineDistance = function(c1, c2) {
return ol.Sphere.getDistance_(c1, c2, this.radius); var lat1 = ol.math.toRadians(c1[1]);
var lat2 = ol.math.toRadians(c2[1]);
var deltaLatBy2 = (lat2 - lat1) / 2;
var deltaLonBy2 = ol.math.toRadians(c2[0] - c1[0]) / 2;
var a = Math.sin(deltaLatBy2) * Math.sin(deltaLatBy2) +
Math.sin(deltaLonBy2) * Math.sin(deltaLonBy2) *
Math.cos(lat1) * Math.cos(lat2);
return 2 * this.radius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}; };
@@ -90,197 +107,3 @@ ol.Sphere.prototype.offset = function(c1, distance, bearing) {
Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat)); Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat));
return [ol.math.toDegrees(lon), ol.math.toDegrees(lat)]; return [ol.math.toDegrees(lon), ol.math.toDegrees(lat)];
}; };
/**
* The mean Earth radius (1/3 * (2a + b)) for the WGS84 ellipsoid.
* https://en.wikipedia.org/wiki/Earth_radius#Mean_radius
* @type {number}
*/
ol.Sphere.DEFAULT_RADIUS = 6371008.8;
/**
* Get the spherical length of a geometry. This length is the sum of the
* great circle distances between coordinates. For polygons, the length is
* the sum of all rings. For points, the length is zero. For multi-part
* geometries, the length is the sum of the length of each part.
* @param {ol.geom.Geometry} geometry A geometry.
* @param {olx.SphereMetricOptions=} opt_options Options for the length
* calculation. By default, geometries are assumed to be in 'EPSG:3857'.
* You can change this by providing a `projection` option.
* @return {number} The spherical length (in meters).
*/
ol.Sphere.getLength = function(geometry, opt_options) {
var options = opt_options || {};
var radius = options.radius || ol.Sphere.DEFAULT_RADIUS;
var projection = options.projection || 'EPSG:3857';
geometry = geometry.clone().transform(projection, 'EPSG:4326');
var type = geometry.getType();
var length = 0;
var coordinates, coords, i, ii, j, jj;
switch (type) {
case ol.geom.GeometryType.POINT:
case ol.geom.GeometryType.MULTI_POINT: {
break;
}
case ol.geom.GeometryType.LINE_STRING:
case ol.geom.GeometryType.LINEAR_RING: {
coordinates = /** @type {ol.geom.SimpleGeometry} */ (geometry).getCoordinates();
length = ol.Sphere.getLength_(coordinates, radius);
break;
}
case ol.geom.GeometryType.MULTI_LINE_STRING:
case ol.geom.GeometryType.POLYGON: {
coordinates = /** @type {ol.geom.SimpleGeometry} */ (geometry).getCoordinates();
for (i = 0, ii = coordinates.length; i < ii; ++i) {
length += ol.Sphere.getLength_(coordinates[i], radius);
}
break;
}
case ol.geom.GeometryType.MULTI_POLYGON: {
coordinates = /** @type {ol.geom.SimpleGeometry} */ (geometry).getCoordinates();
for (i = 0, ii = coordinates.length; i < ii; ++i) {
coords = coordinates[i];
for (j = 0, jj = coords.length; j < jj; ++j) {
length += ol.Sphere.getLength_(coords[j], radius);
}
}
break;
}
case ol.geom.GeometryType.GEOMETRY_COLLECTION: {
var geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries();
for (i = 0, ii = geometries.length; i < ii; ++i) {
length += ol.Sphere.getLength(geometries[i], opt_options);
}
break;
}
default: {
throw new Error('Unsupported geometry type: ' + type);
}
}
return length;
};
/**
* Get the cumulative great circle length of linestring coordinates (geographic).
* @param {Array} coordinates Linestring coordinates.
* @param {number} radius The sphere radius to use.
* @return {number} The length (in meters).
*/
ol.Sphere.getLength_ = function(coordinates, radius) {
var length = 0;
for (var i = 0, ii = coordinates.length; i < ii - 1; ++i) {
length += ol.Sphere.getDistance_(coordinates[i], coordinates[i + 1], radius);
}
return length;
};
/**
* Get the great circle distance between two geographic coordinates.
* @param {Array} c1 Starting coordinate.
* @param {Array} c2 Ending coordinate.
* @param {number} radius The sphere radius to use.
* @return {number} The great circle distance between the points (in meters).
*/
ol.Sphere.getDistance_ = function(c1, c2, radius) {
var lat1 = ol.math.toRadians(c1[1]);
var lat2 = ol.math.toRadians(c2[1]);
var deltaLatBy2 = (lat2 - lat1) / 2;
var deltaLonBy2 = ol.math.toRadians(c2[0] - c1[0]) / 2;
var a = Math.sin(deltaLatBy2) * Math.sin(deltaLatBy2) +
Math.sin(deltaLonBy2) * Math.sin(deltaLonBy2) *
Math.cos(lat1) * Math.cos(lat2);
return 2 * radius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
};
/**
* Get the spherical area of a geometry. This is the area (in meters) assuming
* that polygon edges are segments of great circles on a sphere.
* @param {ol.geom.Geometry} geometry A geometry.
* @param {olx.SphereMetricOptions=} opt_options Options for the area
* calculation. By default, geometries are assumed to be in 'EPSG:3857'.
* You can change this by providing a `projection` option.
* @return {number} The spherical area (in square meters).
*/
ol.Sphere.getArea = function(geometry, opt_options) {
var options = opt_options || {};
var radius = options.radius || ol.Sphere.DEFAULT_RADIUS;
var projection = options.projection || 'EPSG:3857';
geometry = geometry.clone().transform(projection, 'EPSG:4326');
var type = geometry.getType();
var area = 0;
var coordinates, coords, i, ii, j, jj;
switch (type) {
case ol.geom.GeometryType.POINT:
case ol.geom.GeometryType.MULTI_POINT:
case ol.geom.GeometryType.LINE_STRING:
case ol.geom.GeometryType.MULTI_LINE_STRING:
case ol.geom.GeometryType.LINEAR_RING: {
break;
}
case ol.geom.GeometryType.POLYGON: {
coordinates = /** @type {ol.geom.Polygon} */ (geometry).getCoordinates();
area = Math.abs(ol.Sphere.getArea_(coordinates[0], radius));
for (i = 1, ii = coordinates.length; i < ii; ++i) {
area -= Math.abs(ol.Sphere.getArea_(coordinates[i], radius));
}
break;
}
case ol.geom.GeometryType.MULTI_POLYGON: {
coordinates = /** @type {ol.geom.SimpleGeometry} */ (geometry).getCoordinates();
for (i = 0, ii = coordinates.length; i < ii; ++i) {
coords = coordinates[i];
area += Math.abs(ol.Sphere.getArea_(coords[0], radius));
for (j = 1, jj = coords.length; j < jj; ++j) {
area -= Math.abs(ol.Sphere.getArea_(coords[j], radius));
}
}
break;
}
case ol.geom.GeometryType.GEOMETRY_COLLECTION: {
var geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries();
for (i = 0, ii = geometries.length; i < ii; ++i) {
area += ol.Sphere.getArea(geometries[i], opt_options);
}
break;
}
default: {
throw new Error('Unsupported geometry type: ' + type);
}
}
return area;
};
/**
* Returns the spherical area for a list of coordinates.
*
* [Reference](https://trs-new.jpl.nasa.gov/handle/2014/40409)
* Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
* Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
* Laboratory, Pasadena, CA, June 2007
*
* @param {Array.<ol.Coordinate>} coordinates List of coordinates of a linear
* ring. If the ring is oriented clockwise, the area will be positive,
* otherwise it will be negative.
* @param {number} radius The sphere radius.
* @return {number} Area (in square meters).
*/
ol.Sphere.getArea_ = function(coordinates, radius) {
var area = 0, len = coordinates.length;
var x1 = coordinates[len - 1][0];
var y1 = coordinates[len - 1][1];
for (var i = 0; i < len; i++) {
var x2 = coordinates[i][0], y2 = coordinates[i][1];
area += ol.math.toRadians(x2 - x1) *
(2 + Math.sin(ol.math.toRadians(y1)) +
Math.sin(ol.math.toRadians(y2)));
x1 = x2;
y1 = y2;
}
return area * radius * radius / 2.0;
};

View File

@@ -317,7 +317,6 @@ ol.style.RegularShape.prototype.render_ = function(atlasManager) {
var lineJoin = ''; var lineJoin = '';
var miterLimit = 0; var miterLimit = 0;
var lineDash = null; var lineDash = null;
var lineDashOffset = 0;
var strokeStyle; var strokeStyle;
var strokeWidth = 0; var strokeWidth = 0;
@@ -332,10 +331,8 @@ ol.style.RegularShape.prototype.render_ = function(atlasManager) {
strokeWidth = ol.render.canvas.defaultLineWidth; strokeWidth = ol.render.canvas.defaultLineWidth;
} }
lineDash = this.stroke_.getLineDash(); lineDash = this.stroke_.getLineDash();
lineDashOffset = this.stroke_.getLineDashOffset();
if (!ol.has.CANVAS_LINE_DASH) { if (!ol.has.CANVAS_LINE_DASH) {
lineDash = null; lineDash = null;
lineDashOffset = 0;
} }
lineJoin = this.stroke_.getLineJoin(); lineJoin = this.stroke_.getLineJoin();
if (lineJoin === undefined) { if (lineJoin === undefined) {
@@ -360,7 +357,6 @@ ol.style.RegularShape.prototype.render_ = function(atlasManager) {
size: size, size: size,
lineCap: lineCap, lineCap: lineCap,
lineDash: lineDash, lineDash: lineDash,
lineDashOffset: lineDashOffset,
lineJoin: lineJoin, lineJoin: lineJoin,
miterLimit: miterLimit miterLimit: miterLimit
}; };
@@ -464,7 +460,6 @@ ol.style.RegularShape.prototype.draw_ = function(renderOptions, context, x, y) {
context.lineWidth = renderOptions.strokeWidth; context.lineWidth = renderOptions.strokeWidth;
if (renderOptions.lineDash) { if (renderOptions.lineDash) {
context.setLineDash(renderOptions.lineDash); context.setLineDash(renderOptions.lineDash);
context.lineDashOffset = renderOptions.lineDashOffset;
} }
context.lineCap = renderOptions.lineCap; context.lineCap = renderOptions.lineCap;
context.lineJoin = renderOptions.lineJoin; context.lineJoin = renderOptions.lineJoin;
@@ -538,7 +533,6 @@ ol.style.RegularShape.prototype.drawHitDetectionCanvas_ = function(renderOptions
context.lineWidth = renderOptions.strokeWidth; context.lineWidth = renderOptions.strokeWidth;
if (renderOptions.lineDash) { if (renderOptions.lineDash) {
context.setLineDash(renderOptions.lineDash); context.setLineDash(renderOptions.lineDash);
context.lineDashOffset = renderOptions.lineDashOffset;
} }
context.stroke(); context.stroke();
} }

View File

@@ -50,12 +50,6 @@ ol.style.Style = function(opt_options) {
*/ */
this.image_ = options.image !== undefined ? options.image : null; this.image_ = options.image !== undefined ? options.image : null;
/**
* @private
* @type {ol.StyleRenderFunction|null}
*/
this.renderer_ = options.renderer !== undefined ? options.renderer : null;
/** /**
* @private * @private
* @type {ol.style.Stroke} * @type {ol.style.Stroke}
@@ -98,28 +92,6 @@ ol.style.Style.prototype.clone = function() {
}; };
/**
* Get the custom renderer function that was configured with
* {@link #setRenderer} or the `renderer` constructor option.
* @return {ol.StyleRenderFunction|null} Custom renderer function.
* @api
*/
ol.style.Style.prototype.getRenderer = function() {
return this.renderer_;
};
/**
* Sets a custom renderer function for this style. When set, `fill`, `stroke`
* and `image` options of the style will be ignored.
* @param {ol.StyleRenderFunction|null} renderer Custom renderer function.
* @api
*/
ol.style.Style.prototype.setRenderer = function(renderer) {
this.renderer_ = renderer;
};
/** /**
* Get the geometry to be rendered. * Get the geometry to be rendered.
* @return {string|ol.geom.Geometry|ol.StyleGeometryFunction} * @return {string|ol.geom.Geometry|ol.StyleGeometryFunction}

View File

@@ -79,7 +79,6 @@ ol.CanvasFunctionType;
/** /**
* @typedef {{lineCap: string, * @typedef {{lineCap: string,
* lineDash: Array.<number>, * lineDash: Array.<number>,
* lineDashOffset: number,
* lineJoin: string, * lineJoin: string,
* lineWidth: number, * lineWidth: number,
* miterLimit: number, * miterLimit: number,
@@ -626,17 +625,6 @@ ol.StyleFunction;
ol.StyleGeometryFunction; ol.StyleGeometryFunction;
/**
* Custom renderer function. Takes two arguments:
*
* 1. The pixel coordinates of the geometry in GeoJSON notation.
* 2. The {@link olx.render.State} of the layer renderer.
*
* @typedef {function((ol.Coordinate|Array<ol.Coordinate>|Array.<Array.<ol.Coordinate>>),olx.render.State)}
*/
ol.StyleRenderFunction;
/** /**
* @typedef {{opacity: number, * @typedef {{opacity: number,
* rotateWithView: boolean, * rotateWithView: boolean,

View File

@@ -276,7 +276,7 @@ ol.VectorImageTile.prototype.finishLoading_ = function() {
*/ */
ol.VectorImageTile.defaultLoadFunction = function(tile, url) { ol.VectorImageTile.defaultLoadFunction = function(tile, url) {
var loader = ol.featureloader.loadFeaturesXhr( var loader = ol.featureloader.loadFeaturesXhr(
url, tile.getFormat(), tile.onLoad.bind(tile), tile.onError.bind(tile)); url, tile.getFormat(), tile.onLoad_.bind(tile), tile.onError_.bind(tile));
tile.setLoader(loader); tile.setLoader(loader);
}; };

View File

@@ -23,12 +23,6 @@ ol.VectorTile = function(tileCoord, state, src, format, tileLoadFunction) {
*/ */
this.consumers = 0; this.consumers = 0;
/**
* @private
* @type {ol.Extent}
*/
this.extent_ = null;
/** /**
* @private * @private
* @type {ol.format.Feature} * @type {ol.format.Feature}
@@ -88,15 +82,6 @@ ol.VectorTile.prototype.disposeInternal = function() {
}; };
/**
* Gets the extent of the vector tile.
* @return {ol.Extent} The extent.
*/
ol.VectorTile.prototype.getExtent = function() {
return this.extent_ || ol.VectorTile.DEFAULT_EXTENT;
};
/** /**
* Get the feature format assigned for reading this tile's features. * Get the feature format assigned for reading this tile's features.
* @return {ol.format.Feature} Feature format. * @return {ol.format.Feature} Feature format.
@@ -109,7 +94,7 @@ ol.VectorTile.prototype.getFormat = function() {
/** /**
* Get the features for this tile. Geometries will be in the projection returned * Get the features for this tile. Geometries will be in the projection returned
* by {@link ol.VectorTile#getProjection}. * by {@link #getProjection}.
* @return {Array.<ol.Feature|ol.render.Feature>} Features. * @return {Array.<ol.Feature|ol.render.Feature>} Features.
* @api * @api
*/ */
@@ -127,8 +112,7 @@ ol.VectorTile.prototype.getKey = function() {
/** /**
* Get the feature projection of features returned by * Get the feature projection of features returned by {@link #getFeatures}.
* {@link ol.VectorTile#getFeatures}.
* @return {ol.proj.Projection} Feature projection. * @return {ol.proj.Projection} Feature projection.
* @api * @api
*/ */
@@ -163,43 +147,22 @@ ol.VectorTile.prototype.load = function() {
* Handler for successful tile load. * Handler for successful tile load.
* @param {Array.<ol.Feature>} features The loaded features. * @param {Array.<ol.Feature>} features The loaded features.
* @param {ol.proj.Projection} dataProjection Data projection. * @param {ol.proj.Projection} dataProjection Data projection.
* @param {ol.Extent} extent Extent.
*/ */
ol.VectorTile.prototype.onLoad = function(features, dataProjection, extent) { ol.VectorTile.prototype.onLoad_ = function(features, dataProjection) {
this.setProjection(dataProjection); this.setProjection(dataProjection);
this.setFeatures(features); this.setFeatures(features);
this.setExtent(extent);
}; };
/** /**
* Handler for tile load errors. * Handler for tile load errors.
*/ */
ol.VectorTile.prototype.onError = function() { ol.VectorTile.prototype.onError_ = function() {
this.setState(ol.TileState.ERROR); this.setState(ol.TileState.ERROR);
}; };
/** /**
* Function for use in an {@link ol.source.VectorTile}'s `tileLoadFunction`.
* Sets the extent of the vector tile. This is only required for tiles in
* projections with `tile-pixels` as units. The extent should be set to
* `[0, 0, tilePixelSize, tilePixelSize]`, where `tilePixelSize` is calculated
* by multiplying the tile size with the tile pixel ratio. For sources using
* {@link ol.format.MVT} as feature format, the
* {@link ol.format.MVT#getLastExtent} method will return the correct extent.
* The default is `[0, 0, 4096, 4096]`.
* @param {ol.Extent} extent The extent.
* @api
*/
ol.VectorTile.prototype.setExtent = function(extent) {
this.extent_ = extent;
};
/**
* Function for use in an {@link ol.source.VectorTile}'s `tileLoadFunction`.
* Sets the features for the tile.
* @param {Array.<ol.Feature>} features Features. * @param {Array.<ol.Feature>} features Features.
* @api * @api
*/ */
@@ -210,9 +173,7 @@ ol.VectorTile.prototype.setFeatures = function(features) {
/** /**
* Function for use in an {@link ol.source.VectorTile}'s `tileLoadFunction`. * Set the projection of the features that were added with {@link #setFeatures}.
* Sets the projection of the features that were added with
* {@link ol.VectorTile#setFeatures}.
* @param {ol.proj.Projection} projection Feature projection. * @param {ol.proj.Projection} projection Feature projection.
* @api * @api
*/ */
@@ -239,10 +200,3 @@ ol.VectorTile.prototype.setReplayGroup = function(layer, key, replayGroup) {
ol.VectorTile.prototype.setLoader = function(loader) { ol.VectorTile.prototype.setLoader = function(loader) {
this.loader_ = loader; this.loader_ = loader;
}; };
/**
* @const
* @type {ol.Extent}
*/
ol.VectorTile.DEFAULT_EXTENT = [0, 0, 4096, 4096];

View File

@@ -302,14 +302,7 @@ ol.View.prototype.animate = function(var_args) {
} }
animation.callback = callback; animation.callback = callback;
start += animation.duration;
// check if animation is a no-op
if (ol.View.isNoopAnimation(animation)) {
animation.complete = true;
// we still push it onto the series for callback handling
} else {
start += animation.duration;
}
series.push(animation); series.push(animation);
} }
this.animations_.push(series); this.animations_.push(series);
@@ -1165,24 +1158,3 @@ ol.View.createRotationConstraint_ = function(options) {
return ol.RotationConstraint.disable; return ol.RotationConstraint.disable;
} }
}; };
/**
* Determine if an animation involves no view change.
* @param {ol.ViewAnimation} animation The animation.
* @return {boolean} The animation involves no view change.
*/
ol.View.isNoopAnimation = function(animation) {
if (animation.sourceCenter && animation.targetCenter) {
if (!ol.coordinate.equals(animation.sourceCenter, animation.targetCenter)) {
return false;
}
}
if (animation.sourceResolution !== animation.targetResolution) {
return false;
}
if (animation.sourceRotation !== animation.targetRotation) {
return false;
}
return true;
};

View File

@@ -10,7 +10,7 @@ var markupRegEx = /([^\/^\.]*)\.html$/;
var cleanupJSRegEx = /.*(\/\/ NOCOMPILE|goog\.require\(.*\);)[\r\n]*/g; var cleanupJSRegEx = /.*(\/\/ NOCOMPILE|goog\.require\(.*\);)[\r\n]*/g;
var requiresRegEx = /.*goog\.require\('(ol\.\S*)'\);/g; var requiresRegEx = /.*goog\.require\('(ol\.\S*)'\);/g;
var isCssRegEx = /\.css$/; var isCssRegEx = /\.css$/;
var isJsRegEx = /\.js(\?.*)?$/; var isJsRegEx = /\.js$/;
var srcDir = path.join(__dirname, '..', 'examples'); var srcDir = path.join(__dirname, '..', 'examples');
var destDir = path.join(__dirname, '..', 'build', 'examples'); var destDir = path.join(__dirname, '..', 'build', 'examples');

View File

@@ -98,7 +98,7 @@ main() {
npm install npm install
build_js ${PROFILES} build_js ${PROFILES}
build_css build_css
npm publish npm publish --tag beta
} }
if test ${#} -ne 1; then if test ${#} -ne 1; then

View File

@@ -262,44 +262,6 @@ describe('ol.control.ScaleLine', function() {
}); });
}); });
describe('latitude may affect scale line in EPSG:4326', function() {
it('is rendered differently at different latitudes for metric', function() {
var ctrl = new ol.control.ScaleLine();
ctrl.setMap(map);
map.setView(new ol.View({
center: ol.proj.fromLonLat([7, 0]),
zoom: 2,
projection: 'EPSG:4326'
}));
map.renderSync();
var innerHtml0 = ctrl.element_.innerHTML;
map.getView().setCenter([7, 52]);
map.renderSync();
var innerHtml52 = ctrl.element_.innerHTML;
expect(innerHtml0).to.not.be(innerHtml52);
});
it('is rendered the same at different latitudes for degrees', function() {
var ctrl = new ol.control.ScaleLine({
units: 'degrees'
});
ctrl.setMap(map);
map.setView(new ol.View({
center: ol.proj.fromLonLat([7, 0]),
zoom: 2,
projection: 'EPSG:4326'
}));
map.renderSync();
var innerHtml0 = ctrl.element_.innerHTML;
map.getView().setCenter([7, 52]);
map.renderSync();
var innerHtml52 = ctrl.element_.innerHTML;
expect(innerHtml0).to.be(innerHtml52);
});
});
describe('zoom affects the scaleline', function() { describe('zoom affects the scaleline', function() {
var currentZoom; var currentZoom;
var ctrl; var ctrl;

View File

@@ -192,33 +192,6 @@ describe('ol.format.KML', function() {
expect(node).to.xmleql(ol.xml.parse(text)); expect(node).to.xmleql(ol.xml.parse(text));
}); });
it('can write properties', function() {
var lineString = new ol.geom.LineString([[1, 2], [3, 4]]);
lineString.set('extrude', false);
lineString.set('tessellate', true);
lineString.set('altitudeMode', 'clampToGround');
lineString.set('unsupportedProperty', 'foo');
var features = [new ol.Feature(lineString)];
var node = format.writeFeaturesNode(features);
var text =
'<kml xmlns="http://www.opengis.net/kml/2.2"' +
' xmlns:gx="http://www.google.com/kml/ext/2.2"' +
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
' xsi:schemaLocation="http://www.opengis.net/kml/2.2' +
' https://developers.google.com/kml/schema/kml22gx.xsd">' +
' <Placemark>' +
' <LineString>' +
' <extrude>0</extrude>' +
' <tessellate>1</tessellate>' +
' <altitudeMode>clampToGround</altitudeMode>' +
' <coordinates>1,2 3,4</coordinates>' +
' </LineString>' +
' </Placemark>' +
'</kml>';
expect(node).to.xmleql(ol.xml.parse(text));
});
it('can read Point geometries', function() { it('can read Point geometries', function() {
var text = var text =
'<kml xmlns="http://www.opengis.net/kml/2.2"' + '<kml xmlns="http://www.opengis.net/kml/2.2"' +
@@ -439,7 +412,6 @@ describe('ol.format.KML', function() {
' <LineString>' + ' <LineString>' +
' <coordinates>1,2,3 4,5,6</coordinates>' + ' <coordinates>1,2,3 4,5,6</coordinates>' +
' <extrude>0</extrude>' + ' <extrude>0</extrude>' +
' <tessellate>1</tessellate>' +
' <altitudeMode>absolute</altitudeMode>' + ' <altitudeMode>absolute</altitudeMode>' +
' </LineString>' + ' </LineString>' +
' </Placemark>' + ' </Placemark>' +
@@ -452,7 +424,6 @@ describe('ol.format.KML', function() {
expect(g).to.be.an(ol.geom.LineString); expect(g).to.be.an(ol.geom.LineString);
expect(g.getCoordinates()).to.eql([[1, 2, 3], [4, 5, 6]]); expect(g.getCoordinates()).to.eql([[1, 2, 3], [4, 5, 6]]);
expect(g.get('extrude')).to.be(false); expect(g.get('extrude')).to.be(false);
expect(g.get('tessellate')).to.be(true);
expect(g.get('altitudeMode')).to.be('absolute'); expect(g.get('altitudeMode')).to.be('absolute');
}); });
@@ -993,7 +964,6 @@ describe('ol.format.KML', function() {
' <MultiGeometry>' + ' <MultiGeometry>' +
' <LineString>' + ' <LineString>' +
' <extrude>0</extrude>' + ' <extrude>0</extrude>' +
' <tessellate>0</tessellate>' +
' <altitudeMode>absolute</altitudeMode>' + ' <altitudeMode>absolute</altitudeMode>' +
' <coordinates>1,2,3 4,5,6</coordinates>' + ' <coordinates>1,2,3 4,5,6</coordinates>' +
' </LineString>' + ' </LineString>' +
@@ -1015,10 +985,6 @@ describe('ol.format.KML', function() {
expect(g.get('extrude')).to.have.length(2); expect(g.get('extrude')).to.have.length(2);
expect(g.get('extrude')[0]).to.be(false); expect(g.get('extrude')[0]).to.be(false);
expect(g.get('extrude')[1]).to.be(undefined); expect(g.get('extrude')[1]).to.be(undefined);
expect(g.get('tessellate')).to.be.an('array');
expect(g.get('tessellate')).to.have.length(2);
expect(g.get('tessellate')[0]).to.be(false);
expect(g.get('tessellate')[1]).to.be(undefined);
expect(g.get('altitudeMode')).to.be.an('array'); expect(g.get('altitudeMode')).to.be.an('array');
expect(g.get('altitudeMode')).to.have.length(2); expect(g.get('altitudeMode')).to.have.length(2);
expect(g.get('altitudeMode')[0]).to.be('absolute'); expect(g.get('altitudeMode')[0]).to.be('absolute');

View File

@@ -88,13 +88,6 @@ where('ArrayBuffer.isView').describe('ol.format.MVT', function() {
expect(features[0].getId()).to.be(2); expect(features[0].getId()).to.be(2);
}); });
it('sets the extent of the last readFeatures call', function() {
var format = new ol.format.MVT();
format.readFeatures(data);
var extent = format.getLastExtent();
expect(extent.getWidth()).to.be(4096);
});
}); });
}); });

View File

@@ -6,7 +6,7 @@ goog.require('ol.events.Event');
goog.require('ol.events.EventTarget'); goog.require('ol.events.EventTarget');
goog.require('ol.format.GeoJSON'); goog.require('ol.format.GeoJSON');
goog.require('ol.interaction.DragAndDrop'); goog.require('ol.interaction.DragAndDrop');
goog.require('ol.source.Vector');
where('FileReader').describe('ol.interaction.DragAndDrop', function() { where('FileReader').describe('ol.interaction.DragAndDrop', function() {
var viewport, map, interaction; var viewport, map, interaction;
@@ -37,14 +37,6 @@ where('FileReader').describe('ol.interaction.DragAndDrop', function() {
expect(interaction.formatConstructors_).to.have.length(1); expect(interaction.formatConstructors_).to.have.length(1);
}); });
it('accepts a source option', function() {
var source = new ol.source.Vector();
var drop = new ol.interaction.DragAndDrop({
formatConstructors: [ol.format.GeoJSON],
source: source
});
expect(drop.source_).to.equal(source);
});
}); });
describe('#setActive()', function() { describe('#setActive()', function() {
@@ -136,41 +128,6 @@ where('FileReader').describe('ol.interaction.DragAndDrop', function() {
expect(event.dataTransfer.dropEffect).to.be('copy'); expect(event.dataTransfer.dropEffect).to.be('copy');
expect(event.propagationStopped).to.be(true); expect(event.propagationStopped).to.be(true);
}); });
it('adds dropped features to a source', function(done) {
var source = new ol.source.Vector();
var drop = new ol.interaction.DragAndDrop({
formatConstructors: [ol.format.GeoJSON],
source: source
});
drop.setMap(map);
drop.on('addfeatures', function(evt) {
var features = source.getFeatures();
expect(features.length).to.be(1);
done();
});
var event = new ol.events.Event();
event.dataTransfer = {};
event.type = 'dragenter';
viewport.dispatchEvent(event);
event.type = 'dragover';
viewport.dispatchEvent(event);
event.type = 'drop';
event.dataTransfer.files = {
length: 1,
item: function() {
return JSON.stringify({
type: 'FeatureCollection',
features: [{type: 'Feature', id: '1'}]
});
}
};
viewport.dispatchEvent(event);
expect(event.dataTransfer.dropEffect).to.be('copy');
expect(event.propagationStopped).to.be(true);
});
}); });
}); });

View File

@@ -72,19 +72,6 @@ describe('ol.interaction.Extent', function() {
event.pointerEvent.pointerId = 1; event.pointerEvent.pointerId = 1;
map.handleMapBrowserEvent(event); map.handleMapBrowserEvent(event);
} }
describe('Constructor', function() {
it('can be configured with an extent', function() {
expect(function() {
new ol.interaction.Extent({
extent: [-10, -10, 10, 10]
});
}).to.not.throwException();
});
});
describe('snap to vertex', function() { describe('snap to vertex', function() {
it('snap to vertex works', function() { it('snap to vertex works', function() {
interaction.setExtent([-50, -50, 50, 50]); interaction.setExtent([-50, -50, 50, 50]);

View File

@@ -74,20 +74,19 @@ describe('ol.interaction.Modify', function() {
* @param {string} type Event type. * @param {string} type Event type.
* @param {number} x Horizontal offset from map center. * @param {number} x Horizontal offset from map center.
* @param {number} y Vertical offset from map center. * @param {number} y Vertical offset from map center.
* @param {Object} modifiers Lookup of modifier keys. * @param {boolean=} opt_shiftKey Shift key is pressed.
* @param {number} button The mouse button. * @param {number} button The mouse button.
*/ */
function simulateEvent(type, x, y, modifiers, button) { function simulateEvent(type, x, y, opt_shiftKey, button) {
modifiers = modifiers || {};
var viewport = map.getViewport(); var viewport = map.getViewport();
// calculated in case body has top < 0 (test runner with small window) // calculated in case body has top < 0 (test runner with small window)
var position = viewport.getBoundingClientRect(); var position = viewport.getBoundingClientRect();
var shiftKey = opt_shiftKey !== undefined ? opt_shiftKey : false;
var pointerEvent = new ol.pointer.PointerEvent(type, { var pointerEvent = new ol.pointer.PointerEvent(type, {
type: type, type: type,
clientX: position.left + x + width / 2, clientX: position.left + x + width / 2,
clientY: position.top + y + height / 2, clientY: position.top + y + height / 2,
shiftKey: modifiers.shift || false, shiftKey: shiftKey
altKey: modifiers.alt || false
}, { }, {
button: button, button: button,
isPrimary: true isPrimary: true
@@ -178,16 +177,6 @@ describe('ol.interaction.Modify', function() {
expect(rbushEntries[0].feature).to.be(feature); expect(rbushEntries[0].feature).to.be(feature);
}); });
it('accepts a source', function() {
var feature = new ol.Feature(
new ol.geom.Point([0, 0]));
var source = new ol.source.Vector({features: [feature]});
var modify = new ol.interaction.Modify({source: source});
var rbushEntries = modify.rBush_.getAll();
expect(rbushEntries.length).to.be(1);
expect(rbushEntries[0].feature).to.be(feature);
});
}); });
describe('vertex deletion', function() { describe('vertex deletion', function() {
@@ -212,10 +201,10 @@ describe('ol.interaction.Modify', function() {
expect(second.getGeometry().getRevision()).to.equal(secondRevision); expect(second.getGeometry().getRevision()).to.equal(secondRevision);
expect(second.getGeometry().getCoordinates()[0]).to.have.length(5); expect(second.getGeometry().getCoordinates()[0]).to.have.length(5);
simulateEvent('pointerdown', 10, -20, {alt: true}, 0); simulateEvent('pointerdown', 10, -20, false, 0);
simulateEvent('pointerup', 10, -20, {alt: true}, 0); simulateEvent('pointerup', 10, -20, false, 0);
simulateEvent('click', 10, -20, {alt: true}, 0); simulateEvent('click', 10, -20, false, 0);
simulateEvent('singleclick', 10, -20, {alt: true}, 0); simulateEvent('singleclick', 10, -20, false, 0);
expect(first.getGeometry().getRevision()).to.equal(firstRevision + 1); expect(first.getGeometry().getRevision()).to.equal(firstRevision + 1);
expect(first.getGeometry().getCoordinates()[0]).to.have.length(4); expect(first.getGeometry().getCoordinates()[0]).to.have.length(4);
@@ -248,10 +237,10 @@ describe('ol.interaction.Modify', function() {
expect(first.getGeometry().getRevision()).to.equal(firstRevision); expect(first.getGeometry().getRevision()).to.equal(firstRevision);
expect(first.getGeometry().getCoordinates()).to.have.length(5); expect(first.getGeometry().getCoordinates()).to.have.length(5);
simulateEvent('pointerdown', 0, 0, {alt: true}, 0); simulateEvent('pointerdown', 0, 0, false, 0);
simulateEvent('pointerup', 0, 0, {alt: true}, 0); simulateEvent('pointerup', 0, 0, false, 0);
simulateEvent('click', 0, 0, {alt: true}, 0); simulateEvent('click', 0, 0, false, 0);
simulateEvent('singleclick', 0, 0, {alt: true}, 0); simulateEvent('singleclick', 0, 0, false, 0);
expect(first.getGeometry().getRevision()).to.equal(firstRevision + 1); expect(first.getGeometry().getRevision()).to.equal(firstRevision + 1);
expect(first.getGeometry().getCoordinates()).to.have.length(4); expect(first.getGeometry().getCoordinates()).to.have.length(4);
@@ -284,10 +273,10 @@ describe('ol.interaction.Modify', function() {
expect(first.getGeometry().getRevision()).to.equal(firstRevision); expect(first.getGeometry().getRevision()).to.equal(firstRevision);
expect(first.getGeometry().getCoordinates()).to.have.length(5); expect(first.getGeometry().getCoordinates()).to.have.length(5);
simulateEvent('pointerdown', 40, 0, {alt: true}, 0); simulateEvent('pointerdown', 40, 0, false, 0);
simulateEvent('pointerup', 40, 0, {alt: true}, 0); simulateEvent('pointerup', 40, 0, false, 0);
simulateEvent('click', 40, 0, {alt: true}, 0); simulateEvent('click', 40, 0, false, 0);
simulateEvent('singleclick', 40, 0, {alt: true}, 0); simulateEvent('singleclick', 40, 0, false, 0);
expect(first.getGeometry().getRevision()).to.equal(firstRevision + 1); expect(first.getGeometry().getRevision()).to.equal(firstRevision + 1);
expect(first.getGeometry().getCoordinates()).to.have.length(4); expect(first.getGeometry().getCoordinates()).to.have.length(4);
@@ -320,8 +309,8 @@ describe('ol.interaction.Modify', function() {
expect(first.getGeometry().getRevision()).to.equal(firstRevision); expect(first.getGeometry().getRevision()).to.equal(firstRevision);
expect(first.getGeometry().getCoordinates()).to.have.length(5); expect(first.getGeometry().getCoordinates()).to.have.length(5);
simulateEvent('pointerdown', 40, 0, null, 0); simulateEvent('pointerdown', 40, 0, false, 0);
simulateEvent('pointerup', 40, 0, null, 0); simulateEvent('pointerup', 40, 0, false, 0);
var removed = modify.removePoint(); var removed = modify.removePoint();
@@ -354,25 +343,25 @@ describe('ol.interaction.Modify', function() {
map.addInteraction(modify); map.addInteraction(modify);
// Move first vertex // Move first vertex
simulateEvent('pointermove', 0, 0, null, 0); simulateEvent('pointermove', 0, 0, false, 0);
simulateEvent('pointerdown', 0, 0, null, 0); simulateEvent('pointerdown', 0, 0, false, 0);
simulateEvent('pointermove', -10, -10, null, 0); simulateEvent('pointermove', -10, -10, false, 0);
simulateEvent('pointerdrag', -10, -10, null, 0); simulateEvent('pointerdrag', -10, -10, false, 0);
simulateEvent('pointerup', -10, -10, null, 0); simulateEvent('pointerup', -10, -10, false, 0);
// Move middle vertex // Move middle vertex
simulateEvent('pointermove', 0, -40, null, 0); simulateEvent('pointermove', 0, -40, false, 0);
simulateEvent('pointerdown', 0, -40, null, 0); simulateEvent('pointerdown', 0, -40, false, 0);
simulateEvent('pointermove', 10, -30, null, 0); simulateEvent('pointermove', 10, -30, false, 0);
simulateEvent('pointerdrag', 10, -30, null, 0); simulateEvent('pointerdrag', 10, -30, false, 0);
simulateEvent('pointerup', 10, -30, null, 0); simulateEvent('pointerup', 10, -30, false, 0);
// Move last vertex // Move last vertex
simulateEvent('pointermove', 40, 0, null, 0); simulateEvent('pointermove', 40, 0, false, 0);
simulateEvent('pointerdown', 40, 0, null, 0); simulateEvent('pointerdown', 40, 0, false, 0);
simulateEvent('pointermove', 50, -10, null, 0); simulateEvent('pointermove', 50, -10, false, 0);
simulateEvent('pointerdrag', 50, -10, null, 0); simulateEvent('pointerdrag', 50, -10, false, 0);
simulateEvent('pointerup', 50, -10, null, 0); simulateEvent('pointerup', 50, -10, false, 0);
expect(lineFeature.getGeometry().getCoordinates()[0][2]).to.equal(10); expect(lineFeature.getGeometry().getCoordinates()[0][2]).to.equal(10);
expect(lineFeature.getGeometry().getCoordinates()[2][2]).to.equal(30); expect(lineFeature.getGeometry().getCoordinates()[2][2]).to.equal(30);
@@ -393,21 +382,21 @@ describe('ol.interaction.Modify', function() {
map.addInteraction(modify); map.addInteraction(modify);
// Change center // Change center
simulateEvent('pointermove', 10, -10, null, 0); simulateEvent('pointermove', 10, -10, false, 0);
simulateEvent('pointerdown', 10, -10, null, 0); simulateEvent('pointerdown', 10, -10, false, 0);
simulateEvent('pointermove', 5, -5, null, 0); simulateEvent('pointermove', 5, -5, false, 0);
simulateEvent('pointerdrag', 5, -5, null, 0); simulateEvent('pointerdrag', 5, -5, false, 0);
simulateEvent('pointerup', 5, -5, null, 0); simulateEvent('pointerup', 5, -5, false, 0);
expect(circleFeature.getGeometry().getRadius()).to.equal(20); expect(circleFeature.getGeometry().getRadius()).to.equal(20);
expect(circleFeature.getGeometry().getCenter()).to.eql([5, 5]); expect(circleFeature.getGeometry().getCenter()).to.eql([5, 5]);
// Increase radius // Increase radius
simulateEvent('pointermove', 25, -4, null, 0); simulateEvent('pointermove', 25, -4, false, 0);
simulateEvent('pointerdown', 25, -4, null, 0); simulateEvent('pointerdown', 25, -4, false, 0);
simulateEvent('pointermove', 30, -5, null, 0); simulateEvent('pointermove', 30, -5, false, 0);
simulateEvent('pointerdrag', 30, -5, null, 0); simulateEvent('pointerdrag', 30, -5, false, 0);
simulateEvent('pointerup', 30, -5, null, 0); simulateEvent('pointerup', 30, -5, false, 0);
expect(circleFeature.getGeometry().getRadius()).to.equal(25); expect(circleFeature.getGeometry().getRadius()).to.equal(25);
expect(circleFeature.getGeometry().getCenter()).to.eql([5, 5]); expect(circleFeature.getGeometry().getCenter()).to.eql([5, 5]);
@@ -432,10 +421,10 @@ describe('ol.interaction.Modify', function() {
expect(feature.getGeometry().getRevision()).to.equal(1); expect(feature.getGeometry().getRevision()).to.equal(1);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
simulateEvent('pointerdown', 10, -20, {alt: true}, 0); simulateEvent('pointerdown', 10, -20, false, 0);
simulateEvent('pointerup', 10, -20, {alt: true}, 0); simulateEvent('pointerup', 10, -20, false, 0);
simulateEvent('click', 10, -20, {alt: true}, 0); simulateEvent('click', 10, -20, false, 0);
simulateEvent('singleclick', 10, -20, {alt: true}, 0); simulateEvent('singleclick', 10, -20, false, 0);
expect(feature.getGeometry().getRevision()).to.equal(2); expect(feature.getGeometry().getRevision()).to.equal(2);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(4); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(4);
@@ -447,10 +436,10 @@ describe('ol.interaction.Modify', function() {
expect(feature.getGeometry().getRevision()).to.equal(1); expect(feature.getGeometry().getRevision()).to.equal(1);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
simulateEvent('pointerdown', 40, -20, null, 0); simulateEvent('pointerdown', 40, -20, false, 0);
simulateEvent('pointerup', 40, -20, null, 0); simulateEvent('pointerup', 40, -20, false, 0);
simulateEvent('click', 40, -20, null, 0); simulateEvent('click', 40, -20, false, 0);
simulateEvent('singleclick', 40, -20, null, 0); simulateEvent('singleclick', 40, -20, false, 0);
expect(feature.getGeometry().getRevision()).to.equal(2); expect(feature.getGeometry().getRevision()).to.equal(2);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(6); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(6);
@@ -462,10 +451,10 @@ describe('ol.interaction.Modify', function() {
expect(feature.getGeometry().getRevision()).to.equal(1); expect(feature.getGeometry().getRevision()).to.equal(1);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
simulateEvent('pointerdown', 40, -20, null, 0); simulateEvent('pointerdown', 40, -20, false, 0);
simulateEvent('pointerup', 40, -20, null, 0); simulateEvent('pointerup', 40, -20, false, 0);
simulateEvent('click', 40, -20, null, 0); simulateEvent('click', 40, -20, false, 0);
simulateEvent('singleclick', 40, -20, null, 0); simulateEvent('singleclick', 40, -20, false, 0);
expect(feature.getGeometry().getRevision()).to.equal(2); expect(feature.getGeometry().getRevision()).to.equal(2);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(6); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(6);
@@ -473,10 +462,10 @@ describe('ol.interaction.Modify', function() {
validateEvents(events, [feature]); validateEvents(events, [feature]);
events.length = 0; events.length = 0;
simulateEvent('pointerdown', 40, -20, {alt: true}, 0); simulateEvent('pointerdown', 40, -20, false, 0);
simulateEvent('pointerup', 40, -20, {alt: true}, 0); simulateEvent('pointerup', 40, -20, false, 0);
simulateEvent('click', 40, -20, {alt: true}, 0); simulateEvent('click', 40, -20, false, 0);
simulateEvent('singleclick', 40, -20, {alt: true}, 0); simulateEvent('singleclick', 40, -20, false, 0);
expect(feature.getGeometry().getRevision()).to.equal(3); expect(feature.getGeometry().getRevision()).to.equal(3);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
@@ -488,11 +477,11 @@ describe('ol.interaction.Modify', function() {
expect(feature.getGeometry().getRevision()).to.equal(1); expect(feature.getGeometry().getRevision()).to.equal(1);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
simulateEvent('pointermove', 40, -20, null, 0); simulateEvent('pointermove', 40, -20, false, 0);
simulateEvent('pointerdown', 40, -20, null, 0); simulateEvent('pointerdown', 40, -20, false, 0);
simulateEvent('pointermove', 30, -20, null, 0); simulateEvent('pointermove', 30, -20, false, 0);
simulateEvent('pointerdrag', 30, -20, null, 0); simulateEvent('pointerdrag', 30, -20, false, 0);
simulateEvent('pointerup', 30, -20, null, 0); simulateEvent('pointerup', 30, -20, false, 0);
expect(feature.getGeometry().getRevision()).to.equal(4); expect(feature.getGeometry().getRevision()).to.equal(4);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(6); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(6);
@@ -504,12 +493,12 @@ describe('ol.interaction.Modify', function() {
expect(feature.getGeometry().getRevision()).to.equal(1); expect(feature.getGeometry().getRevision()).to.equal(1);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
simulateEvent('pointermove', 40, -20, null, 0); simulateEvent('pointermove', 40, -20, false, 0);
// right click // right click
simulateEvent('pointerdown', 40, -20, null, 1); simulateEvent('pointerdown', 40, -20, false, 1);
simulateEvent('pointermove', 30, -20, null, 1); simulateEvent('pointermove', 30, -20, false, 1);
simulateEvent('pointerdrag', 30, -20, null, 1); simulateEvent('pointerdrag', 30, -20, false, 1);
simulateEvent('pointerup', 30, -20, null, 1); simulateEvent('pointerup', 30, -20, false, 1);
expect(feature.getGeometry().getRevision()).to.equal(1); expect(feature.getGeometry().getRevision()).to.equal(1);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
@@ -539,13 +528,13 @@ describe('ol.interaction.Modify', function() {
expect(feature.getGeometry().getRevision()).to.equal(1); expect(feature.getGeometry().getRevision()).to.equal(1);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
simulateEvent('pointerdown', 10, -20, null, 0); simulateEvent('pointerdown', 10, -20, false, 0);
simulateEvent('pointerup', 10, -20, null, 0); simulateEvent('pointerup', 10, -20, false, 0);
simulateEvent('click', 10, -20, null, 0); simulateEvent('click', 10, -20, false, 0);
simulateEvent('pointerdown', 10, -20, null, 0); simulateEvent('pointerdown', 10, -20, false, 0);
simulateEvent('pointerup', 10, -20, null, 0); simulateEvent('pointerup', 10, -20, false, 0);
simulateEvent('click', 10, -20, null, 0); simulateEvent('click', 10, -20, false, 0);
simulateEvent('dblclick', 10, -20, null, 0); simulateEvent('dblclick', 10, -20, false, 0);
expect(feature.getGeometry().getRevision()).to.equal(2); expect(feature.getGeometry().getRevision()).to.equal(2);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(4); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(4);
@@ -558,10 +547,10 @@ describe('ol.interaction.Modify', function() {
expect(feature.getGeometry().getRevision()).to.equal(1); expect(feature.getGeometry().getRevision()).to.equal(1);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
simulateEvent('pointerdown', 10, -20, null, 0); simulateEvent('pointerdown', 10, -20, false, 0);
simulateEvent('pointerup', 10, -20, null, 0); simulateEvent('pointerup', 10, -20, false, 0);
simulateEvent('click', 10, -20, null, 0); simulateEvent('click', 10, -20, false, 0);
simulateEvent('singleclick', 10, -20, null, 0); simulateEvent('singleclick', 10, -20, false, 0);
expect(feature.getGeometry().getRevision()).to.equal(1); expect(feature.getGeometry().getRevision()).to.equal(1);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
@@ -584,20 +573,20 @@ describe('ol.interaction.Modify', function() {
var feature = features[0]; var feature = features[0];
// move first vertex // move first vertex
simulateEvent('pointermove', 0, 0, null, 0); simulateEvent('pointermove', 0, 0, false, 0);
simulateEvent('pointerdown', 0, 0, null, 0); simulateEvent('pointerdown', 0, 0, false, 0);
simulateEvent('pointermove', -10, -10, null, 0); simulateEvent('pointermove', -10, -10, false, 0);
simulateEvent('pointerdrag', -10, -10, null, 0); simulateEvent('pointerdrag', -10, -10, false, 0);
simulateEvent('pointerup', -10, -10, null, 0); simulateEvent('pointerup', -10, -10, false, 0);
expect(listenerSpy.callCount).to.be(0); expect(listenerSpy.callCount).to.be(0);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
// try to add vertex // try to add vertex
simulateEvent('pointerdown', 40, -20, null, 0); simulateEvent('pointerdown', 40, -20, false, 0);
simulateEvent('pointerup', 40, -20, null, 0); simulateEvent('pointerup', 40, -20, false, 0);
simulateEvent('click', 40, -20, null, 0); simulateEvent('click', 40, -20, false, 0);
simulateEvent('singleclick', 40, -20, null, 0); simulateEvent('singleclick', 40, -20, false, 0);
expect(listenerSpy.callCount).to.be(1); expect(listenerSpy.callCount).to.be(1);
expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5); expect(feature.getGeometry().getCoordinates()[0]).to.have.length(5);
@@ -704,7 +693,7 @@ describe('ol.interaction.Modify', function() {
map.addInteraction(modify); map.addInteraction(modify);
expect(modify.vertexFeature_).to.be(null); expect(modify.vertexFeature_).to.be(null);
simulateEvent('pointermove', 10, -20, null, 0); simulateEvent('pointermove', 10, -20, false, 0);
expect(modify.vertexFeature_).to.not.be(null); expect(modify.vertexFeature_).to.not.be(null);
modify.setActive(false); modify.setActive(false);

View File

@@ -183,57 +183,6 @@ describe('ol.Map', function() {
}); });
describe('#getFeaturesAtPixel', function() {
var target, map;
beforeEach(function() {
target = document.createElement('div');
target.style.width = target.style.height = '100px';
document.body.appendChild(target);
map = new ol.Map({
target: target,
layers: [new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature(new ol.geom.Point([0, 0]))]
})
})],
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
map.renderSync();
});
afterEach(function() {
document.body.removeChild(target);
});
it('returns null if no feature was found', function() {
var features = map.getFeaturesAtPixel([0, 0]);
expect(features).to.be(null);
});
it('returns an array of found features', function() {
var features = map.getFeaturesAtPixel([50, 50]);
expect(features).to.be.an(Array);
expect(features[0]).to.be.an(ol.Feature);
});
it('respects options', function() {
var otherLayer = new ol.layer.Vector({
source: new ol.source.Vector
});
map.addLayer(otherLayer);
var features = map.getFeaturesAtPixel([50, 50], {
layerFilter: function(layer) {
return layer == otherLayer;
}
});
expect(features).to.be(null);
});
});
describe('#forEachLayerAtPixel()', function() { describe('#forEachLayerAtPixel()', function() {
var target, map, original, log; var target, map, original, log;

View File

@@ -212,33 +212,6 @@ describe('ol.proj', function() {
}); });
describe('getPointResolution()', function() {
it('returns the correct point resolution for EPSG:4326', function() {
var pointResolution = ol.proj.getPointResolution('EPSG:4326', 1, [0, 0]);
expect (pointResolution).to.be(1);
pointResolution = ol.proj.getPointResolution('EPSG:4326', 1, [0, 52]);
expect (pointResolution).to.be(1);
});
it('returns the correct point resolution for EPSG:4326 with custom units', function() {
var pointResolution = ol.proj.getPointResolution('EPSG:4326', 1, [0, 0], 'm');
expect(pointResolution).to.roughlyEqual(111195.0802335329, 1e-5);
pointResolution = ol.proj.getPointResolution('EPSG:4326', 1, [0, 52], 'm');
expect(pointResolution).to.roughlyEqual(89826.53390979706, 1e-5);
});
it('returns the correct point resolution for EPSG:3857', function() {
var pointResolution = ol.proj.getPointResolution('EPSG:3857', 1, [0, 0]);
expect(pointResolution).to.be(1);
pointResolution = ol.proj.getPointResolution('EPSG:3857', 1, ol.proj.fromLonLat([0, 52]));
expect(pointResolution).to.roughlyEqual(0.615661, 1e-5);
});
it('returns the correct point resolution for EPSG:3857 with custom units', function() {
var pointResolution = ol.proj.getPointResolution('EPSG:3857', 1, [0, 0], 'degrees');
expect(pointResolution).to.be(1);
pointResolution = ol.proj.getPointResolution('EPSG:4326', 1, ol.proj.fromLonLat([0, 52]), 'degrees');
expect(pointResolution).to.be(1);
});
});
describe('Proj4js integration', function() { describe('Proj4js integration', function() {
var proj4 = window.proj4; var proj4 = window.proj4;

View File

@@ -154,8 +154,8 @@ describe('ol.render.webgl.TextReplay', function() {
expect(replay.originY).to.be(charInfo.offsetY); expect(replay.originY).to.be(charInfo.offsetY);
expect(replay.imageHeight).to.be(charInfo.image.height); expect(replay.imageHeight).to.be(charInfo.image.height);
expect(replay.imageWidth).to.be(charInfo.image.width); expect(replay.imageWidth).to.be(charInfo.image.width);
expect(replay.anchorX).to.be(-widthX - 10); expect(replay.anchorX).to.be(-widthX + 10);
expect(replay.anchorY).to.be(-10); expect(replay.anchorY).to.be(10);
}); });
it('does not draw if text is empty', function() { it('does not draw if text is empty', function() {

View File

@@ -205,67 +205,6 @@ describe('ol.render.canvas.ReplayGroup', function() {
expect(style2.getStroke().getLineDashOffset()).to.be(2); expect(style2.getStroke().getLineDashOffset()).to.be(2);
expect(lineDashOffset).to.be(4); expect(lineDashOffset).to.be(4);
}); });
it('calls the renderer function configured for the style', function() {
var calls = [];
var style = new ol.style.Style({
renderer: function(coords, state) {
calls.push({
coords: coords,
geometry: state.geometry,
feature: state.feature,
context: state.context,
pixelRatio: state.pixelRatio,
rotation: state.rotation,
resolution: state.resolution
});
}
});
var point = new ol.Feature(new ol.geom.Point([45, 90]));
var multipoint = new ol.Feature(new ol.geom.MultiPoint(
[[45, 90], [90, 45]]));
var linestring = new ol.Feature(new ol.geom.LineString(
[[45, 90], [45, 45], [90, 45]]));
var multilinestring = new ol.Feature(new ol.geom.MultiLineString(
[linestring.getGeometry().getCoordinates(), linestring.getGeometry().getCoordinates()]));
var polygon = feature1;
var multipolygon = new ol.Feature(new ol.geom.MultiPolygon(
[polygon.getGeometry().getCoordinates(), polygon.getGeometry().getCoordinates()]));
var geometrycollection = new ol.Feature(new ol.geom.GeometryCollection(
[point.getGeometry(), linestring.getGeometry(), polygon.getGeometry()]));
replay = new ol.render.canvas.ReplayGroup(1, [-180, -90, 180, 90], 1, true);
ol.renderer.vector.renderFeature(replay, point, style, 1);
ol.renderer.vector.renderFeature(replay, multipoint, style, 1);
ol.renderer.vector.renderFeature(replay, linestring, style, 1);
ol.renderer.vector.renderFeature(replay, multilinestring, style, 1);
ol.renderer.vector.renderFeature(replay, polygon, style, 1);
ol.renderer.vector.renderFeature(replay, multipolygon, style, 1);
ol.renderer.vector.renderFeature(replay, geometrycollection, style, 1);
ol.transform.scale(transform, 0.1, 0.1);
replay.replay(context, 1, transform, 0, {});
expect(calls.length).to.be(9);
expect(calls[0].geometry).to.be(point.getGeometry());
expect(calls[0].feature).to.be(point);
expect(calls[0].context).to.be(context);
expect(calls[0].pixelRatio).to.be(1);
expect(calls[0].rotation).to.be(0);
expect(calls[0].resolution).to.be(1);
expect(calls[0].coords).to.eql([4.5, 9]);
expect(calls[1].feature).to.be(multipoint);
expect(calls[1].coords[0]).to.eql([4.5, 9]);
expect(calls[2].feature).to.be(linestring);
expect(calls[2].coords[0]).to.eql([4.5, 9]);
expect(calls[3].feature).to.be(multilinestring);
expect(calls[3].coords[0][0]).to.eql([4.5, 9]);
expect(calls[4].feature).to.be(polygon);
expect(calls[4].coords[0][0]).to.eql([-9, -4.5]);
expect(calls[5].feature).to.be(multipolygon);
expect(calls[5].coords[0][0][0]).to.eql([-9, -4.5]);
expect(calls[6].feature).to.be(geometrycollection);
expect(calls[6].geometry.getCoordinates()).to.eql([45, 90]);
expect(calls[7].geometry.getCoordinates()[0]).to.eql([45, 90]);
expect(calls[8].geometry.getCoordinates()[0][0]).to.eql([-90, -45]);
});
}); });
}); });

View File

@@ -121,18 +121,6 @@ describe('ol.renderer.canvas.VectorTileLayer', function() {
spy2.restore(); spy2.restore();
}); });
it('renders replays with custom renderers as direct replays', function() {
layer.renderMode_ = 'image';
layer.setStyle(new ol.style.Style({
renderer: function() {}
}));
var spy = sinon.spy(ol.renderer.canvas.VectorTileLayer.prototype,
'getReplayTransform_');
map.renderSync();
expect(spy.callCount).to.be(1);
spy.restore();
});
it('gives precedence to feature styles over layer styles', function() { it('gives precedence to feature styles over layer styles', function() {
var spy = sinon.spy(map.getRenderer().getLayerRenderer(layer), var spy = sinon.spy(map.getRenderer().getLayerRenderer(layer),
'renderFeature'); 'renderFeature');
@@ -186,14 +174,6 @@ describe('ol.renderer.canvas.VectorTileLayer', function() {
spy2.restore(); spy2.restore();
}); });
it('uses the extent of the source tile', function() {
var renderer = map.getRenderer().getLayerRenderer(layer);
var tile = new ol.VectorTile([0, 0, 0], 2);
tile.setExtent([0, 0, 4096, 4096]);
var tilePixelRatio = renderer.getTilePixelRatio_(source, tile);
expect(tilePixelRatio).to.be(16);
});
}); });
describe('#prepareFrame', function() { describe('#prepareFrame', function() {
@@ -298,42 +278,6 @@ describe('ol.renderer.canvas.VectorTileLayer', function() {
expect(spy.callCount).to.be(1); expect(spy.callCount).to.be(1);
expect(spy.getCall(0).args[1]).to.equal(layer); expect(spy.getCall(0).args[1]).to.equal(layer);
}); });
it('does not give false positives when overzoomed', function(done) {
var target = document.createElement('div');
target.style.width = '100px';
target.style.height = '100px';
document.body.appendChild(target);
var extent = [1824704.739223726, 6141868.096770482, 1827150.7241288517, 6144314.081675608];
var source = new ol.source.VectorTile({
format: new ol.format.MVT(),
url: 'spec/ol/data/14-8938-5680.vector.pbf',
minZoom: 14,
maxZoom: 14
});
var map = new ol.Map({
target: target,
layers: [
new ol.layer.VectorTile({
extent: extent,
source: source
})
],
view: new ol.View({
center: ol.extent.getCenter(extent),
zoom: 19
})
});
source.on('tileloadend', function() {
setTimeout(function() {
var features = map.getFeaturesAtPixel([96, 96]);
document.body.removeChild(target);
map.dispose();
expect(features).to.be(null);
done();
}, 200);
});
});
}); });
}); });

View File

@@ -6,11 +6,13 @@ goog.require('ol.proj');
goog.require('ol.source.VectorTile'); goog.require('ol.source.VectorTile');
goog.require('ol.tilegrid'); goog.require('ol.tilegrid');
describe('ol.source.VectorTile', function() { describe('ol.source.VectorTile', function() {
var format = new ol.format.MVT(); var format = new ol.format.MVT();
var source = new ol.source.VectorTile({ var source = new ol.source.VectorTile({
format: format, format: format,
tileGrid: ol.tilegrid.createXYZ({tileSize: 512}),
tilePixelRatio: 8, tilePixelRatio: 8,
url: 'spec/ol/data/{z}-{x}-{y}.vector.pbf' url: 'spec/ol/data/{z}-{x}-{y}.vector.pbf'
}); });
@@ -20,16 +22,9 @@ describe('ol.source.VectorTile', function() {
it('sets the format on the instance', function() { it('sets the format on the instance', function() {
expect(source.format_).to.equal(format); expect(source.format_).to.equal(format);
}); });
it('uses ol.VectorTile as default tileClass', function() { it('uses ol.VectorTile as default tileClass', function() {
expect(source.tileClass).to.equal(ol.VectorTile); expect(source.tileClass).to.equal(ol.VectorTile);
}); });
it('creates a 512 XYZ tilegrid by default', function() {
var tileGrid = ol.tilegrid.createXYZ({tileSize: 512});
expect(source.tileGrid.tileSize_).to.equal(tileGrid.tileSize_);
expect(source.tileGrid.extent_).to.equal(tileGrid.extent_);
});
}); });
describe('#getTile()', function() { describe('#getTile()', function() {

View File

@@ -108,92 +108,3 @@ describe('ol.Sphere', function() {
}); });
}); });
describe('ol.Sphere.getLength()', function() {
var cases = [{
geometry: new ol.geom.Point([0, 0]),
length: 0
}, {
geometry: new ol.geom.MultiPoint([[0, 0], [1, 1]]),
length: 0
}, {
geometry: new ol.geom.LineString([
[12801741.441226462, -3763310.627144653],
[14582853.293918837, -2511525.2348457114],
[15918687.18343812, -2875744.624352243],
[16697923.618991036, -4028802.0261344076]
]),
length: 4407939.124914191
}, {
geometry: new ol.geom.LineString([
[115, -32],
[131, -22],
[143, -25],
[150, -34]
]),
options: {projection: 'EPSG:4326'},
length: 4407939.124914191
}, {
geometry: new ol.geom.MultiLineString([
[
[115, -32],
[131, -22],
[143, -25],
[150, -34]
], [
[115, -32],
[131, -22],
[143, -25],
[150, -34]
]
]),
options: {projection: 'EPSG:4326'},
length: 2 * 4407939.124914191
}, {
geometry: new ol.geom.GeometryCollection([
new ol.geom.LineString([
[115, -32],
[131, -22],
[143, -25],
[150, -34]
]),
new ol.geom.LineString([
[115, -32],
[131, -22],
[143, -25],
[150, -34]
])
]),
options: {projection: 'EPSG:4326'},
length: 2 * 4407939.124914191
}];
cases.forEach(function(c, i) {
it('works for case ' + i, function() {
var c = cases[i];
var length = ol.Sphere.getLength(c.geometry, c.options);
expect(length).to.equal(c.length);
});
});
});
describe('ol.Sphere.getArea()', function() {
var geometry;
before(function(done) {
afterLoadText('spec/ol/format/wkt/illinois.wkt', function(wkt) {
try {
var format = new ol.format.WKT();
geometry = format.readGeometry(wkt);
} catch (e) {
done(e);
}
done();
});
});
it('calculates the area of Ilinois', function() {
var area = ol.Sphere.getArea(geometry, {projection: 'EPSG:4326'});
expect(area).to.equal(145652224192.4434);
});
});

View File

@@ -457,20 +457,6 @@ describe('ol.View', function() {
}, 10); }, 10);
}); });
it('immediately completes for no-op animations', function() {
var view = new ol.View({
center: [0, 0],
zoom: 5
});
view.animate({
zoom: 5,
center: [0, 0],
duration: 25
});
expect(view.getAnimating()).to.eql(false);
});
it('prefers zoom over resolution', function(done) { it('prefers zoom over resolution', function(done) {
var view = new ol.View({ var view = new ol.View({
center: [0, 0], center: [0, 0],
@@ -570,21 +556,6 @@ describe('ol.View', function() {
view.setCenter([1, 2]); // interrupt the animation view.setCenter([1, 2]); // interrupt the animation
}); });
it('calls a callback even if animation is a no-op', function(done) {
var view = new ol.View({
center: [0, 0],
zoom: 0
});
view.animate({
zoom: 0,
duration: 25
}, function(complete) {
expect(complete).to.be(true);
done();
});
});
it('can run multiple animations in series', function(done) { it('can run multiple animations in series', function(done) {
var view = new ol.View({ var view = new ol.View({
center: [0, 0], center: [0, 0],
@@ -642,7 +613,7 @@ describe('ol.View', function() {
expect(view.getHints()[ol.ViewHint.ANIMATING]).to.be(2); expect(view.getHints()[ol.ViewHint.ANIMATING]).to.be(2);
view.animate({ view.animate({
rotation: Math.PI, rotate: Math.PI,
duration: 25 duration: 25
}, decrement); }, decrement);
expect(view.getHints()[ol.ViewHint.ANIMATING]).to.be(3); expect(view.getHints()[ol.ViewHint.ANIMATING]).to.be(3);
@@ -669,7 +640,7 @@ describe('ol.View', function() {
expect(view.getHints()[ol.ViewHint.ANIMATING]).to.be(2); expect(view.getHints()[ol.ViewHint.ANIMATING]).to.be(2);
view.animate({ view.animate({
rotation: Math.PI, rotate: Math.PI,
duration: 25 duration: 25
}); });
expect(view.getHints()[ol.ViewHint.ANIMATING]).to.be(3); expect(view.getHints()[ol.ViewHint.ANIMATING]).to.be(3);
@@ -1311,74 +1282,3 @@ describe('ol.View', function() {
}); });
}); });
}); });
describe('ol.View.isNoopAnimation()', function() {
var cases = [{
animation: {
sourceCenter: [0, 0], targetCenter: [0, 0],
sourceResolution: 1, targetResolution: 1,
sourceRotation: 0, targetRotation: 0
},
noop: true
}, {
animation: {
sourceCenter: [0, 0], targetCenter: [0, 1],
sourceResolution: 1, targetResolution: 1,
sourceRotation: 0, targetRotation: 0
},
noop: false
}, {
animation: {
sourceCenter: [0, 0], targetCenter: [0, 0],
sourceResolution: 1, targetResolution: 0,
sourceRotation: 0, targetRotation: 0
},
noop: false
}, {
animation: {
sourceCenter: [0, 0], targetCenter: [0, 0],
sourceResolution: 1, targetResolution: 1,
sourceRotation: 0, targetRotation: 1
},
noop: false
}, {
animation: {
sourceCenter: [0, 0], targetCenter: [0, 0]
},
noop: true
}, {
animation: {
sourceCenter: [1, 0], targetCenter: [0, 0]
},
noop: false
}, {
animation: {
sourceResolution: 1, targetResolution: 1
},
noop: true
}, {
animation: {
sourceResolution: 0, targetResolution: 1
},
noop: false
}, {
animation: {
sourceRotation: 10, targetRotation: 10
},
noop: true
}, {
animation: {
sourceRotation: 0, targetRotation: 10
},
noop: false
}];
cases.forEach(function(c, i) {
it('works for case ' + i, function() {
var noop = ol.View.isNoopAnimation(c.animation);
expect(noop).to.equal(c.noop);
});
});
});

Binary file not shown.

Before

Width:  |  Height:  |  Size: 396 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 403 B

View File

@@ -135,49 +135,6 @@ describe('ol.render', function() {
}); });
it('supports lineDash styles', function(done) {
var vectorContext = ol.render.toContext(context, {size: [100, 100]});
var style = new ol.style.Style({
stroke: new ol.style.Stroke({
lineDash: [10, 5]
})
});
vectorContext.setStyle(style);
vectorContext.drawGeometry(new ol.geom.Polygon([
[[25, 25], [75, 25], [75, 75], [25, 75], [25, 25]],
[[40, 40], [40, 60], [60, 60], [60, 40], [40, 40]]
]));
resembleCanvas(context.canvas,
'spec/ol/expected/render-polygon-linedash.png', IMAGE_TOLERANCE, done);
});
it('supports lineDashOffset', function(done) {
var vectorContext = ol.render.toContext(context, {size: [100, 100]});
var style = new ol.style.Style({
stroke: new ol.style.Stroke({
lineDash: [10, 5],
lineDashOffset: 5
})
});
vectorContext.setStyle(style);
vectorContext.drawGeometry(new ol.geom.Polygon([
[[25, 25], [75, 25], [75, 75], [25, 75], [25, 25]],
[[40, 40], [40, 60], [60, 60], [60, 40], [40, 40]]
]));
resembleCanvas(context.canvas,
'spec/ol/expected/render-polygon-linedashoffset.png', IMAGE_TOLERANCE, done);
});
}); });
}); });

Binary file not shown.

Before

Width:  |  Height:  |  Size: 819 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 831 B

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