uniapp 整合openlayers 编辑图形文件并上传到服务器

news/2025/2/23 17:49:55

引入openlayer依赖 

import Map from 'ol/Map.js'  // OpenLayers的主要类,用于创建和管理地图  
import View from 'ol/View.js'  // OpenLayers的视图类,定义地图的视图属性 
import TileLayer from 'ol/layer/Tile.js'// OpenLayers的瓦片图层类   
import XYZ from 'ol/source/XYZ.js'
import olsourceOSM from 'ol/source/OSM.js'
import TileWMS from 'ol/source/TileWMS.js';
import Feature from 'ol/Feature.js'  // OpenLayers的要素类,表示地图上的一个对象或实体          
import Point from 'ol/geom/Point.js'  // OpenLayers的点几何类,用于表示点状的地理数据        
import { Vector as VectorLayer } from 'ol/layer.js'  // OpenLayers的矢量图层类,用于显示矢量数据        
import { Vector as VectorSource } from 'ol/source.js'  // OpenLayers的矢量数据源类,用于管理和提供矢量数据       
import { Circle as CircleStyle, Style, Stroke, Fill, Icon } from "ol/style.js"  // OpenLayers的样式类,用于定义图层的样式,包括圆形样式、基本样式、边框、填充和图标      
import { ScaleLine, defaults as defaultControls, MousePosition } from 'ol/control.js'// OpenLayers的控件类,包括默认的控件集合和特定的全屏、鼠标位置、比例尺控件
import { transform } from 'ol/proj.js'// OpenLayers的投影转换函数,用于经纬度坐标和投影坐标之间的转换
import LineString from 'ol/geom/LineString.js'  // OpenLayers的线几何类,用于表示线状的地理数据            
import Polygon from "ol/geom/Polygon.js"  // OpenLayers的多边形几何类,用于表示面状的地理数据
import ZoomSlider from 'ol/control/ZoomSlider.js';// 滑动放大缩小按钮
import FullScreen from 'ol/control/FullScreen.js';// 全屏按钮
import ZoomToExtent from 'ol/control/ZoomToExtent.js';// 范围 
import {GeoJSON, GML, WFS} from 'ol/format'; 
import {Select, Draw, Modify, Snap} from 'ol/interaction.js';
import Overlay from 'ol/Overlay';

1、创建编辑图层

                        
                        // 创建 VectorLayer 用于加载 GeoJSON
						layer =  new VectorLayer({
						  source: new VectorSource({
							url: data.url, // 替换为您的 GeoJSON 服务 URL
							format: new GeoJSON(),
						  }),
						  style: new Style({
							fill: new Fill({
							  color: '#ff00ff',
							}),
							// 样式-边框
							stroke: new Stroke({
							  color: '#6600ff',
							  width: 2,
							}),
							// 使用 CircleStyle 创建一个圆形的点
							image:new CircleStyle({
								// 点样式
								fill:new Fill({
									color: 'rgba(255,0,0,0.4)',
								}),
								// 点周边样式
								stroke:new Stroke({
									color: '#3399CC',
									width: 1.25, 
								}),
								radius:7,// 半径
							}),
						  }),
						  visible: true,
						  // 上传服务器所需
						  projection: data.wkid,
						  featureNS:data.featureNS,
						  featureType:data.featureType,
					      geometryName:data.geometryName,
						  wfsjdUrl:data.wfsjdUrl,
						  wkid:data.wkid,
						});
                    // 添加图层
					this.map.addLayer(layer); 

2、创建交互editLayer()方法

editLayer(){
				const that = this;
				//console.log("selLayer",selLayer.get("wfsjdUrl"));
				// 创建选择交互
				const select = new Select({
					condition: function (event) {
					  return event.type === "click";
					},
				});
				that.map.addInteraction(select);
				
				// 根据选择状态动态设置修改交互
				select.on("select", function (event) {
					const selectedFeatures = event.selected;
				    const selectlayer = select.getLayer(selectedFeatures[0]);
					if(selectlayer == null){
						return;
					}
					
					if (selectedFeatures.length > 0) {
						that.modify = new Modify({
							features:select.getFeatures(),
							style:null,// 使用features的默认样式
						});
						that.map.addInteraction(that.modify);
						
						const snap = new Snap({
							source: selectlayer.getSource(),
						});
						that.map.addInteraction(snap);
						
						that.modify.on("modifyend",(e) =>{
							let feature = e.features.item(0).clone();
							feature.setId(e.features.item(0).getId());
							if(selectlayer.get("geometryName")!=null)
							{
							  feature.setGeometryName(selectlayer.get("geometryName")); 
							}
							// 坐标系转换:3857 -> 4326
							// const geometry = feature.getGeometry().clone();
							// geometry.transform('EPSG:3857', 'EPSG:4326');
							// feature.setGeometry(geometry);
							// let geomType = feature.getGeometry().getType().toLowerCase();
					
							// feature.getGeometry().applyTransform(function(flatCoordinates, flatCoordinates2, stride){
							//   for(let j = 0, jj = flatCoordinates.length; j < jj; j += stride){
							//     let y = flatCoordinates[j];
							//     let x = flatCoordinates[j + 1];
							//     flatCoordinates[j] = x;
							//     flatCoordinates[j + 1] = y;
							//   }
							// })
							// const featureN = new Feature();
							// featureN.setId('土地推介地块.32');
							// featureN.setGeometry(feature.values_.geometry)
						   that.editGeometry("update", feature, selectlayer);
						});
						
					}
				
				});
				
				// 双击地图
				that.map.on('dblclick', function (evt) {
					 // 移除监听modify
					 that.map.removeInteraction(modify);
				});
				
				
			},

