01 openLayer_入门

1 综述

关注三点:

  • 每个类构建时的 option,以及该类的可触发的事件,和可调用的属性
  • 类与类之间的继承关系,子类可以继承父类的方法
  • openLayer 对 JS 标准库中数组、事件等进行了一些封装,从而形成的类

2 Observable - 抽象基类 - 可观察类

Abstract base class; normally only used for creating subclasses and not instantiated in apps. An event target providing convenient methods for listener registration and unregistration. A generic change event is always available through changed.

可以实现 chang : 属性

2.1 Subclasses

2.2 Fires(事件)

2.2.1 chang(BaseEvent)

Triggered when the revision counter is increased

这个 revision 即由 getRevision 获取的

// 通用更改事件。当修订计数器增加时触发。
  map.on('change', (event) => {
    console.log(event);
    //map对象的属性只要有改变,就会修改此对象的版本号,版本号变化了,此事件就会触发
  });
  // change:size事件
  map.on('change:size', (event) => {
    console.log('size改变');
    //屏幕尺寸变化的回调
  });
  // change:view事件
  map.on('change:view', (event) => {
    console.log('view改变');
  });

  // change:target事件
  map.on('change:target', (event) => {
    console.log('target改变');
  });

  // change:layerGroup事件
  map.on('change:layergroup', (event) => {
    console.log('target改变');
    //图层动态变化,图例动态变化
  });
2.2.2 error(BaseEvent)

Triggered when an error occurs.

// 地图发生错误触发
  map.on('error', (event) => {
    console.log('error');
  });

2.3 Methods(方法)

2.3.1 changed()

获取此对象的版本号

//获取此对象的版本号。每次修改对象时,其版本号都会增加。
let revision = map.getRevision();
console.log('getRevision1', revision);
map.changed();
console.log('getRevision12', map.getRevision());
2.3.2 dispatchEvent(event)=> {boolean | undefined}
 map.on('click', (event) => {
    // dispatchEvent即执行一下dblclick事件
    map.dispatchEvent('dblclick');
  });
2.3.3 getRevision()=>{number}

获取版本号

2.3.4 on(type, listener)、once(type, listener)、 un(type, listener)

监听事件

image.png

3 BaseObject - 抽象基类

Abstract base class; normally only used for creating subclasses and not instantiated in apps. Most non-trivial classes inherit from this.

它扩展了 Observable 可观察的属性,其中每个属性以及整个对象都是可观察的。

从此继承的类具有预定义属性,您可以向其中添加自己的属性。预定义属性在本文档中列为“可观察属性”,并具有自己的访问器;例如, Map 具有target属性,可使用 访问 getTarget()并使用 更改setTarget()。但是,并非所有属性都是可设置的。还有通用访问器get()set()。例如,get('target')相当于getTarget()

访问set器会触发更改事件,您可以通过注册侦听器来监控此事件。例如,View 具有 center属性,因此view.on('change:center', function(evt) {...});每当 center 属性的值发生变化时都会调用该函数。在函数内,evt.target将是视图,因此evt.target.getCenter() 将返回新的中心。

您可以使用 添加您自己的可观察属性 object.set('prop', 'value'),并使用 检索该属性object.get('prop')。您可以使用 监听该属性值的更改 object.on('change:prop', listener)。您可以使用 获取所有属性的列表 getProperties

Note that the observable properties are separate from standard JS properties. You can, for example, give your map object a title with map.title='New title' and with map.set('title', 'Another title'). The first will be a hasOwnProperty; the second will appear in getProperties(). Only the second is observable.

import BaseObject from 'ol/Object.js';

3.1 Subclasses

3.2 Extends

3.3 Fires(事件)

3.3.1 chang(BaseEvent)[inherit]
3.3.2 error(BaseEvent)[inherit]
3.3.3 propertychange(ObjectEvent)

Triggered when a property is changed.

//当属性改变时触发
  map.on('propertychange', (event) => {
    console.log('propertychange');
  });

3.4 Methods(方法)

3.4.1 changed() [inherit]
3.4.2 on(type, listener)、once(type, listener)、 un(type, listener)[inherit]
3.4.3 getRevision()=>{number}[inherit]
3.4.4 get(key)

Gets a value.

3.4.5 getKeys()=> {Array.<string>}

