GIS N_GIS 核心知识

GeoServer

GeoServer 是一款JAVA编写的、开源的、用于共享地理空间数据的软件服务器. GeoServer 实现了 开放地理空间信息联盟(OGC )标准下WFS、WMS、WCS、WMTS 等格式的发布.

官网- https://geoserver.org/ 下载页 - https://geoserver.org/release/stable/ https://docs.geoserver.org/2.25.x/en/user/index.html

Platform Independent Binary: Operating system independent runnable binary.(独立与操作系统可单独运行) Windows Installer: Windows安装版,安装过程中可以设置端口、jre路径、账号密码等. Web Archive: Web 归档版本(War包),用于打包为servlet与 Apache Tomcat 和 Jetty 等服务器一起使用

quickstart

web-admin-quickstart

Navigate to the upper right of the web interface to log into GeoServer. The default administration credentials are:

User name: admin Password: geoserver

图层发布

  1. 添加工作空间 填写名称和URI. 其中,名称用作唯一标识,命名要有意义. 第二个URI可以随便填写,也是用于标识作用 勾选 WMS, WMTS !

  2. 添加新的存储仓库.

配置数据来源, 支持:

  • Directory of spatial files (shapefiles) - Takes a directory of shapefiles and exposes it as a data store//即shapefiles文件
  • Shapefile - ESRI(tm) Shapefiles (*.shp) //单个.shp文件
  • GeoTIFF - Tagged Image File Format with Geographic information //tif文件

连接参数 选择文件 (文件要放到 ./data/data/ 目录下) odm_orthophoto.original.tif

  1. 发布 以工作空间:mytest , 示例 访问地址: http://127.0.0.1:8080/geoserver/mytest/wms

  2. 新建图层

注意 坐标参考系统(EPSG) 参数

本机SRS 是指地图数据本身的坐标参考系统,这是由地图数据本身的属性决定的,也是不可修改的. GeoServer会自动从数据文件中读取这一信息. 相对应的Native Bounding Box则是根据本机SRS自动计算出来的边框,我们点击从数据中计算就能计算出来边框范围.

定义SRS 是指我们自己想要定义显示地图数据的坐标参考系统. 强制申明会让自定义SRS覆盖本机SRS. 对于国内用户来说

常用的坐标系统可以通过键入 4326 进行查找选择. 选择确定后 通过点击“compute from nativ bounds”可以计算出在这个坐标系统下的边界.

Bounding 参数 Native Bounding Box 这里可以看到图层的经纬度范围

另外 高德 只支持 EPSG:3857 坐标系统的图层. 天地图 只支持 EPSG:900913

踩坑指南

Failed to encode the PNG?

Failed to encode the PNG Could not find a scanline extractor for PlanarImage

https://gis.stackexchange.com/questions/371983/geoserver-wms-only-works-in-jpeg-format-not-png 貌似时色彩空间的问题 ArcMap 图层Data 导出TIF 时, 勾选 Output Raster , 强制RGB色彩, 它默认是的CMYK?

跨域头

Geoserver安装目录 \webapps\geoserver\WEB-INF\web.xml文件,找到

Uncomment following filter to enable CORS in Tomcat. Do not forget the second config block further down. 把跨域过滤器 配置启用 注释放开 (Tomcat) Uncomment following filter to enable CORS 把跨域过滤器映射配置 注释放开

<filter>
	  <filter-name>cross-origin</filter-name>
	  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
	  <!-- 配置允许的 HTTP 头 -->
	  <init-param>
	    <param-name>cors.allowed.headers</param-name>
	    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization</param-value>
	  </init-param>
	  <!-- 配置允许的 HTTP 方法 -->
	  <init-param>
	    <param-name>cors.allowed.methods</param-name>
	    <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
	  </init-param>
	  <!-- 配置允许的源(域名) -->
	  <init-param>
	    <param-name>cors.allowed.origins</param-name>
	    <param-value>*</param-value>
	  </init-param>
	  <!-- 是否允许携带凭证(cookies等) -->
	  <init-param>
	    <param-name>cors.support.credentials</param-name>
	    <param-value>false</param-value>
	  </init-param>
	  <!-- 预检请求有效期(秒) -->
	  <init-param>
	    <param-name>cors.preflight.maxage</param-name>
	    <param-value>1800</param-value>
	  </init-param>
