OpenLayers基础教程——要素的编辑

本文介绍了如何在OpenLayers中实现地图要素的编辑功能,通过ol.interaction.Select选择要素并使用ol.interaction.Modify进行编辑。在要素编辑后,通过监听'modifyend'事件获取并处理修改后的坐标,适用于地理信息系统中的地图编辑场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、前言

OpenLayers中,要素的编辑主要使用ol.interaction.Selectol.interaction.Modify配合实现,下面开始介绍。

2、编辑要素

编辑功能的实现很简答,ol.interaction.Select负责选择要素,ol.interaction.Modify对被选择的要素进行编辑,代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>编辑要素</title>
    <link href="lib/ol/ol.css" rel="stylesheet" />
    <script src="lib/ol/ol.js"></script>
</head>
<body>
    <div id="map" style="width: 800px; height: 800px;"></div>
    <script>
        // 创建图层
        var layer = new ol.layer.Vector({
            source: new ol.source.Vector({
                features: [
                    new ol.Feature({
                        geometry: new ol.geom.Point([119.4, 29.6]),
                    }),
                    new ol.Feature({
                        geometry: new ol.geom.LineString([
                            [119.0, 29.4],
                            [119.2, 29.3],
                            [119.4, 29.5]
                        ])
                    }),
                    new ol.Feature({
                        geometry: new ol.geom.Polygon([[
                            [119.4, 29.0],
                            [119.6, 29.0],
                            [119.5, 29.2],
                            [119.4, 29.0]
                        ]])
                    })
                ]
            }),
            style: new ol.style.Style({
                image: new ol.style.Circle({
                    radius: 30,
                    fill: new ol.style.Fill({
                        color: 'red'
                    })
                }),
                stroke: new ol.style.Stroke({
                    color: 'blue',
                    width: 2
                }),
                fill: new ol.style.Fill({
                    color: 'yellow'
                })
            })
        });

        // 创建地图
        var map = new ol.Map({
            target: 'map',
            layers: [
                layer
            ],
            view: new ol.View({
                projection: 'EPSG:4326',
                center: [119.2, 29.2],
                zoom: 10
            })
        });

        // 创建选择工具
        var select = new ol.interaction.Select({
            condition: ol.events.condition.singleClick,
            style: new ol.style.Style({
                image: new ol.style.Circle({
                    radius: 30,
                    fill: new ol.style.Fill({
                        color: 'red'
                    })
                }),
                stroke: new ol.style.Stroke({
                    color: 'blue',
                    width: 2
                }),
                fill: new ol.style.Fill({
                    color: 'yellow'
                })
            }),
            layers: [
                layer
            ]
        });

        // 创建修改工具
        var modify = new ol.interaction.Modify({
            features: select.getFeatures()
        });

        // 添加交互工具
        map.addInteraction(select);
        map.addInteraction(modify);
    </script>
</body>
</html>

运行结果如下图所示:

在这里插入图片描述

3、要素编辑后的处理

在对要素进行拖动或者拉伸等操作后,其坐标肯定会随之发生改变,如果要获取编辑后的要素坐标,则需要监听modifyend事件,代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>编辑要素</title>
    <link href="lib/ol/ol.css" rel="stylesheet" />
    <script src="lib/ol/ol.js"></script>
