OpenLayers动态修改GeoServer发布的地图样式

流程思路

1.改写GeoServer相应的SLD,使其支持动态修改样式;
2.修改前端请求WMS服务参数。

修改GeoServer的SLD

该部分在GeoServer官网上有说明,想了解更多请访问GeoServer官网:https://docs.geoserver.org/stable/en/user/styling/sld/extensions/substitution.html#sld-variable-substitution
GeoServer从2.0.2开始支持通过改变请求参数来动态改变WMS服务的SLD样式,如改变字体、大小、颜色等。

示例

本文以动态修改点状符号的类型、颜色和大小为例进行说明。

常规状态下SLD写法

常规状态下要渲染点的颜色和大小,其SLD如下:

<?xml version="1.0" encoding="ISO-8859-1"?>
<StyledLayerDescriptor version="1.0.0" xmlns="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc"
  xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd">
  <NamedLayer>
    <UserStyle>
      <Title>Default point</Title>
      <Abstract>A sample style that just prints out a 6px wide red square</Abstract>

      <FeatureTypeStyle>
        <Rule>
          <Title>Red square</Title>
          <PointSymbolizer>
            <Graphic>
              <Mark>
                <WellKnownName>square</WellKnownName>
                <Fill>
                  <CssParameter name="fill">#FF0000</CssParameter>
                </Fill>
              </Mark>
              <Size>6</Size>
            </Graphic>
          </PointSymbolizer>
        </Rule>

      </FeatureTypeStyle>
    </UserStyle>
  </NamedLayer>
</StyledLayerDescriptor>

该样式下渲染结果如下图:
默认样式下渲染结果

需动态修改状态下的SLD

在需修改的关键点处已标明注释

<?xml version="1.0" encoding="ISO-8859-1"?>
<StyledLayerDescriptor version="1.0.0" xmlns="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc"
  xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd">
  <NamedLayer>
    <UserStyle>
      <Title>Default point</Title>
      <Abstract>A sample style that just prints out a 6px wide red square</Abstract>

      <FeatureTypeStyle>
        <Rule>
          <Title>Red square</Title>
          <PointSymbolizer>
            <Graphic>
              <Mark>
                <WellKnownName>
                 <!--此处将点符号类型改为函数类型的-->
                  <ogc:Function name="env">
                    <!--name为前端调用时符号类型的参数名-->
                      <ogc:Literal>name</ogc:Literal>
                      <!--默认符号类型-->
                      <ogc:Literal>square</ogc:Literal>
                   </ogc:Function>
                </WellKnownName>
                <Fill>
                  <CssParameter name="fill">
				  <!--此处将颜色值改为函数类型的-->
                    #<ogc:Function name="env">
					  <!--color为前端调用时颜色的参数名-->
                      <ogc:Literal>color</ogc:Literal>
					  <!--默认颜色值-->
                      <ogc:Literal>FF0000</ogc:Literal>
                   </ogc:Function>
                  </CssParameter>
                </Fill>
              </Mark>
              <Size>
			     <!--此处将大小改为函数类型的-->
                 <ogc:Function name="env">
				    <!--size为前端调用时符号大小的参数名-->
                    <ogc:Literal>size</ogc:Literal>
					<!--默认大小-->
                    <ogc:Literal>6</ogc:Literal>
                 </ogc:Function>
              </Size>
            </Graphic>
          </PointSymbolizer>
        </Rule>

      </FeatureTypeStyle>
    </UserStyle>
  </NamedLayer>
</StyledLayerDescriptor>
OpenLayers调用核心代码
var raster = new ol.layer.Tile({
      source: new ol.source.TileWMS({
		url: 'geoserver 服务地址',
			params: { 
				LAYERS: '图层名称', 
				VERSION: "1.1.1", 
				env:'color:00FF00;name:triangle;size:12'  //重点处:修改点状符号为:绿色、三角形、大小为12						
			}
		})
    });

其渲染结果如图所示:
动态渲染结果

扫描下方二维码,关注微信公众号,精彩内容同步更新
微信公众号.jpg