</filter>
 
   <!-- Uncomment following filter to enable CORS   -->
    <filter-mapping>
        <filter-name>cross-origin</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
缓存头
  1. 打开Geoserver的管理界面,并进入“图层”页面。
  2. 点击发布标签,就可以看到Caching Settings
WFS查询数据是非经纬度?

EPSG:4326 空间坐标方才返回的是经纬度数据,

EPSG:3857 支持

高德 只支持 EPSG:3857,因此需要增加一个 Gridset

Gridsets,添加18级level,level 名改成高德要的那样,18级不够也可以再加 回到 Tile Caching > Tile LayersTile Layers

获取服务地址

在主页 GeoServer Web Map Tile Service A compliant implementation of WMTS service.

常用地图API加载

高德API

WMS

let wms_opts = {
  url : "http://127.0.0.1:8080/geoserver/ows",
  params :{
    layers: 'mytest:tdts',
    Service: 'WMS',
    Request: 'GetMap',
    Version: '1.1.1',
    Format: 'image/png',
    zooms: [1,32]
  }
}
let wms = new AMap.TileLayer.WMS(wms_opts)
map.add(wms);

天地图API

 
let wms_opts = {
	url : "http://192.168.20.130:8080/geoserver/ows",
	params :{
		// layers: 'sny:乔木林地', //900913
		layers: 'sny:乔木林地_4326',
		Service: 'WMS',
		Request: 'GetMap',
		Version: '1.1.1',
		format: 'image/png',
		transparent:true,
	}
}
wmsLayer = new T.TileLayer.WMS(wms_opts.url, wms_opts.params)
console.log( " 加载 wmsLayer = %o", wmsLayer);
map.addLayer(wmsLayer);

OpenLayer API

 
// 天地图 卫星图 WMTS 
// var url = "http://t0.tianditu.gov.cn/img_w/wmts?" +
//     "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
//     "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=c94ca7ff1fda359919b7132d1307ed62";
// var layer =new ol.layer.Tile({
//     source: new ol.source.XYZ({
//         url: url,
//     }),
//     name: "BaseMap",
// })
 
////////////////// wms
 
var wms = new ol.layer.Tile({
	source: new ol.source.TileWMS({
		//url : "http://121.32.129.19:9977/geoserver/ows",
		url:"http://192.168.40.112:8080/geoserver/ows",
		crossOrigin: 'anonymous',
		attributions: ' ',
		params :{
			layers: 'sny:zcgy_1_ex',
			Service: 'WMS',
			Request: 'GetMap',
			Version: '1.1.1',
			format: 'image/png',
			transparent:true,
		},
		serverType: 'mapserver',
	}),
});
map.addLayer(wms)

SLD - Styled Layer Descriptor

SLD是风格化图层描述器(Styled Layer Descriptor)的简称,是2005年OGC提出的一个标准,这个标准在一定条件下允许WMS服务器对地图可视化的表现形式进行扩展。

在 geoserver 中添加SLD : styles -> - Add a new style 在 geoserver 中给图层设置默认 style: Layers > 对应图层 > Publishing > Default Style

For QGIS

右键图层 → 属性 → 符号化; QGIS 可以基于分类, 规则, 表达式 定义

分类符号化(Categorized)

1. 右键图层 → 属性 → 符号化
2. 在顶部下拉菜单中选择"分类"
3. 选择要分类的字段
4. 点击"classify"按钮 
5. 定义每个分类的颜色
6. 点击"应用"

导出

1. 右键点击图层 → 属性
2. 选择"符号化"选项卡
3. 设置好样式后,点击左下角"样式"按钮
4. 选择"保存样式" → 选择"SLD格式" (*.sld)
5. 保存文件

一个依据 DLMC 属性决定它样式的示例:

<?xml version="1.0" encoding="UTF-8"?>
<StyledLayerDescriptor xmlns="http://www.opengis.net/sld" version="1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd" xmlns:se="http://www.opengis.net/se" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink">
  <NamedLayer>
    <se:Name>tdlylx_2022_all</se:Name>
    <UserStyle>
      <se:Name>tdlylx_2022_all</se:Name>
      <se:FeatureTypeStyle>
        <se:Rule>
          <se:Name>茶园</se:Name>
          <se:Description>
            <se:Title>茶园</se:Title>
          </se:Description>
          <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
            <ogc:PropertyIsEqualTo>
              <ogc:PropertyName>DLMC</ogc:PropertyName>
              <ogc:Literal>茶园</ogc:Literal>
            </ogc:PropertyIsEqualTo>
          </ogc:Filter>
          <se:PolygonSymbolizer>
            <se:Fill>
              <se:SvgParameter name="fill">#49ec0d</se:SvgParameter>
            </se:Fill>
            <se:Stroke>
              <se:SvgParameter name="stroke">#232323</se:SvgParameter>
              <se:SvgParameter name="stroke-width">1</se:SvgParameter>
              <se:SvgParameter name="stroke-linejoin">bevel</se:SvgParameter>
            </se:Stroke>
          </se:PolygonSymbolizer>
        </se:Rule>
        
        <se:Rule>
          <se:Name>干渠</se:Name>
          <se:Description>
            <se:Title>干渠</se:Title>
          </se:Description>
          <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
            <ogc:PropertyIsEqualTo>
              <ogc:PropertyName>DLMC</ogc:PropertyName>
              <ogc:Literal>干渠</ogc:Literal>
            </ogc:PropertyIsEqualTo>
          </ogc:Filter>
          <se:PolygonSymbolizer>
            <se:Fill>
              <se:SvgParameter name="fill">#edaa5c</se:SvgParameter>
            </se:Fill>
            <se:Stroke>
              <se:SvgParameter name="stroke">#232323</se:SvgParameter>
              <se:SvgParameter name="stroke-width">1</se:SvgParameter>
              <se:SvgParameter name="stroke-linejoin">bevel</se:SvgParameter>
            </se:Stroke>
          </se:PolygonSymbolizer>
        </se:Rule>
    
          <se:PolygonSymbolizer>
            <se:Fill>
              <se:SvgParameter name="fill">#d360ad</se:SvgParameter>
            </se:Fill>
            <se:Stroke>
              <se:SvgParameter name="stroke">#232323</se:SvgParameter>
              <se:SvgParameter name="stroke-width">1</se:SvgParameter>
              <se:SvgParameter name="stroke-linejoin">bevel</se:SvgParameter>
            </se:Stroke>
          </se:PolygonSymbolizer>
        </se:Rule>
      </se:FeatureTypeStyle>
    </UserStyle>
  </NamedLayer>
</StyledLayerDescriptor>
 

Layer Groups

https://www.osgeo.cn/geoserver-user-manual/data/webadmin/layergroups.html

图层组 图层组是一个容器,其中图层和其他图层组可以按层次结构组织。在WMS请求中,可以用单个名称引用层组。这允许更简单的请求,因为可以指定一个层而不是多个单独的层。图层组还提供其所包含图层的一致、固定顺序,并可以为图层指定备用(非默认)样式。

Layer Groups Add new layer group

层组模式

mode. 有5个可用值:

