添加geotools

This commit is contained in:
qiusj 2023-11-28 17:09:45 +08:00
parent 1690647e0a
commit 5e767e2121
9 changed files with 569 additions and 0 deletions

View File

@ -0,0 +1,21 @@
---
title: Qgis制作网格
date: 2023-11-18
author: ac
categries:
- GIS
tags:
- Qgis
- grid
---
### Qgis 制作网格
#### 1. 数据准备
https://t{s}.tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=ea3530e6803b44025cfa81500eaae01f
————————————————
版权声明本文为CSDN博主「wu_223」的原创文章遵循CC 4.0 BY-SA版权协议转载请附上原文出处链接及本声明。
原文链接https://blog.csdn.net/qq_34790644/article/details/86535456
http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=ea3530e6803b44025cfa81500eaae01f

View File

@ -0,0 +1,154 @@
---
title: GeoTools-快速起步
date: 2023-11-19
author: ac
categries:
- GIS
tags:
- GeoTools
---
### GeoTools-快速起步
#### 1.maven构建
```shell
mvn archetype:generate -DgroupId=org.geotools -DartifactId=tutorial -Dversion=1.0-SNAPSHOT -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart
```
> archetype的意思就是模板原型的意思原型是一个Maven项目模板工具包。
![image-20231120113304413](./images/image-20231120113304413.png)
#### 2. 添加依赖
```xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<!-- 指定geotools的版本号-->
<geotools.version>31-SNAPSHOT</geotools.version>
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
<!-- 添加仓库地址-->
<repositories>
<repository>
<id>osgeo</id>
<name>OSGeo Release Repository</name>
<url>https://repo.osgeo.org/repository/release/</url>
<snapshots><enabled>false</enabled></snapshots>
<releases><enabled>true</enabled></releases>
</repository>
<repository>
<id>osgeo-snapshot</id>
<name>OSGeo Snapshot Repository</name>
<url>https://repo.osgeo.org/repository/snapshot/</url>
<snapshots><enabled>true</enabled></snapshots>
<releases><enabled>false</enabled></releases>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-swing</artifactId>
<version>${geotools.version}</version>
</dependency>
</dependencies>
```
#### 3. 主程序
```java
import java.io.File;
import java.util.logging.Logger;
import org.geotools.api.data.FileDataStore;
import org.geotools.api.data.FileDataStoreFinder;
import org.geotools.api.data.SimpleFeatureSource;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.styling.SLD;
import org.geotools.api.style.Style;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.data.JFileDataStoreChooser;
/**
* Prompts the user for a shapefile and displays the contents on the screen in a map frame.
*
* <p>This is the GeoTools Quickstart application used in documentationa and tutorials. *
*/
public class Quickstart {
/**
* GeoTools Quickstart demo application.
* Prompts the user for a shapefile and displays its
* contents on the screen in a map frame
*/
public static void main(String[] args) throws Exception {
File file = JFileDataStoreChooser.showOpenFile("shp", null);
if (file == null) {
return;
}
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
// Create a map content and add our shapefile to it
MapContent map = new MapContent();
map.setTitle("Quickstart");
Style style = SLD.createSimpleStyle(featureSource.getSchema());
Layer layer = new FeatureLayer(featureSource, style);
map.addLayer(layer);
// Now display the map
JMapFrame.showMap(map);
}
}
```
选择一份`shp`文件程序会读取该文件添加到mapContent面板中。
<img src="./images/image-20231120142008338.png" alt="image-20231120142008338" style="zoom: 80%;" />
注意shp文件没有被加载到内存中而是每次需要时都从磁盘读取它。这种方式允许您处理大于内存的数据集。
#### 4. advance
为了更好的交互体验,我们可以通过`DataStoreFinder`获取数据源时添加额外的参数,如设置缓存、创建空间索引等方法来优化。
```java
File file = JFileDataStoreChooser.showOpenFile("shp", null);
Map<String, Object> params = new HashMap<>();
params.put("url", file.toURI().toURL());
params.put("create spatial index", true);
params.put("memory mapped buffer", true);
params.put("charset", "UTF-8");
DataStore store = DataStoreFinder.getDataStore(params);
SimpleFeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
```

