--- title: interactions date: 2020-11-2 author: ac tags: - OpenLayers - Interactions categories: - GIS --- ## 1 Interactions `ol`中与地图交互相关的类都封装在`ol.interaction`命名空间下。 在`Interactions`模块中有一个`defaults`交互组件对象, 它是`Map`中默认交互组件的集合。在创建`Map`实例时,可以添加`interactions`参数设置默认交互组件的是否加载到`Map`实例中。这些默认的交互控件,提供基础的地图展示功能。 ### 1.1 Default Interactions - [`ol/interaction/DragRotate~DragRotate`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_DragRotate-DragRotate.html):拖动旋转。按住`Shift`和`Alt`键,鼠标拖动地图,会绕当前视图中心旋转。 - [`ol/interaction/DoubleClickZoom~DoubleClickZoom`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_DoubleClickZoom-DoubleClickZoom.html):双击放大。按住`Shift`键双击是缩小。 - [`ol/interaction/DragPan~DragPan`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_DragPan-DragPan.html):拖动地图。 - [`ol/interaction/PinchRotate~PinchRotate`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_PinchRotate-PinchRotate.html):允许用户通过两个手指在触摸屏上旋转地图。 - [`ol/interaction/PinchZoom~PinchZoom`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_PinchZoom-PinchZoom.html):允许用户通过在触摸屏上用两个手指捏来缩放地图。 - [`ol/interaction/KeyboardPan~KeyboardPan`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_KeyboardPan-KeyboardPan.html):允许用户使用键盘箭头平移地图。请注意,尽管这种交互在默认情况下包含在map中,但只有当浏览器的焦点放在附加键盘事件的元素上时,才能使用这些键。简单点说就是焦点在map上时才可以使用箭头,点击一下map上的放大缩小或attributes属性控件,让可以map获取焦点。 - [`ol/interaction/KeyboardZoom~KeyboardZoom`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_KeyboardZoom-KeyboardZoom.html):使用数字键盘上的`+`、`-`控制地图的缩放(`Shift`+`=+`也可以放大)。同样需要map获取焦点后才有效,可以点击map上的放大缩小或attributes属性控件,让可以map获取焦点。 - [`ol/interaction/MouseWheelZoom~MouseWheelZoom`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_MouseWheelZoom-MouseWheelZoom.html):允许使用滚轮滑动控制地图缩放。 - [`ol/interaction/DragZoom~DragZoom`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_DragZoom-DragZoom.html):允许用户通过按`Shift`键在地图上框选来放大地图。 可以看出默认控件主要功能是地图的导航相关的操作,通过键盘或鼠标对地图进行平移、旋转、缩放等功能。 ### 1.2 数据交互 除了这些默认的交互控件外,`ol`还提供跟用户在线编辑相关的交互控件,如: - [`ol/interaction/Draw`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_Draw-Draw.html):用于绘制几何对象的交互控件。 - [`ol/interaction/Modify`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_Modify-Modify.html):用于修改要素几何对象的交互控件。必须使用`source`或`feature`选项来构建,当要修改已经添加到`source`中的要素,需要在构造参数`option`中指定`source`,当要修改`feature`集合中的要素时,需要在在构造参数`option`中指定`features` - [`ol/interaction/Select`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_Select-Select.html):用于选择矢量要素的交互控件。 - [`ol/interaction/Snap`](https://openlayers.org/en/latest/apidoc/module-ol_interaction_Snap-Snap.html):在绘制或修改时,用于捕捉节点的交互工具。 除了默认的交互控件,地图上要新增其它控件需要调用map的`addInteraction()`方法添加,移除控件调用map的`removeInteraction()`方法,交互控件只有添加到地图上才有作用。 ## 2 示例 **默认交互组件设置:** ```html OpenLayers example

My Map

```