3、编辑属性信息editGeometry()方法

editGeometry(type, mofeature, layer){
				  const that = this;
				  const formatWFS = new WFS({
				    featureNS: layer.get("featureNS"),//  featureNS: http://jcdl
				    featureType: layer.get("featureType"),// featureType: ceshidk
				    // featurePrefix: 'jcdl', // 命名空间前缀
				    version: '1.0.0' // 指定为和示例代码一致的版本
				  });
				  
				  var formatGML = new GML({
				      featureNS: layer.get("featureNS"),//  featureNS: http://jcdl
				      featureType:  layer.get("featureType"),// featureType: ceshidk
				      // featurePrefix: 'jcdl', // 命名空间前缀
					  // projection:3857
				      srsName: 'EPSG:'+layer.get("projection"), // GeoServer 图层应使用 WGS84
				      gmlVersion: 1, // 强制使用 GML 3
				      
				  });
				
				   var node = '';
				   switch (type) {
				      case "insert":
				        node = formatWFS.writeTransaction([mofeature], [], [], formatGML);
				        break;
				      case "update":
				        node = formatWFS.writeTransaction([], [mofeature], [], formatGML);
				        break;
				      case "delete":
				        node = formatWFS.writeTransaction([], [], [mofeature], formatGML);
				        break;
				    }

				    const serializer = new XMLSerializer();
				    const transactionString = serializer.serializeToString(node);
				    const wfsjdUrl=layer.get("wfsjdUrl");
				    that.fetchFeatures(transactionString,wfsjdUrl);
				  
			},

4、上传编辑后的结果fetchFeatures()方法

fetchFeatures(node,url){
				//url = http://192.168.1.20:8081/geoserver/wfs
				console.log("url",url)
				fetch(url, {
					method: 'POST',
					body: node,
					headers: { 
						'Content-Type': 'text/xml',
					}
				}).then((response) => {
				  return response.text().then((text) => {
					if (response.ok) {
					  console.log('保存成功,服务器响应:', text);
					} else {
					  console.error('保存失败,服务器响应:', text);
					}
				  });
				}).catch(function (error) {
					console.error('保存失败: ', error);
				});
				  
			},


http://www.niftyadmin.cn/n/5863636.html

相关文章

verilog中等难度设计实践与ALU设计

Verilog中等难度部分设计实践&#xff08;含ALU算术逻辑单元的设计&#xff09; verilog的中等部分根据Deepseek给出的大纲理应包括时序逻辑verilog设计实践和组合逻辑verilog组合设计实践两个部分。 时序逻辑verilog设计和实践 在 Verilog 中&#xff0c;时序逻辑通常通过 …

计算机考研复试上机07

14、数据结构 1)二叉树 1.常用操作 struct TreeNode{int data;TreeNode *leftChild;TreeNode *rightChild; }; //前序遍历 void PreOrder(TreeNode *root){if(root == NULL) return;visit(root->data);PreOrder(root->leftChild);PreOrder(root->rightChild);ret…

提效10倍:基于Paimon+Dolphin湖仓一体新架构在阿里妈妈品牌业务探索实践

1. 业务背景 阿里妈妈品牌广告数据包括投放引擎、下发、曝光、点击等日志&#xff0c;面向运筹调控、算法特征、分析报表、诊断监控等应用场景&#xff0c;进行了品牌数仓能力建设。随着业务发展&#xff0c;基于Lambda架构的数仓开发模式&#xff0c;缺陷日益突出&#xff1a;…

Windows 上编译 mebedtls 的鸿蒙库

mebedtls 地址&#xff1a;https://github.com/Mbed-TLS/mbedtls 准备工作&#xff1a; clone mebedtls 仓库到本地(tag: mbedtls-2.26.0)鸿蒙工具链(SDK version: v5.0.5) 编译文件修改&#xff1a; 对 CMakeLists.txt 进行修改&#xff0c;主要是关闭了以下几个选项 ENABLE_P…

Spring Boot Validation 接口校验:从零到掌握

在开发 Web 应用时&#xff0c;数据校验是不可忽视的一部分。无论是注册用户信息、提交表单数据&#xff0c;还是处理业务逻辑&#xff0c;数据的有效性和完整性都需要得到保证。Spring Boot 提供了强大的验证功能&#xff0c;基于 Hibernate Validator 框架&#xff0c;通过注…

11.Docker 之分布式仓库 Harbor

Docker 之分布式仓库 Harbor Docker 之分布式仓库 Harbor1. Harbor 组成2. 安装 Harbor Docker 之分布式仓库 Harbor Harbor 是一个用于存储和分发 Docker 镜像的企业级 Registry 服务器&#xff0c;由 VMware 开源&#xff0c;其通过添加一些企业必需的功能特性&#xff0c;例…

Spring Boot 集成 T-io 实现客户端服务器通信

Spring Boot 集成 T-io 实现客户端服务器通信 本文详细介绍如何在 Spring Boot 项目中集成 T-io 框架&#xff0c;实现客户端与服务器之间的通信&#xff0c;并支持组聊、群聊和私聊功能。通过本文&#xff0c;您能够全面了解 T-io core 的使用方法&#xff0c;以及如何正确启…

从零开始学 Rust:基本概念——变量、数据类型、函数、控制流

文章目录 Variables and MutabilityShadowing Data TypesScalar TypesCompound Types FunctionsFunction Parameters CommentsControl FlowRepetition with Loops Variables and Mutability fn main() {let mut x 5;println!("The value of x is: {}", x);x 6;pri…