<think>好的,我需要帮用户找到关于如何使用OpenLayersGeoServer实现地图交互功能的教程或示例。用户提到了引用[1]和[2],其中引用[2]提到了使用WFS服务实现图层新增功能,这应该和交互相关。首先,我应该回顾用户提供的引用内容,确保答案准确。 用户的需求是地图交互功能,比如点击、绘制、编辑等。GeoServer通常提供WMS和WFS服务,WMS用于显示地图,而WFS支持事务操作,适合交互。所以需要结合OpenLayers的交互控件和GeoServer的WFS服务。 接下来,我需要整理实现步骤。首先,发布图层到GeoServer,确保启用WFS。然后,在OpenLayers中加载WMS作为底图,同时使用WFS-T(事务支持)来允许数据编辑。需要示例代码,展示如何初始化地图,添加交互控件如Select、Draw、Modify等。 然后,考虑用户可能需要的相关功能,比如点击查询、要素编辑、数据保存等。引用[2]已经提到了新增功能,可能包括绘制新要素并提交到GeoServer。需要确保代码示例正确,使用正确的WFS端点,并处理事务请求。 还要检查是否需要处理跨域问题,比如配置GeoServer的CORS设置。另外,用户可能需要了解如何配置GeoServer的数据存储,以及OpenLayers中如何与WFS服务交互。 最后,生成相关问题,帮助用户深入理解,比如性能优化、高级交互功能、安全设置等。确保回答结构清晰,分步骤说明,并提供可运行的代码示例,引用用户提供的参考资料。</think>以下是结合OpenLayersGeoServer实现地图交互功能的完整实现方案,包含核心代码示例和关键配置步骤: ### 一、基础环境搭建 1. 在GeoServer发布WMS/WFS服务 - 确保数据存储已正确配置 - 发布图层时勾选WFS服务选项 - 在"服务"→"WFS"设置中启用事务支持(WFS-T) 2. OpenLayers基础地图初始化 ```javascript import Map from 'ol/Map'; import View from 'ol/View'; import TileLayer from 'ol/layer/Tile'; import OSM from 'ol/source/OSM'; const map = new Map({ target: 'map', layers: [ new TileLayer({ source: new OSM() }) ], view: new View({ center: [0, 0], zoom: 2 }) }); ``` ### 二、核心交互功能实现 #### 1. 要素点击查询(GetFeatureInfo) ```javascript import WMSGetFeatureInfo from 'ol/format/WMSGetFeatureInfo'; map.on('singleclick', function(evt) { const view = map.getView(); const url = 'http://localhost:8080/geoserver/wms'; const params = { INFO_FORMAT: 'application/json', FEATURE_COUNT: 10, QUERY_LAYERS: 'workspace:layername' }; const parser = new WMSGetFeatureInfo(); fetch(url + '?REQUEST=GetFeatureInfo' + '&SERVICE=WMS' + '&VERSION=1.3.0' + '&CRS=' + view.getProjection().getCode() + '&WIDTH=' + map.getSize()[0] + '&HEIGHT=' + map.getSize()[1] + '&BBOX=' + view.calculateExtent().join(',') + '&I=' + Math.round(evt.pixel[0]) + '&J=' + Math.round(evt.pixel[1]) + formatParams(params)) .then(response => response.json()) .then(data => { console.log('查询结果:', parser.readFeatures(data)); }); }); ``` #### 2. 要素编辑(WFS-T) ```javascript import VectorLayer from 'ol/layer/Vector'; import VectorSource from 'ol/source/Vector'; import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style'; import { Draw, Modify, Select } from 'ol/interaction'; import GeoJSON from 'ol/format/GeoJSON'; // 创建矢量图层 const vectorSource = new VectorSource({ format: new GeoJSON(), url: function(extent) { return 'http://localhost:8080/geoserver/wfs?service=WFS&' + 'version=1.1.0&request=GetFeature&typeName=workspace:layername&' + 'outputFormat=application/json&srsname=EPSG:3857'; }, strategy: 'all' }); const vectorLayer = new VectorLayer({ source: vectorSource, style: new Style({ /* 样式配置 */ }) }); // 添加交互控件 const draw = new Draw({ source: vectorSource, type: 'Polygon' }); const select = new Select(); const modify = new Modify({ features: select.getFeatures() }); map.addInteraction(draw); map.addInteraction(select); map.addInteraction(modify); // 保存修改 document.getElementById('save').addEventListener('click', function() { const format = new GeoJSON(); const features = vectorSource.getFeatures(); const serializer = new XMLSerializer(); const transaction = '<wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" ' + 'xmlns:gml="http://www.opengis.net/gml" ' + 'xmlns:workspace="http://workspace" ' + 'service="WFS" version="1.1.0">' + '<wfs:Update typeName="workspace:layername">' + // 生成更新内容 '</wfs:Update>' + '</wfs:Transaction>'; fetch('http://localhost:8080/geoserver/wfs', { method: 'POST', body: transaction }).then(response => { // 处理响应 }); }); ``` ### 三、关键配置注意事项 1. GeoServer端需要: - 开启CORS支持(jetty-web.xml添加跨域头) - 设置数据存储的写权限 - 配置用户权限(如有安全需求) 2. OpenLayers开发需要: ```bash npm install ol @geoapify/geocoder-autocomplete ``` ### 四、进阶交互功能扩展 1. 实时要素过滤 ```javascript vectorSource.setUrl(function(extent) { return 'http://geoserver/wfs?filter=' + encodeURIComponent( '<Filter xmlns="http://www.opengis.net/ogc">' + '<PropertyIsEqualTo>' + '<PropertyName>status</PropertyName>' + '<Literal>active</Literal>' + '</PropertyIsEqualTo>' + '</Filter>' ); }); ``` 2. 空间分析交互 ```javascript import { buffer } from 'ol/extent'; const bufferInteraction = new Draw({ type: 'Circle', geometryFunction: function(coordinates, geometry) { if (!geometry) geometry = new Polygon([]); const center = fromLonLat(coordinates[0]); const radius = coordinates[1][0] - coordinates[0][0]; return buffer(center, radius); } }); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值