单一的:图层组显示为具有名称的单个图层,充当图层列表的别名。这些层仍然显示为WMS功能文档中的顶级条目(除非由树组显式引用)。 不透明容器:图层组显示为具有名称的单个图层,充当图层列表的别名。但是,其中包含的层和子组不会显示在capabilities文档中(除非由树组显式引用),也不会在WMS调用和WMS capabilities文档中单独使用,而只能作为组的一部分。 命名树 :层组可以由一个名称引用,但也会在功能文档中公开其嵌套的层和组。 容器树 :层组在功能文档中公开,但没有名称,因此无法单独呈现。这在WMS规范中称为“包含类别”。 地球观测树 :为管理WMS地球观测要求而创建的特殊类型的组。此组不呈现其嵌套的层和组,而只呈现名为“根层”的“预览层”。选择此模式后,配置UI中将显示一个新字段“根层”。

特性维度详细说明
1. 逻辑容器图层组本身不是数据,而是一个引用列表。它将多个独立的图层(Layers)或其他图层组组合在一起,形成一个虚拟的“地图文档”。
2. 单一入口 (简化调用)最大优势。客户端只需请求一个图层名(即组名),即可获取组内所有图层叠加后的结果。极大简化了前端代码和 WMS 请求 URL。
3. 强制叠加顺序在组内定义的图层顺序是固定的。无论客户端如何请求,GeoServer 都会严格按照定义的下上顺序进行渲染(例如:底图在下,注记在上)。
4. 自动坐标对齐组内可以包含不同坐标系(SRS)的图层。GeoServer 会在服务器端自动将它们重投影到组设定的坐标系(或请求指定的坐标系)中进行合成,客户端无需处理投影转换。
5. 统一边界 (Bounding Box)图层组拥有自己独立的边界框(通常是所有子图层边界的并集)。客户端请求该组时,默认基于这个联合范围,避免了手动计算多图层范围的麻烦。
6. 样式隔离与复用组内的每个图层依然保持自己独立的样式(SLD)。修改组不会改变子图层的样式,但可以在组级别设置一些全局渲染参数(如透明度混合模式)。
7. 嵌套支持支持嵌套:一个图层组可以包含另一个图层组。这使得构建复杂的地图层级结构(如“全国图”包含“各省组”,“各省组”包含“具体图层”)成为可能。
8. 不支持CQLCQL_FILTER 时,GeoServer 无法判断这个过滤条件应该应用到组内的哪一个具体图层

Rest APIs

https://docs.geoserver.org/stable/en/user/rest/index.html

Stores 管理

A data store contains vector format spatial data. It can be a file (such as a shapefile), a database (such as PostGIS), or a server (such as a remote Web Feature Service).

https://docs.geoserver.org/latest/en/api/#1.0.0/datastores.yaml

创建 for GeoPackage

The data store body information to upload. The contents of the connection parameters will differ depending on the type of data store being added.

Examples:

  • application/xml:
<dataStore>
  <name>nyc</name>
  <connectionParameters>
	<database>file:///path/to/nyc.gpkg</database>
	<dbtype>geopkg</dbtype>
  </connectionParameters>
</dataStore>
  • application/json:
{
  "dataStore": {
	"name": "nyc",
	"connectionParameters": {
	  "entry": [
		{"@key":"database","$":"file:///path/to/nyc.gpkg"},
		{"@key":"dbtype","$":"geopkg"}
	  ]
	}
  }
}

Connection Parameters:

keydescriptionleveltyperequireddefault
Primary key metadata tableThe optional table containing primary key structure and sequence associations. Can be expressed as ‘schema.name’ or just ‘name’userStringFalse
Callback factoryName of JDBCReaderCallbackFactory to enable on the data storeuserStringFalse
Evictor tests per runnumber of connections checked by the idle connection evictor for each of its runs (defaults to 3)userIntegerFalse3
databaseDatabaseuserFileTrue
Batch insert sizeNumber of records inserted in the same batch (default, 1). For optimal performance, set to 100.userIntegerFalse1
fetch sizenumber of records read with each interaction with the DBMSuserIntegerFalse1000
Connection timeoutnumber of seconds the connection pool will wait before timing out attempting to get a new connection (default, 20 seconds)userIntegerFalse20
namespaceNamespace prefixuserStringFalse
max connectionsmaximum number of open connectionsuserIntegerFalse10
Test while idlePeriodically test the connections are still valid also while idle in the pooluserBooleanFalseTrue
Max connection idle timenumber of seconds a connection needs to stay idle for the evictor to consider closing ituserIntegerFalse300
Session startup SQLSQL statement executed when the connection is grabbed from the pooluserStringFalse
validate connectionscheck connection is alive before using ituserBooleanFalseTrue
dbtypeTypeprogramStringTruegeopkg
passwdpassword used to loginuserStringFalse
Expose primary keysExpose primary key columns as attributes of the feature typeuserBooleanFalseFalse
min connectionsminimum number of pooled connectionsuserIntegerFalse1
Evictor run periodicitynumber of seconds between idle object evictor runs (default, 300 seconds)userIntegerFalse300
Session close-up SQLSQL statement executed when the connection is released to the pooluserStringFalse
useruser name to login asuserStringFalse