</head>
<body>
    <div id="map" style="width: 800px; height: 800px;"></div>
    <script>
        // 创建图层
        var layer = new ol.layer.Vector({
            source: new ol.source.Vector({
                features: [
                    new ol.Feature({
                        geometry: new ol.geom.Point([119.4, 29.6]),
                    }),
                    new ol.Feature({
                        geometry: new ol.geom.LineString([
                            [119.0, 29.4],
                            [119.2, 29.3],
                            [119.4, 29.5]
                        ])
                    }),
                    new ol.Feature({
                        geometry: new ol.geom.Polygon([[
                            [119.4, 29.0],
                            [119.6, 29.0],
                            [119.5, 29.2],
                            [119.4, 29.0]
                        ]])
                    })
                ]
            }),
            style: new ol.style.Style({
                image: new ol.style.Circle({
                    radius: 30,
                    fill: new ol.style.Fill({
                        color: 'red'
                    })
                }),
                stroke: new ol.style.Stroke({
                    color: 'blue',
                    width: 2
                }),
                fill: new ol.style.Fill({
                    color: 'yellow'
                })
            })
        });

        // 创建地图
        var map = new ol.Map({
            target: 'map',
            layers: [
                layer
            ],
            view: new ol.View({
                projection: 'EPSG:4326',
                center: [119.2, 29.2],
                zoom: 10
            })
        });

        // 创建选择工具
        var select = new ol.interaction.Select({
            condition: ol.events.condition.singleClick,
            style: new ol.style.Style({
                image: new ol.style.Circle({
                    radius: 30,
                    fill: new ol.style.Fill({
                        color: 'red'
                    })
                }),
                stroke: new ol.style.Stroke({
                    color: 'blue',
                    width: 2
                }),
                fill: new ol.style.Fill({
                    color: 'yellow'
                })
            }),
            layers: [
                layer
            ]
        });

        // 创建修改工具
        var modify = new ol.interaction.Modify({
            features: select.getFeatures()
        });

        // 监听modifyend事件,获取要素修改后的坐标
        modify.on('modifyend', function (e) {
            var features = e.features;
            if (features.getLength() > 0) {
                var feature = features.item(0);
                var geometry = feature.getGeometry();
                var coordinates = geometry.getCoordinates();

                // 点
                if (geometry instanceof ol.geom.Point) {
                    console.log('更新后的点坐标:[' + coordinates + ']');
                }

                // 线
                if (geometry instanceof ol.geom.LineString) {
                    var msg = [];
                    for (var i = 0; i < coordinates.length; i++) {
                        msg.push('[' + coordinates[i] + ']');
                    }
                    console.log('更新后的线坐标:' + msg.join('、'));
                    msg = [];
                }

                // 面
                if (geometry instanceof ol.geom.Polygon) {
                    var msg = [];
                    for (var i = 0; i < coordinates.length; i++) {
                        var coordinate = coordinates[i];
                        for (var j = 0; j < coordinate.length; j++) {
                            msg.push('[' + coordinate[j] + ']');
                        }
                    }
                    console.log('更新后的面坐标:' + msg.join('、'));
                    msg = [];
                }
            }
        });

        // 添加交互工具
        map.addInteraction(select);
        map.addInteraction(modify);
    </script>
</body>
</html>

运行结果如下图所示:
在这里插入图片描述

### OpenLayers 基础教程和入门指南 #### 一、OpenLayers简介 OpenLayers是一个用于构建Web地图应用程序的强大JavaScript库。它支持多种地理空间数据格式,并提供了丰富的API来操作这些数据。通过OpenLayers,开发者可以在浏览器中轻松地展示来自不同源的地图瓦片、矢量数据和其他地理信息。 #### 二、安装与配置 为了在项目中使用OpenLayers,可以通过npm包管理器进行安装: ```bash npm install ol ``` 如果是在Vue.js环境中工作,则还需要确保正确设置了Webpack或其他打包工具以便能够加载所需的模块[^1]。 #### 三、核心概念介绍 ##### Map对象 `ol/Map` 是整个应用的核心部分之一,代表了一个完整的交互式地图实例。创建一个新的地图通常涉及指定其容器(通常是DOM中的div元素),视图(view),以及至少一层(layer)[^2]。 ##### View对象 `ol/View` 定义了当前视角的状态,比如中心位置(center)、缩放级别(zoom)等参数。这使得我们可以控制用户查看地图的方式——放大缩小或是平移移动。 ##### Layer层次结构 每一幅地图都由多个图层组成;每种类型的layer都有特定的功能。常见的有TileLayer(栅格图像), VectorLayer(几何图形特征集合)等等。它们共同构成了最终呈现给用户的视觉效果。 ##### Source数据来源 source负责提供实际的数据内容给对应的layer去渲染出来。例如,对于tile layer来说就是获取远程服务器上的切片图片资源;而对于vector layer而言则是处理本地GeoJSON文件或者其他形式的空间要素集。 #### 四、简单示例代码 下面给出一段简单的HTML+JS代码片段用来说明如何初始化一张带有底图的基础地图: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Basic Map</title> <!-- 引入样式 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@openlayers/openlayers@latest/dist/ol.css"/> <!-- 加载OpenLayers JS 文件 --> <script src="https://cdn.jsdelivr.net/npm/@openlayers/openlayers@latest/dist/ol.js"></script> </head> <body> <div id="map" style="width:100%;height:400px;"></div> <script type="text/javascript"> import 'ol/ol.css'; import {Map, View} from 'ol/'; import TileLayer from 'ol/layer/Tile'; import OSM from 'ol/source/OSM'; const map = new Map({ target: document.getElementById('map'), layers: [ new TileLayer({ source: new OSM() }) ], view: new View({ center: [0, 0], zoom: 2 }) }); </script> </body> </html> ``` 这段代码展示了怎样利用OpenStreetMap作为背景服务提供商,在页面上绘制出一幅世界地图概览图[^3]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值