View File

@ -0,0 +1,261 @@
---
title: GeoTools-创建要素Feature
date: 2023-11-19
author: ac
categries:
- GIS
tags:
- GeoTools
---
### GeoTools-创建要素
> csv2shp通过csv转点shp文件学习
>
> 1. 如何创建`FeatureType`、`FeatureCollection`和`Features`
> 2. 通过`GeometryFactory`构建`Points`点集;
> 3. 输出shp文件
> 4. 设置投影。
#### 1.数据准备
下载一份[csv文件](https://docs.geotools.org/latest/userguide/_downloads/d4bcf8751cc3f33a9fb673902a960e53/locations.csv) ,内容格式如下:
```text
LAT, LON, CITY, NUMBER
46.066667, 11.116667, Trento, 140
44.9441, -93.0852, St Paul, 125
13.752222, 100.493889, Bangkok, 150
45.420833, -75.69, Ottawa, 200
44.9801, -93.251867, Minneapolis, 350
46.519833, 6.6335, Lausanne, 560
48.428611, -123.365556, Victoria, 721
-33.925278, 18.423889, Cape Town, 550
-33.859972, 151.211111, Sydney, 436
41.383333, 2.183333, Barcelona, 914
39.739167, -104.984722, Denver, 869
52.95, -1.133333, Nottingham, 800
45.52, -122.681944, Portland, 840
37.5667,129.681944,Seoul,473
50.733992,7.099814,Bonn,700,2016
```
#### 2.添加依赖
```xml
<dependencies>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>${geotools.version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>osgeo</id>
<name>OSGeo Release Repository</name>
<url>https://repo.osgeo.org/repository/release/</url>
<snapshots><enabled>false</enabled></snapshots>
<releases><enabled>true</enabled></releases>
</repository>
<repository>
<id>osgeo-snapshot</id>
<name>OSGeo Snapshot Repository</name>
<url>https://repo.osgeo.org/repository/snapshot/</url>
<snapshots><enabled>true</enabled></snapshots>
<releases><enabled>false</enabled></releases>
</repository>
</repositories>
```
#### 3. 示例
```java
package learning;
import org.geotools.api.feature.simple.SimpleFeature;
import org.geotools.api.feature.simple.SimpleFeatureType;
import org.geotools.data.DataUtilities;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author ac
* @date 2023/11/20 15:44
*/
public class Csv2Shape {
public static void main(String[] args) throws Exception {
// Set cross-platform look & feel for compatability
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
File file = JFileDataStoreChooser.showOpenFile("csv", null);
if (file == null) {
return;
}
/*
* We use the DataUtilities class to create a FeatureType that will describe the data in our
* shapefile.
*
* See also the createFeatureType method below for another, more flexible approach.
*
* 通过 DataUtilities 创建 FeatureType 类似定义shp文件的名称、几何类型、属性字段、空间参考等信息。
*/
final SimpleFeatureType TYPE =
DataUtilities.createType(
"Location",
"the_geom:Point:srid=4326,"
+ // <- the geometry attribute: Point type
"name:String,"
+ // <- a String attribute
"number:Integer" // a number attribute
);
System.out.println("TYPE:" + TYPE);
/*
* A list to collect features as we create them.
*/
List<SimpleFeature> features = new ArrayList<>();
/*
* GeometryFactory will be used to create the geometry attribute of each feature,
* using a Point object for the location.
* 创建几何工厂实例,要素构建者实例
* 通过缓冲流一行行读取解析数据构建Point实例
*/
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
/* First line of the data file is the header */
String line = reader.readLine();
System.out.println("Header: " + line);
for (line = reader.readLine(); line != null; line = reader.readLine()) {
if (line.trim().length() > 0) { // skip blank lines
String[] tokens = line.split("\\,");
double latitude = Double.parseDouble(tokens[0]);
double longitude = Double.parseDouble(tokens[1]);
String name = tokens[2].trim();
int number = Integer.parseInt(tokens[3].trim());
/* Longitude (= x coord) first ! */
// 创建几何实例geometry - point
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
// 创建要素实例feature
// feature
// ↙ ↘
// geometry properties
featureBuilder.add(point);
featureBuilder.add(name);
featureBuilder.add(number);
SimpleFeature feature = featureBuilder.buildFeature(null);
features.add(feature);
}
}
}
/*
* Get an output file name and create the new shapefile
*
* 设置输出路径
*/
File newFile = getNewShapeFile(file);
// 创建数据存储工厂实例
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<>();
params.put("url", newFile.toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
// 创建新的数据存储会输出shp文件
ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
/*
* TYPE is used as a template to describe the file contents
* 添加类型描述
*/
newDataStore.createSchema(TYPE);
}
/**
* Prompt the user for the name and path to use for the output shapefile
* 弹窗让用户选择新生成的shp文件的保存位置
*
* @param csvFile the input csv file used to create a default shapefile name
* @return name and path for the shapefile as a new File object
*/
private static File getNewShapeFile(File csvFile) {
String path = csvFile.getAbsolutePath();
String newPath = path.substring(0, path.length() - 4) + ".shp";
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
chooser.setSelectedFile(new File(newPath));
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
// the user cancelled the dialog
System.exit(0);
}
File newFile = chooser.getSelectedFile();
if (newFile.equals(csvFile)) {
System.out.println("Error: cannot replace " + csvFile);
System.exit(0);
}
return newFile;
}
}
```
#### 参考文章
[1] Feature Tutorial https://docs.geotools.org/latest/userguide/tutorial/feature/csv2shp.html

View File

@ -0,0 +1,133 @@
---
title: GeoTools-简介
date: 2023-11-28
author: ac
categries:
- GIS
tags:
- GeoTools
---
### GeoTools-简介
### 1.简介
GeoTools是一个开源(LGPL) Java代码库它为地理空间数据的操作提供了符合标准的方法例如实现地理信息系统。GeoTools库数据结构基于开放地理空间联盟(OGC)规范。
了解GeoTools库是如何构建的这有助于您找出需要在应用程序中包含哪些jar。
### 2. GeoTools 库
![image-20231128145948967](./images/image-20231128145948967.png)
GeoTools库形成了一个软件“堆栈”每个模块都建立在前一个定义的模块之上。
“堆栈”的每一层都是建立在下一层之上的,例如:
- 如果要使用`Referencing` ,你需要先使用`gt-api`,`gt-metadata`,`gt-references`,为了确保`EPSG`codes的正确还需要使用一个插件`gt-epsg-hsql`来定义EPSG。
- 如果要使用`Coverage`,需要使用`gt-api`,`gt-metadata`,`gt-referencing(包含gt-epsg-hsql)`,`gt-main`和`gt-coverage`。为了充分利用Coverage模块我们使用了一个插件比如`gt-geotiff`来访问`GeoTIFF`文件。
`Maven`工具能够计算项目中需要的`jar`.
下面是各个模块的作用:
| Module | Purpose |
| :--------------- | :----------------------------------------------------------- |
| `gt-render` | Map API, with Java2D rendering engine for mapping. |
| `gt-jdbc` | Implements for accessing spatial database |
| `gt-xml` | Implements of common spatial XML formats |
| `gt-cql` | Implements of Common Query Language for filters |
| `gt-coverage` | Implementation for accessing raster information |
| `gt-main` | Data API, with default implementations of filter, feature, etc… |
| `gt-referencing` | Implementation of co-ordinate location and transformation |
| `gt-metadata` | Implementation of identification and description |
| `gt-api` | Definition of interfaces for common spatial concepts |
| `jts` | JTS Topology Suite (external library) implementing Geometry |
### 3. GeoTools 插件
GeoTools提供插件来支持额外的数据格式和不同的坐标参考系统等功能。
| Module | JAR | Plugin |
| :--------------- | :------------------ | :------------------------------- |
| `gt-render` | | |
| `gt-jdbc` | `gt-jdbc-db2` | Geometry in DB2 |
| | `gt-jdbc-h2` | Pure Java “H2” database |
| | `gt-jdbc-mysql` | Geometry in MySQL |
| | `gt-jdbc-oracle` | Oracle SDO Geometry |
| | `gt-jdbc-postgis` | PostgreSQL extension PostGIS |
| | `gt-jdbc-sqlserver` | SQL Server |
| | `gt-jdbc-hana` | SAP HANA |
| `gt-xml` | | |
| `gt-cql` | | |
| `gt-main` | `gt-shape` | Shapefile read/write support |
| | `gt-wfs` | WFS read/write support |
| `gt-coverage` | `gt-geotiff` | GeoTIFF raster format |
| | `gt-arcgrid` | arcgrid format |
| | `gt-mif` | MIF format |
| | `gt-image` | JPG, PNG, TIFF formats |
| `gt-referencing` | `epsg-access` . | Official EPSG database in Access |
| | `epsg-hsql` | Pure Java port of EPSG database |
| | `epsg-wkt` | Lightweight copy of EPSG codes |
| | `epsg-postgresql` | PostgreSQL port of EPSG database |
| `gt-metadata` | | |
| `gt-api` | | |
| `jts` | | |
通常每个层至少需要一个插件才能让GeoTools做一些事情。
### 4.GeoTools 扩展
更进一步在GeoTools库的基础上实现了一些有趣的“扩展”。这些扩展提供了使用核心库的全部功能构建在GeoTools之上的额外功能。
![image-20231128165232067](./images/image-20231128165232067.png)
这些扩展相互独立,可能在您的应用程序中使用:
| JAR | Extension |
| :-------------- | :--------------------------------------------------- |
| `gt-app-schema` | Map from application schema to complex feature model |
| `gt-brewer` | Generation of styles using color brewer |
| `gt-complex` | Support for making custom complex feature model |
| `gt-graph` | Work with graph and network traversals |
| `gt-grid` | Dynamicly generate features from grid definiton |
| `gt-transform` | Transform features on the fly |
| `gt-wms` | Web Map Server client |
| `gt-wmts` | Web Map Tile Server client |
| `gt-xsd` | Parsing/Encoding for common OGC schemas |
### 5.XML
为了支持GeoTools中的XML模块我们以JAR形式捆绑了几个XML模式(以避免每次需要时都需要从Internet下载它们)。此外这些jar包含一个由Eclipse Modeling Framework生成的Java数据结构。
| JAR | Schema |
| :---------------- | :---------------------------- |
| `net.opengis.ows` | open web services schema |
| `net.opengis.wfs` | web feature service |
| `net.opengis.wps` | web processing service schema |
| `net.opengis.wcs` | web coverage service schema |
| `net.opengis.wfs` | web feature service schema |
| `org.w3.xlink` | XLink schema |
XSD解析器通过一系列XSD插件使用这些工具。这些插件指示如何使用Eclipse XSD库解析和编码附加内容以解析XML模式文档并提供“绑定”显示如何解析和编码Java类如String、Date、URL和Geometry。
| JAR | Bindings |
| :-------------- | :-------------------------------- |
| `gt-xsd-core` | Basic types defined by XML schema |
| `gt-xsd-fes` | filter 2.0 |
| `gt-xsd-filter` | filter (used by OGC CAT and WFS) |
| `gt-xsd-kml` | keyhole markup language |
| `gt-xsd-wfs` | web feature service |
| `gt-xsd-wps` | web processing service |
| `gt-xsd-gml3` | geographic markup language 3 |
| `gt-xsd-gml2` | geographic markup language 2 |
| `gt-xsd-ows` | open web services |
| `gt-xsd-wcs` | web coverage service |
| `gt-xsd-wms` | web map service |
| `gt-xsd-sld` | style layer descriptor |
#### 参考文章
[1] architecture https://docs.geotools.org/latest/userguide/welcome/architecture.html

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB