meface/docs/article/gis/openlayers/61interactions.md

5.9 KiB
Raw Blame History

title date author tags categories
interactions 2020-11-2 ac
OpenLayers
Interactions
GIS

1 Interactions

ol中与地图交互相关的类都封装在ol.interaction命名空间下。

Interactions模块中有一个defaults交互组件对象, 它是Map中默认交互组件的集合。在创建Map实例时,可以添加interactions参数设置默认交互组件的是否加载到Map实例中。这些默认的交互控件,提供基础的地图展示功能。

1.1 Default Interactions

可以看出默认控件主要功能是地图的导航相关的操作,通过键盘或鼠标对地图进行平移、旋转、缩放等功能。

1.2 数据交互

除了这些默认的交互控件外,ol还提供跟用户在线编辑相关的交互控件,如:

  • ol/interaction/Draw:用于绘制几何对象的交互控件。
  • ol/interaction/Modify:用于修改要素几何对象的交互控件。必须使用sourcefeature选项来构建,当要修改已经添加到source中的要素,需要在构造参数option中指定source,当要修改feature集合中的要素时,需要在在构造参数option中指定features
  • ol/interaction/Select:用于选择矢量要素的交互控件。
  • ol/interaction/Snap:在绘制或修改时,用于捕捉节点的交互工具。

除了默认的交互控件地图上要新增其它控件需要调用map的addInteraction()方法添加移除控件调用map的removeInteraction()方法,交互控件只有添加到地图上才有作用。

2 示例

默认交互组件设置:

<!doctype html>
<html>
  <head>
    <link rel="stylesheet" href="css/ol.css" type="text/css">
    <style>
      .map {
        height: 400px;
        width: 100%;
      }
    </style>
    <script src="lib/ol.js"></script>
    <title>OpenLayers example</title>
    <meta charset="UTF-8">
  </head>
  <body>
    <h2>My Map</h2>
    <div id="map" class="map"></div>
    <script type="text/javascript">
        var map = new ol.Map({
            target: 'map',
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                })
            ],
            view: new ol.View({
                center: ol.proj.fromLonLat([37.41, 8.82]),
                zoom: 4
            }),
            interactions:new ol.interaction.defaults({
                'altShiftDragRotate': true,//是否允许按住Alt-Shift拖动地图进行旋转
                'onFocusOnly':false, //是否只有map所在的html元素获取焦点时才可以使用滚轮缩放地图和拖动地图
                'doubleClickZoom':true,
                'keyboard':true,//在map聚焦的情况下可以使用键盘上的"-"缩小地图shift+"+"放大地图,按"↑"、"↓"、"←"、"→"键平移地图
                'mouseWheelZoom':false,//是否可以使用鼠标滑轮进行缩放
                'shiftDragZoom':true,//是否按住shift加拖动的方式放大地图(拖动的区域)
                'dragPan':false,//是否可以拖动地图
                'pinchRotate':true,//是否允许用户使用两个手指【旋转】地图(移动端用的到)
                'pinchZoom':true,//是否允许用户使用两个手指【缩放】地图(移动端用的到)
                // 'zoomDuration':500 //缩放的动画时间
            })
        });

    </script>
  </body>
</html>