Get a list of object property names.

3.4.6 getProperties()=>{Object.<string, * > }

Get an object of all property names and values.

3.4.7 set(key, value, silent)

Sets a value.

image.png

silent 设置为 true 指 在不触发事件的情况下更新

3.4.8 setProperties(values, silent)

Sets a collection of key-value pairs. Note that this changes any existing properties and adds new ones (it does not remove any existing properties).

image.png

3.4.9 unset(key, silent)

Unsets a property.

image.png

4 Collection - JS 数组的扩展

标准 JS 数组的扩展版本,添加了方便的操作方法。添加和删除对 Collection 的更改会触发 Collection 事件。请注意,这不包括对 Collection_内_对象的更改;它们会触发相应对象的事件,而不是整个 Collection 的事件。

4.1 new Collection(array, options)

QQ_1721809982425.png

4.2 Fires

4.3 Extends

4.4 Observable Properties

image.png

4.5 Methods

image.png

注意几个方法:

  • insertAt(index, elem) :Insert an element at the provided index.
    QQ_1721810153600.png
  • item(index)=>{T} : Get the element at the provided index.
  • remove(elem)=>{T | undefined} : Remove the first occurrence of an element from the collection.
  • removeAt(index){T | undefined} : Remove the element at the provided index and return it. Return undefined if the collection does not contain this index.
  • setAt(index, elem) : Set the element at the provided index.

5 Map - 地图

The map is the core component of OpenLayers. For a map to render, a view, one or more layers, and a target container are needed:

import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';

const map = new Map({
  view: new View({
    center: [0, 0],
    zoom: 1,
  }),
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
  ],
  target: 'map',
});

The above snippet creates a map using a TileLayer to display OSM OSM data and render it to a DOM element with the id map.

The constructor places a viewport container (with CSS class name ol-viewport) in the target element (see getViewport()), and then two further elements within the viewport: one with CSS class name ol-overlaycontainer-stopevent for controls and some overlays, and one with CSS class name ol-overlaycontainer for other overlays (see the stopEvent option of Overlay for the difference). The map itself is placed in a further element within the viewport.

QQ_1721694433855.png

Layers are stored as a Collection in layerGroups. A top-level group is provided by the library. This is what is accessed by getLayerGroup and setLayerGroup. Layers entered in the options are added to this group, and addLayer and removeLayer change the layer collection in the group. getLayers is a convenience function for getLayerGroup().getLayers(). Note that LayerGroup is a subclass of BaseLayer, so layers entered in the options or added with addLayer can be groups, which can contain further groups, and so on.

5.1 Extends

5.2 new Map(options)

  • target
    地图的容器,元素本身或 id 元素的 。如果在构建时未指定,则 module:ol/Map~Map # setTarget 必须调用以渲染地图 。如果通过元素传递,则容器可以位于辅助文档中。
  • Layers
    如果未定义,将渲染没有图层的地图。请注意,图层按提供的顺序呈现,因此,例如,如果您希望矢量图层出现在切片图层的顶部,则它必须位于切片图层之后。
  • view
    地图视图。除非在构造时或通过 指定,否则将不会获取图层源 module:ol/Map~Map #setView 。
  • overlays
    最初添加到地图的叠加层。默认情况下,不添加叠加层。
  • interactions
    最初添加到地图的交互。如果未指定, module:ol/interaction.defaults 则使用。
  • controls
    最初添加到地图的控件。如果未指定, module:ol/control.defaults 则使用。
  • pixelRatio
    设备上物理像素与设备无关像素(下降)之间的比率。(默认为 window.devicePixelRatio)Window 接口的 devicePixelRatio 返回当前显示设备的物理像素分辨率与 CSS 像素分辨率之比。此值也可以解释为像素大小的比率:一个 CSS 像素的大小与一个物理像素的大小。 简单来说,它告诉浏览器应使用多少屏幕实际像素来绘制单个 CSS 像素。
  • keyboardEventTarget
    监听键盘事件的元素。这确定何时触发 KeyboardPan 和 KeyboardZoom 交互。例如,如果此选项设置为 document 键盘交互将始终触发。如果未指定此选项,则监听键盘事件的元素是地图目标(即用户提供的地图 div)。如果不是 document,则需要聚焦目标元素才能发出关键事件,要求目标元素具有 tabindex 属性。
  • maxTilesLoading
    同时加载的最大数量的瓦片。(默认为 16)moveTolerance 光标必须移动的最小距离(以像素为单位)才能被检测为地图移动事件而不是单击。增加此值可以更轻松地单击地图。(默认为 1)

5.3 Fires(事件)

5.3.1 BaseEvent
  • change
  • error
5.3.2 ObjectEvent
  • `change:layerGroup
  • change:size
  • change:target
  • change:view
  • propertychang
5.3.3 MapBrowserEvent
  • click
  • `dblclick
  • singleclick
  • pointerdrag : Triggered when a pointer is dragged.
  • pointermove : Triggered when a pointer is moved. Note that on touch devices this is triggered when the map is panned, so is not the same as mousemove.
// click事件,双击触发两次,点多少次都会触发
  map.on('click', (event) => {
    console.log('click');
  });
  //双击事件,没有拖动
  map.on('dblclick', (event) => {
    console.log('dblclick');
  });
  //真正的单击,没有拖动和双击。请注意,此事件会延迟 250 毫秒,以确保它不是双击。
  map.on('singleclick', (event) => {
    console.log('singleclick ');
  });

/* 触摸设备事件 */
// 地图触摸拖拽事件
  map.on('pointerdrag', (event) => {
    console.log('pointerdrag');
  });

  // 地图触摸移动事件
  map.on('pointermove', (event) => {
    console.log('pointermove');
  });
5.3.4 MapEvent
  • loadstart : Triggered when loading of additional map data has completed.
  • loadend : Triggered when loading of additional map data (tiles, images, features) starts.
  • movestart : Triggered when the map starts moving.
  • moveend : Triggered after the map is moved.
  • postrender : Triggered after a map frame is rendered.
// 地图开始移动事件
  map.on('movestart', (event) => {
    console.log('movestart ', event);
  });

  // 地图移动结束事件
  map.on('moveend', (event) => {
    console.log('moveend', event);
  });
 
//地图渲染完成触发
  map.on('postrender', (event) => {
    console.log('postrender');
  });
5.3.5 RenderEvent
  • precompose
     Triggered before layers are composed. When dispatched by the map, the event object will not have a context set. When dispatched by a layer, the event object will have a context set. Only WebGL layers currently dispatch this event.
  • postcompose
    Triggered after layers are composed. When dispatched by the map, the event object will not have a context set. When dispatched by a layer, the event object will have a context set. Only WebGL layers currently dispatch this event.
  • rendercomplete
     Triggered when rendering is complete, i.e. all sources and tiles have finished loading for the current viewport, and all tiles are faded in. The event object will not have a context set.
//在渲染图层之前触发,没有设置上下文context
  //监听的是渲染的图层layer
  map.on('precompose', (event) => {
    console.log('precompose');
  });

  //所有图层渲染完后触发,没有设置上下文context
  //监听的是渲染的图层layer
  map.on('postcompose', (event) => {
    console.log('postcompose');
  });

5.4 Observable Properties

NameTypeSettableObjectEvent typeDescription
layerGroupLayerGroupyeschange:layergroupA layer group containing the layers in this map.
sizeSize | undefinedyeschange:sizeThe size in pixels of the map in the DOM.
targetHTMLElement | string | undefinedyeschange:targetThe Element or id of the Element that the map is rendered in.
viewViewyeschange:viewThe view that controls this map.

5.5 Methods(方法)

5.5.1 add
  • addControl(control)
  • addInteraction(interaction)
  • addLayer(layer)
  • addOverlay(overlay)
5.5.2 get
5.5.3 set
  • setLayers(layers)
  • setLayerGroup(layerGroup)
  • setSize(size)
  • setTarget(target)
  • setView(view)
5.5.4 remove
  • removeControl(control) => {Control | undefined}
  • removeInteraction(interaction) => {Interaction | undefined}
  • removeLayer(layer) => {BaseLayer | undefined}
  • removeOverlay(overlay) => {Overlay | undefined}