创建 for Shapefile

Create a new data store
POST /workspaces/{workspaceName}/datastores

  • Shapefile Examples:
  • application/xml:
<dataStore>
  <name>nyc</name>
  <connectionParameters>
	<url>file:/path/to/nyc.shp</url>
  </connectionParameters>
</dataStore>
  • application/json:
{
  "dataStore": {
	"name": "nyc",
	"connectionParameters": {
	  "entry": [
		{"@key":"url","$":"file:/path/to/nyc.shp"}
	  ]
	}
  }
}

Connection Parameters:

keydescriptionleveltyperequireddefault
cache and reuse memory mapsonly memory map a file one, then cache and reuse the mapadvancedBooleanFalseTrue
namespaceURI to the namespaceadvancedURIFalse
filetypeDiscriminator for directory storesprogramStringFalseshapefile
charsetcharacter used to decode strings from the DBF fileadvancedCharsetFalseISO-8859-1
create spatial indexenable/disable the automatic creation of spatial indexadvancedBooleanFalseTrue
fstypeEnable using a setting of ‘shape’.advancedStringFalseshape
urlurl to a .shp fileuserURLTrue
enable spatial indexenable/disable the use of spatial index for local shapefilesadvancedBooleanFalseTrue
memory mapped bufferenable/disable the use of memory-mapped IOadvancedBooleanFalseFalse
timezonetime zone used to read dates from the DBF fileadvancedTimeZoneFalsePacific Standard Time
  • Directory of spatial files (shapefiles) Examples:
    • application/xml:
<dataStore>
  <name>nyc</name>
  <connectionParameters>
	<url>file:/path/to/directory</url>
  </connectionParameters>
</dataStore>
  • application/json:
{
  "dataStore": {
	"name": "nyc",
	"connectionParameters": {
	  "entry": [
		{"@key":"url","$":"file:/path/to/directory"}
	  ]
	}
  }
}

Connection Parameters:

keydescriptionleveltyperequireddefault
cache and reuse memory mapsonly memory map a file one, then cache and reuse the mapadvancedBooleanFalseTrue
namespaceURI to the namespaceadvancedURIFalse
filetypeDiscriminator for directory storesprogramStringFalseshapefile
charsetcharacter used to decode strings from the DBF fileadvancedCharsetFalseISO-8859-1
create spatial indexenable/disable the automatic creation of spatial indexadvancedBooleanFalseTrue
fstypeEnable using a setting of ‘shape’.advancedStringFalseshape
urlurl to a .shp fileuserURLTrue
enable spatial indexenable/disable the use of spatial index for local shapefilesadvancedBooleanFalseTrue
memory mapped bufferenable/disable the use of memory-mapped IOadvancedBooleanFalseFalse
timezonetime zone used to read dates from the DBF fileadvancedTimeZoneFalsePacific Standard Time

Layers 管理

A layer is a published resource (feature type or coverage). http://docs.geoserver.org/latest/en/api/#1.0.0/layers.yaml

发布图层

发布图层, 其实是通过 https://docs.geoserver.org/stable/en/user/rest/api/featuretypes.html

切图(WMTS)

