OpenLayers 自定义拖动事件

249 阅读5分钟

前言

页面交互的复杂度体现系统使用的难易程度,在开发WebGIS系统过程中,总会涉及要素操作,如何设计才能使交互操作变得简洁呢?OpenLayers提供了一些成熟的交互控件可以做到,并且可以自定义交互事件。

1. 自定义交互类

创建拖动类Drag,并继承ol.interaction.Pointer类。在构造函数中初始化使用super函数初始化鼠标事件,然后设置坐标和鼠标样式。

PointerInteraction作为用户定义事件down、move、up的基类,管理着事件“拖动序列”。

当用户定义事件函数handleDownEvent返回true时,开始拖动序列,在拖动序列中,事件函数handleDragEvent在移动事件中被调用,当事件函数handleUpEvent被调用并返回false时,拖动序列结束。

class Drag extends ol.interaction.Pointer {
    constructor() {
        super({
            handleDownEvent,
            handleDragEvent,
            handleMoveEvent,
            handleUpEvent
        })
        // 要素坐标
        this.coordinate_ = null
        // 鼠标样式
        this.cursor_ = 'pointer'
        // 移动前鼠标样式
        this.previousCursor_ = undefined
        // 移动要素
        this.feature_ = null
    }
}

2. 鼠标交互事件

2.1. 鼠标按下事件

在鼠标按下事件中查询当前像素坐标点要素,从事件参数event中获取到map对象,通过调用forEachFeatureAtPixel方法获取目标位置要素对象,该方法接受两个参数,一个目标点象数坐标,另一个参数为函数对象,在该函数中返回查询要素。

如果在鼠标按下事件中查询到要素对象,则保存当前位置坐标和查询要素,设置返回条件为仅当查询到要素时才返回true,即当返回值为true时才可以进行拖动。

// 鼠标按下事件,返回'true'开始拖动
function handleDownEvent(evt) {
    const map = evt.map
    const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
        return feature
    })
    if (feature) {
        this.coordinate_ = evt.coordinate
        this.feature_ = feature
    }
    // 仅当查询到要素时才可以进行拖动
    return !!feature
}

2.2. 鼠标拖动事件

在鼠标拖动事件中需要计算要素拖动距离,在移动事件中可以获取当前移动的鼠标坐标,将当前X、Y坐标和目标要素坐标做差得出偏移距离,然后获取到要素几何对象,通过translate方法设置几何对象偏移。最后更新要素坐标值。

//  鼠标拖动事件
function handleDragEvent(evt) {
    // 计算拖动距离
    const deltaX = evt.coordinate[0] - this.coordinate_[0]
    const deltaY = evt.coordinate[1] - this.coordinate_[1]
    const geometry = this.feature_.getGeometry()
    geometry.translate(deltaX, deltaY)

    // 更新位置坐标
    this.coordinate_[0] = evt.coordinate[0]
    this.coordinate_[1] = evt.coordinate[1]
}

2.3. 鼠标移动事件

在鼠标移动事件中切换鼠标样式。在查询到要素对象时,设置鼠标样式为自定义样式,并保存地图对象原来鼠标样式,在未查询到要素对象时恢复原来的鼠标样式。

// 鼠标移动事件
function handleMoveEvent(evt) {
    if (this.cursor_) {
        const map = evt.map
        const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
            return feature
        })
        // 获取地图对象绑定HTMLElement
        const element = map.getTargetElement()
        if (feature) {
            if (element.style.cursor !== this.cursor_) {
                this.previousCursor_ = element.style.cursor
                element.style.cursor = this.cursor_
            }
        } else if (this.previousCursor_ !== undefined) {
            element.style.cursor = this.previousCursor_
            this.previousCursor_ = undefined
        }
    }
}

2.4. 鼠标释放事件

在鼠标释放事件中返回false,重置要素和坐标值,结束拖动事件。

// 鼠标松开事件
function handleUpEvent(evt) {
    this.feature_ = null
    this.coordinate_ = null
    return false
}

3. 加载拖动交互事件

加载交互事件有很多种方式,可以使用addInteraction方式加载,也可以获取交互对象进行加载。具体加载方式可以参考:OpenLayers 移动要素:

4. 完整代码

其中libs文件夹下的包需要更换为自己下载的本地包或者引用在线资源。

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>OpenLayers 拖拽缩放和旋转</title>
    <meta charset="utf-8" />

    <link rel="stylesheet" href="../../libs/css/ol9.2.4.css">

    <script src="../../js/config.js"></script>
    <script src="../../libs/js/ol9.2.4.js"></script>
    <style>
        * {
            padding0;
            margin0;
            font-size14px;
            font-family'微软雅黑';
        }

        html,
        body {
            width100%;
            height100%;
        }

        #map {
            position: absolute;
            top50px;
            bottom0;
            width100%;
        }

        #top-content {
            position: absolute;
            width100%;
            height50px;
            line-height50px;
            backgroundlinear-gradient(135deg#ff00cc#ffcc00#00ffcc#ff0066);
            color#fff;
            text-align: center;
            font-size32px;
        }

        #top-content span {
            font-size32px;
        }
    </style>
</head>

<body>
    <div id="top-content">
        <span>OpenLayers 自定义拖拽事件</span>
    </div>
    <div id="map" title="地图显示"></div>
</body>

</html>

<script>
    //地图投影坐标系
    const projection = ol.proj.get('EPSG:3857');
    //==============================================================================//
    //============================天地图服务参数简单介绍==============================//
    //================================vec:矢量图层==================================//
    //================================img:影像图层==================================//
    //================================cva:注记图层==================================//
    //======================其中:_c表示经纬度投影,_w表示球面墨卡托投影================//
    //==============================================================================//
    const TDTImgLayer = new ol.layer.Tile({
        title"天地图影像图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,
            attibutions"天地图影像描述",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const TDTImgCvaLayer = new ol.layer.Tile({
        title"天地图影像注记图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,
            attibutions"天地图注记描述",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const map = new ol.Map({
        target"map",
        loadTilesWhileInteractingtrue,
        viewnew ol.View({
            center: [102.84586425.421639],
            zoom5,
            worldsWrapfalse,
            minZoom1,
            maxZoom20,
            projection'EPSG:4326',
        }),
        layers: [TDTImgLayerTDTImgCvaLayer],
        // 地图默认控件
        controls: ol.control.defaults.defaults({
            zoomfalse,
            attributionfalse,
            rotatefalse
        }),
        // interactions: ol.interaction.defaults.defaults().extend([new Drag()])
    })

    map.on('click'evt => {
        console.log("获取地图坐标:", evt.coordinate)
    })

    class Drag extends ol.interaction.Pointer {
        constructor() {
            super({
                handleDownEvent,
                handleDragEvent,
                handleMoveEvent,
                handleUpEvent
            })
            // 要素坐标
            this.coordinate_ = null
            // 鼠标样式
            this.cursor_ = 'pointer'
            // 移动前鼠标样式
            this.previousCursor_ = undefined
            // 移动要素
            this.feature_ = null
        }
    }
    // 鼠标按下事件,返回'true'开始拖动
    function handleDownEvent(evt) {
        const map = evt.map
        const feature = map.forEachFeatureAtPixel(evt.pixelfunction (feature) {
            return feature
        })
        if (feature) {
            this.coordinate_ = evt.coordinate
            this.feature_ = feature
        }
        // 仅当查询到要素时才可以进行拖动
        return !!feature
    }
    //  鼠标拖动事件
    function handleDragEvent(evt) {
        // 计算拖动距离
        const deltaX = evt.coordinate[0] - this.coordinate_[0]
        const deltaY = evt.coordinate[1] - this.coordinate_[1]
        const geometry = this.feature_.getGeometry()
        geometry.translate(deltaX, deltaY)

        // 更新位置坐标
        this.coordinate_[0] = evt.coordinate[0]
        this.coordinate_[1] = evt.coordinate[1]
    }

    // 鼠标移动事件
    function handleMoveEvent(evt) {
        if (this.cursor_) {
            const map = evt.map
            const feature = map.forEachFeatureAtPixel(evt.pixelfunction (feature) {
                return feature
            })
            const element = map.getTargetElement()
            if (feature) {
                if (element.style.cursor !== this.cursor_) {
                    this.previousCursor_ = element.style.cursor
                    element.style.cursor = this.cursor_
                }
            } else if (this.previousCursor_ !== undefined) {
                element.style.cursor = this.previousCursor_
                this.previousCursor_ = undefined
            }
        }
    }
    // 鼠标松开事件
    function handleUpEvent(evt) {
        this.feature_ = null
        this.coordinate_ = null
        return false
    }

    map.getInteractions().extend([new Drag()])

    // 创建要素对象
    const pointFeature = new ol.Feature(new ol.geom.Point([
        90.45461480466271,
        28.27171566587066
    ]))
    const lineStringFeature = new ol.Feature(new ol.geom.LineString([
        [98.0607093593254131.773693479057368],
        [98.0607093593254118.823243159290566]
    ]))
    const polygonFeature = new ol.Feature(new ol.geom.Polygon([
        [
            [105.6232077530.401227753660713],
            [114.2716473957672230.471610903957952],
            [114.2716473957672221.920091032793525],
            [105.6232077520.934729613526073]
        ]
    ]))

    // 创建矢量数据源
    const vectorSource = new ol.source.Vector({
        features: [pointFeature, lineStringFeature, polygonFeature]
    })
    // 创建矢量图层
    const vectorLayer = new ol.layer.Vector({
        source: vectorSource,
        style: {
            'icon-src''../../image/point.png',
            // 'icon-size':[100,100],
            'icon-scale'5,
            // 'icon-opacity': 0.95,
            // 'icon-anchor': [0.5, 46],
            'icon-anchor-x-units''fraction',
            'icon-anchor-y-units''pixels',
            'stroke-width'5,
            'stroke-color': [0,255,2041],
            'fill-color': [255,204,00.6],
        }
    })
    map.addLayer(vectorLayer)

</script>

OpenLayers示例数据下载,请回复关键字:ol数据

全国信息化工程师-GIS 应用水平考试资料,请回复关键字:GIS考试

【GIS之路】 已经接入了智能助手,欢迎关注,欢迎提问。

欢迎访问我的博客网站-长谈GIShttp://shanhaitalk.com

都看到这了,不要忘记点赞、收藏 + 关注

本号不定时更新有关 GIS开发 相关内容,欢迎关注 !