5.5.5 像素与坐标
  • getEventPixel(event) => {Pixel}

    Returns the map pixel position for a browser event relative to the viewport.

  mapDom.value?.addEventListener('mousemove', (event: MouseEvent) => {
    // 获取到地图鼠标的位置
    mousePosition = map.getEventPixel(event);
    // 鼠标移动时强制渲染地图
    map.render();
  });
  • getEventCoordinate(event) => {Coordinate}

    Returns the coordinate in user projection for a browser event.

  • getCoordinateFromPixel(pixel) => {Coordinate}

    Get the coordinate for a given pixel. This returns a coordinate in the user projection.

  • getPixelFromCoordinate(coordinate) => {Pixel}

    Get the pixel for a coordinate. This takes a coordinate in the user projection and returns the corresponding pixel.

//获取到当前视口的像素
    let eventPixel = map.getEventPixel(event.originalEvent);
    console.log('getEventPixel', eventPixel);
    //获取指定事件的投影坐标
    let eventCoordinate = map.getEventCoordinate(event.originalEvent);
    console.log('getEventCoordinate', eventCoordinate);
    //获取给定像素的投影坐标
    let coordinateFromPixel = map.getCoordinateFromPixel(event.pixel);
    console.log('getCoordinateFromPixel', coordinateFromPixel);
    //获取指定坐标的像素。这需要用户投影中的坐标并返回相应的像素
    let pixelFromCoordinate = map.getPixelFromCoordinate([113.35275651421398, 23.12185264976067]);
    console.log('getPixelFromCoordinate', pixelFromCoordinate);
  • getFeaturesAtPixel(pixel, options) => {Array< FeatureLike >}

    Get all features that intersect a pixel on the viewport.

  • hasFeatureAtPixel(pixel, options) => {boolean}

    Detect if features intersect a pixel on the viewport. Layers included in the detection can be configured through the layerFilter option.

  • forEachFeatureAtPixel(pixel, callback, opt_options) => {T | undefined}
    image.png

//获取与视口上的像素相交的所有要素。
    let feature = map.getFeaturesAtPixel(event.pixel);
    console.log('getFeaturesAtPixel', feature);
    map.on('singleclick', (event) => {
      //检测与视口上的像素相交的featrue
      let features: FeatureLike[] = [];
      map.forEachFeatureAtPixel(
        event.pixel,
        (feature, layer) => {
          console.log(event, feature, layer);
          features.push(feature);
        },
        {
          layerFilter: function (layer) {
            //图层过滤
            return layer.get('name') === 'gz';
          },
          hitTolerance: 0, //以 css 像素为单位的命中检测容差。将检查给定位置周围半径内的像素的featrue。
          checkWrapped: true, //将检查 +/- 1 世界宽度范围内的包裹几何图形
        },
      );
    });
5.5.6 其他
  • render()

    Request a map rendering (at the next animation frame).

  • renderSync()

    Requests an immediate render in a synchronous manner.

  • updateSize()

    Force a recalculation of the map viewport size. This should be called when third-party code changes the size of the map viewport.

    //强制重新计算地图视口大小
    
    

map.updateSize();

//在下一个动画帧请求地图渲染

map.render();

//以同步方式请求立即渲染

map.renderSync();


## 5 View - 视图
### 5.1 概览

> A View object represents a simple 2D view of the map.
> This is the object to act upon to change the center, resolution, and rotation of the map.
> A View has a `projection`. The projection determines the coordinate system of the center, and its units determine the units of the resolution (projection units per pixel). The default projection is Web Mercator (EPSG:3857).
### 5.2 new View(options)

| Name                         | Type                                                                                                                    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `center`                     | [Coordinate](https://openlayers.org/en/latest/apidoc/module-ol_coordinate.html#~Coordinate) \| undefined                | The initial center for the view. If a user projection is not set, the coordinate system for the center is specified with the `projection` option. Layer sources will not be fetched if this is not set, but the center can be set later with ` #setCenter `.                                                                                                                                                                                                                                                                                        |
| `constrainRotation`          | boolean \| number (defaults to true)                                                                                    | Rotation constraint. `false` means no constraint. `true` means no constraint, but snap to zero near zero. A number constrains the rotation to that number of values. For example, `4` will constrain the rotation to 0, 90, 180, and 270 degrees.                                                                                                                                                                                                                                                                                                 |
| `enableRotation`             | boolean (defaults to true)                                                                                              | Enable rotation. If `false`, a rotation constraint that always sets the rotation to zero is used. The `constrainRotation` option has no effect if `enableRotation` is `false`.                                                                                                                                                                                                                                                                                                                                                                    |
| `extent`                     | [Extent](https://openlayers.org/en/latest/apidoc/module-ol_extent.html#~Extent) \| undefined                            | The extent that constrains the view, in other words, nothing outside of this extent can be visible on the map.                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `constrainOnlyCenter`        | boolean (defaults to false)                                                                                             | If true, the extent constraint will only apply to the view center and not the whole extent.                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `smoothExtentConstraint`     | boolean (defaults to true)                                                                                              | If true, the extent constraint will be applied smoothly, i.e. allow the view to go slightly outside of the given `extent`.                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `maxResolution`              | number \| undefined                                                                                                     | The maximum resolution used to determine the resolution constraint. It is used together with `minResolution` (or `maxZoom`) and `zoomFactor`. If unspecified it is calculated in such a way that the projection's validity extent fits in a 256x256 px tile. If the projection is Spherical Mercator (the default) then `maxResolution` defaults to `40075016.68557849 / 256 = 156543.03392804097`.                                                                                                                                               |
| `minResolution`              | number \| undefined                                                                                                     | The minimum resolution used to determine the resolution constraint. It is used together with `maxResolution` (or `minZoom`) and `zoomFactor`. If unspecified it is calculated assuming 29 zoom levels (with a factor of 2). If the projection is Spherical Mercator (the default) then `minResolution` defaults to `40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253`.                                                                                                                                                           |
| `maxZoom`                    | number (defaults to 28)                                                                                                 | The maximum zoom level used to determine the resolution constraint. It is used together with `minZoom` (or `maxResolution`) and `zoomFactor`. Note that if `minResolution` is also provided, it is given precedence over `maxZoom`.                                                                                                                                                                                                                                                                                                               |
| `minZoom`                    | number (defaults to 0)                                                                                                  | The minimum zoom level used to determine the resolution constraint. It is used together with `maxZoom` (or `minResolution`) and `zoomFactor`. Note that if `maxResolution` is also provided, it is given precedence over `minZoom`.                                                                                                                                                                                                                                                                                                               |
| `multiWorld`                 | boolean (defaults to false)                                                                                             | If `false` the view is constrained so only one world is visible, and you cannot pan off the edge. If `true` the map may show multiple worlds at low zoom levels. Only used if the `projection` is global. Note that if `extent` is also provided it is given precedence.                                                                                                                                                                                                                                                                          |
| `constrainResolution`        | boolean (defaults to false)                                                                                             | If true, the view will always animate to the closest zoom level after an interaction; false means intermediary zoom levels are allowed.                                                                                                                                                                                                                                                                                                                                                                                                           |
| `smoothResolutionConstraint` | boolean (defaults to true)                                                                                              | If true, the resolution min/max values will be applied smoothly, i. e. allow the view to exceed slightly the given resolution or zoom bounds.                                                                                                                                                                                                                                                                                                                                                                                                     |
| `showFullExtent`             | boolean (defaults to false)                                                                                             | Allow the view to be zoomed out to show the full configured extent. By default, when a view is configured with an extent, users will not be able to zoom out so the viewport exceeds the extent in either dimension. This means the full extent may not be visible if the viewport is taller or wider than the aspect ratio of the configured extent. If showFullExtent is true, the user will be able to zoom out so that the viewport exceeds the height or width of the configured extent, but not both, allowing the full extent to be shown. |
| `projection`                 | [ProjectionLike](https://openlayers.org/en/latest/apidoc/module-ol_proj.html#~ProjectionLike) (defaults to 'EPSG:3857') | The projection. The default is Spherical Mercator.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `resolution`                 | number \| undefined                                                                                                     | The initial resolution for the view. The units are `projection` units per pixel (e.g. meters per pixel). An alternative to setting this is to set `zoom`. Layer sources will not be fetched if neither this nor `zoom` are defined, but they can be set later with ` #setZoom ` or ` #setResolution `.                                                                                                                                                                                                                                                |
| `resolutions`                | Array.<number> \| undefined                                                                                             | Resolutions that determine the zoom levels if specified. The index in the array corresponds to the zoom level, therefore the resolution values have to be in descending order. It also constrains the resolution by the minimum and maximum value. If set the `maxResolution`, `minResolution`, `minZoom`, `maxZoom`, and `zoomFactor` options are ignored.                                                                                                                                                                                       |
| `rotation`                   | number (defaults to 0)                                                                                                  | The initial rotation for the view in radians (positive rotation clockwise, 0 means North).                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `zoom`                       | number \| undefined                                                                                                     | Only used if `resolution` is not defined. Zoom level used to calculate the initial resolution for the view.                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `zoomFactor`                 | number (defaults to 2)                                                                                                  | The zoom factor used to compute the corresponding resolution.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `padding`                    | Array.<number> (defaults to [0, 0, 0, 0])                                                                               | Padding (in css pixels). If the map viewport is partially covered with other content (overlays) along its edges, this setting allows to shift the center of the viewport away from that content. The order of the values is top, right, bottom, left.                                                                                                                                                                                                                                                                                             |

```js
const view = new View({

    center: [113.24981689453125, 23.126468438108688], //视图中心位置
    projection: 'EPSG:4326', //指定投影,84参考系投影
    zoom: 12, //缩放到的级别
    constrainRotation: false, //true/false 没有约束,4将旋转限制为 0、90、180 和 270 度
    enableRotation: true,
    constrainOnlyCenter: false, // 如果为 true,则范围约束将仅适用于视图中心而不是整个范围
    extent: [-180.0, 0.0, 180.0, 90.0], // 限制视图的范围 [左下角经度,左下角纬度,右上角经度,右上角纬度]
    smoothExtentConstraint: true, // 如果为 true,范围约束将被平滑地应用,即允许视图稍微超出给定的 extent
    maxResolution: 256, // 如果未指定,则以投影的有效范围适合 256x256 像素图块的方式计算
    minResolution: 256, // 如果未指定,则以投影的有效范围适合 256x256 像素图块的方式计算
    maxZoom: 5, //用于确定分辨率约束的最大缩放级别
    minZoom: 0, //用于确定分辨率约束的最小缩放级别
    multiWorld: false, //如果 false 视图受到约束,因此只有一个世界可见,并且您无法平移边缘。如果 true 地图可能以低缩放级别显示多个世界
    constrainResolution: false, //如果为 true,则视图将始终在交互后以最接近的缩放级别进行动画处理;false 表示允许中间缩放级别。
    smoothResolutionConstraint: true, //如果为 true,则视图将始终在交互后以最接近的缩放级别进行动画处理;false 表示允许中间缩放级别。
    showFullExtent: true, //允许缩小视图以显示完整的配置范围
    resolution: 2, //视图的初始分辨率。单位是 projection 每像素的单位(例如每像素米
    resolutions: [50, 40, 30, 20, 10, 5, 2], //指定缩放级别的分辨率,数组中的索引对应于缩放级别,因此分辨率值必须按降序排列。
    rotation: Math.PI / 2, //以弧度为单位的视图初始旋转(顺时针旋转,0 表示北)
    zoomFactor: 2, //用于计算相应分辨率的缩放因子
    padding: [350, 150, 150, 150], //填充(以 css 像素为单位)顺序是上、右、下、左,如果地图视口沿其边缘部分被其他内容(覆盖)覆盖,则此设置允许将视口的中心从该内容移开
  });

5.6 Extends

5.7 Observable Properties

image.png

5.8 Fire

image.png

5.9 Methods

5.9.1 adjust

opt_anchor 为锚点(可选值)
image.png

  • adjustCenter(deltaCoordinates)
  • adjustResolution(ratio, opt_anchor)
  • adjustRotation(delta, opt_anchor)
  • adjustZoom(delta, opt_anchor)
let view = map.getView();
  if (view) {
    view.adjustCenter([-10, 3]); // 将相对坐标添加到视图的中心
    view.adjustResolution(3) //将视图分辨率乘以一个比率
    view.adjustRotation(Math.PI/2,[130,25])//向视图旋转添加一个值, [130,25]为锚点
    view.adjustZoom(3,[100,25])// 将值添加到视图缩放级别
  }
5.9.2 animate(var_args)

Animate the view. The view’s center, zoom (or resolution), and rotation can be animated for smooth transitions between view states. For example, to animate the view to a new zoom level:

view.animate({zoom: view.getZoom() + 1});

By default, the animation lasts one second and uses in-and-out easing. You can customize this behavior by including duration (in milliseconds) and easing options (see ol/easing).

To chain together multiple animations, call the method with multiple animation objects. For example, to first zoom and then pan:

view.animate({zoom: 10}, {center: [0, 0]});

If you provide a function as the last argument to the animate method, it will get called at the end of an animation series. The callback will be called with true if the animation series completed on its own or false if it was cancelled.

Animations are cancelled by user interactions (e.g. dragging the map) or by calling view.setCenter()view.setResolution(), or view.setRotation() (or another method that calls one of these).

image.png


import { easeIn, easeOut } from 'ol/easing';

let view = map.getView();
  if (view) {
    view.animate(
      { zoom: 10, rotation: Math.PI / 2, duration: 2000 },
      {
        center: [116.36564254760744, 39.90486412650293],
        easing: easeOut,
        duration: 10000,
      },
      (flag) => { // 回调函数
        if (flag) console.log('动画完成');
        else console.log('动画取消');
      },
    );
    setTimeout(() => {
      //取消动画
      view.cancelAnimations();
    }, 5000);
  }
5.9.3 fit(geometryOrExtent, options)

Fit the given geometry or extent based on the given map size and border. The size is pixel dimensions of the box to fit the extent into. In most cases you will want to use the map size, that is map.getSize(). Takes care of the map angle.

image.png

let view = map.getView();
  let extent = [106.36564254760744, 30.90486412650293, 116.36564254760744, 39.90486412650293];
  if (view) {
    view.fit(extent, {
      //根据给定的地图大小和边界拟合给定的几何图形或范围
      duration: 3000,
      callback: () => {
        console.log('fit 函数执行完毕');
      },
    });

  }
5.9.4 get、set
  • get/set 属性名

  • getAnimating() => {boolean}

    Determine if the view is being animated.

  • getZoomForResolution(resolution) => {number | undefined}

    Get the zoom level for a resolution.

  • getResolutionForZoom(zoom) => {number}

    Get the resolution for a zoom level.

  • getResolutionForExtent(extent, size) => {number}

    Get the resolution for a provided extent (in map units) and size (in pixels).

5.9.5 其他
  • beginInteraction()

    Notify the View that an interaction has started. The view state will be resolved to a stable one if needed (depending on its constraints).

  • endInteraction(duration, resolutionDirection, anchor)

    Notify the View that an interaction has ended. The view state will be resolved to a stable one if needed (depending on its constraints).
    image.png

  • calculateExtent(size) => {Extent}

    Calculate the extent for the current view state and the passed box size.

  • centerOn(coordinate, size, position)

    Center on coordinate and view position.
    image.png

OpenLayers是一个开源的JavaScript库,用于在Web上创建交互式地图应用程序。它提供了一系列功能强大的地图操作和可视化效果,可以轻松地在网页中显示地图、标记点、绘制图形等。\[1\] 如果你想学习OpenLayers,可以从官方网站开始。虽然官网资料是全英文的,但你可以通过翻译工具或者在线教程来帮助理解。另外,你也可以参考其他人的学习经验和教程,例如在论坛或社交媒体上与其他开发者交流和讨论。\[1\] 在开始学习OpenLayers之前,你可以先了解一下它的基本概念和使用方法。你可以通过一个小地图示例来展示OpenLayers的效果,例如使用Vue和OpenLayers结合来创建一个简单的地图应用程序。你可以使用NPM来安装OpenLayers,执行命令"cnpm i -S ol"即可。\[2\] 在OpenLayers中,layers属性用于定义地图中可用图层的列表。你可以使用ol.layer.Tile类来创建一个瓦片图层,并使用ol.source.OSM类作为图层的数据源。这样就可以在地图上显示一个基本的OpenStreetMap图层。\[3\] 希望这些信息对你开始学习OpenLayers有所帮助!如果你有任何进一步的问题,请随时提问。 #### 引用[.reference_title] - *1* *2* [OpenLayers入门(一)](https://blog.csdn.net/jcxxs_xm/article/details/122357809)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [OpenLayers 学习--快速入门](https://blog.csdn.net/naturessdfsafagf/article/details/102546412)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值