WMS 是实时生成的太卡了, 切图一下图转成 WMTS 服务, GeoServer 是有这个功能的

当请求的URL中加上 gwc/service 后,便开启瓦片缓存服务了

示例带缓存的请求

http://192.168.50.191:8080/geoserver/sny/gwc/service/wmts?layer=sny%3Ass_sh_20241010_1000&style=&tilematrixset=EPSG%3A4326&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix=EPSG%3A4326%3A18&TileCol=428083&TileRow=97850

新建切片策略

  1. Gridsets Create a new gridset
  2. 选择数据的空间参考: (EPSG:3857)
  3. 切图范围: 让它适配最大 (Compute from maximum extent of CRS) 瓦片大小
  4. 添加级别: 最大!

图层 关联 切片策略

Layers 目标图层 Tile cacheing > Add grid subset(选中该策略)

设置/执行任务

Tile Layers 目标图层 > (Actions列) Seed/Truncate

Create a new task:

  1. Number of tasks to use:该选项表示可以用多少个任务来切图,类似于多线程的模式,如果电脑性能允许的情况下,可以适当增加这个数量,这样切片的速度会更快些;如果电脑性能不高的话,数值太大的话,反而可能会影响性能。
  2. Type of operation:操作类型,包括:Reseed-regenerate all tiles(重新进行完整的切片操作)、Seed-generate missing tiles(只对缺失的部分进行切片)、Truncate-remove tiles(清空切片数据)。
  3. Grid Set:选择切片的Gridset,和图层配置时候设置的Gridset有关。
  4. Format:切片的数据格式。比如image/png。
  5. Tile failure retries: -1 直接失败?

默认位置在 /opt/apache-tomcat-8.5.63/temp/geowebcache

/opt/apache-tomcat-8.5.63/webapps/geoserver/WEB-INF/web.xml 可配置切片缓存目录

<context-param>
	<param-name>GEOWEBCACHE_CACHE_DIR</param-name>
	<param-value>D:\software\Tomcat\apache-tomcat-8.5.35\webapps\geoserver\data\gwc</param-value>
</context-param>
 

测试验证

开启 wmts 服务能力 任务完成后, 可以在图层预览: Tile Layers 目标图层 Select One

N_GIS可视化开发 openlayer

用户认证

1.创建用户和角色

  • 在 “Security” 下,选择 “Users, Groups, and Roles
  • 在 Roles 中 Add new role > 创建新 web_role 角色
  • 在 Users, Groups, Roles > 创建新的用户,并为其分配角色。

2.设置角色访问权限

  • 在 “Security” 下,选择 “Data”。
  • 在 Data Security Add new rule
  • 你可以为特定的图层或工作区指定哪些角色可以读取、写入或管理。
  • 另外需要在 Workspaces > Edit Workspace 中的 Security 也配置角色访问权限

3.Service 认证

  • 在 “Security” 下,选择 “Service Security”。
  • 在这里,你可以为特定的 Service(如 WMS, WFS, WCS) Method (如 GetMap, GetStyle)设置访问权限。

4. HTTP Basic 认证

拼接成 用户名:密码 格式

为避免账号密码在URL中明文传输,将账号密码通过拼接使用Base64进行编码,通过headers传参进行基本认证

Authorization:Basic d2ViX3VzZXI6WUpBS0wzUE92MHN2d3JIb2Y=

在Openlayer 中

var source = new ol.source.TileWMS({
	url:"http://192.168.40.112:8080/geoserver/ows",
	crossOrigin: 'anonymous',
	attributions: ' ',
	params: params,
	serverType: 'mapserver',
	tileLoadFunction: function(tile, src) {
		fetch(src, {
			headers: {
				'Authorization': 'Basic xxxxxxxpxxxxxxb2Y=',
			}
		})
		.then(response => response.blob())
		.then(blob => {
		const url = URL.createObjectURL(blob);
			tile.getImage().src = url;
		})
		.catch(err => console.error(err));
	}
})