官方案例
依赖:
<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>
点
public class CSV2Shp {
private static SimpleFeatureType createFeatureType() {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Location");
builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
// add attributes in order
builder.add("the_geom", Point.class);
builder.length(15).add("Name", String.class); // <- 15 chars width for name field
builder.add("number", Integer.class);
// build the type
final SimpleFeatureType LOCATION = builder.buildFeatureType();
return LOCATION;
}
public static void main(String[] args) {
List<SimpleFeature> features = new ArrayList<>();
// 直接实例化GeometryFactory geometryFactory = new GeometryFactory();
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
SimpleFeatureType TYPE = createFeatureType();
// 要素创建,需要传入FeatureType
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
// 数据文件
File file = new File("E:\\DataofGeotools\\locations.csv");
// 读取文件
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 ! */
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
featureBuilder.add(point);
featureBuilder.add(name);
featureBuilder.add(number);
SimpleFeature feature = featureBuilder.buildFeature(null);
features.add(feature);
}
}
// 创建矢量文件
File shpFile = new File("E:\\DataofGeotools\\locations.shp");
// 保存数据工厂类
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
// 参数
Map<String,Serializable> params = new HashMap<>();
params.put("url",shpFile.toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
// 创建保存数据的对象
ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
newDataStore.createSchema(TYPE);
/*
* 指定事务
*/
Transaction transaction = new DefaultTransaction("create");
String typeName = newDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
SimpleFeatureType SHAPE_TYPE = featureSource.getSchema();
/*
* The Shapefile format has a couple limitations:
* - "the_geom" is always first, and used for the geometry attribute name
* - "the_geom" must be of type Point, MultiPoint, MuiltiLineString, MultiPolygon
* - Attribute names are limited in length
* - Not all data types are supported (example Timestamp represented as Date)
*
* Each data store has different limitations so check the resulting SimpleFeatureType.
*/
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
/*
* SimpleFeatureStore has a method to add features from a
* SimpleFeatureCollection object, so we use the ListFeatureCollection
* class to wrap our list of features.
*/
// 直接Features转为要素集合
SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
// 提交事务创建要素集
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
}
System.exit(0); // success!
} else {
System.out.println(typeName + " does not support read/write access");
System.exit(1);
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
自定义数据(面)
表结构
package com.geo.geotools.example;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKBReader;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import java.io.*;
import java.net.MalformedURLException;
import java.util.*;
/**
* @ClassName:
* @Description:(描述这个类的作用)
* @author: liyong
* @date:
* @Copyright:
*/
public class CSV2Polygon {
private static SimpleFeatureType createFeatureType() throws IOException {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("data");
builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
// add attributes in order
// 这个the_geom名称不能改变
builder.add("the_geom", MultiPolygon.class);
Map attributeMap = getAttribute("E:\\home\\dgis\\digitalmap\\data_jinjang.csv");
// build the type
Iterator<Map.Entry<String, Object>> iterator = attributeMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String,Object> entry = iterator.next();
builder.add(entry.getKey(),(Class) entry.getValue());
}
final SimpleFeatureType LOCATION = builder.buildFeatureType();
return LOCATION;
}
private static Map<String,Object> getAttribute(String filePath) throws IOException {
File data = new File(filePath);
BufferedReader br = new BufferedReader(new FileReader(data));
String header = br.readLine();
String[] attributes = header.split(",");
Map<String,Object> attributeMap = new HashMap<>();
for (String el : attributes) {
if (el.equals("buildingid"))continue;
attributeMap.put(el,String.class);
}
return attributeMap;
}
public static void main(String[] args) throws IOException {
{
List<SimpleFeature> features = new ArrayList<>();
// 直接实例化GeometryFactory geometryFactory = new GeometryFactory();
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
SimpleFeatureType TYPE = createFeatureType();
// 要素创建,需要传入FeatureType
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
// 数据文件
File file = new File("E:\\home\\dgis\\digitalmap\\data_jinjang.csv");
// 读取文件
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
/* First line of the data file is the header */
String line = reader.readLine();
for (line = reader.readLine(); line != null; line = reader.readLine()) {
if (line.trim().length() > 0) { // skip blank lines
String tokens[] = line.split("\\,");
WKBReader wkbReader = new WKBReader(geometryFactory);
MultiPolygon polygon = (MultiPolygon) wkbReader.read(WKBReader.hexToBytes(tokens[1]));
// 属性添加相加,添加后才有属性值,与simplefeaturetype需要一一对应
String name = tokens[2].trim();
int number = Integer.parseInt(tokens[3].trim());
featureBuilder.add(polygon);
featureBuilder.add(name);
featureBuilder.add(number);
SimpleFeature feature = featureBuilder.buildFeature(null);
features.add(feature);
}
}
// 创建矢量文件
File shpFile = new File("E:\\DataofGeotools\\data.shp");
// 保存数据工厂类
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
// 参数
Map<String,Serializable> params = new HashMap<>();
params.put("url",shpFile.toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
// 创建保存数据的对象
ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
newDataStore.createSchema(TYPE);
/*
* 指定事务
*/
Transaction transaction = new DefaultTransaction("create");
String typeName = newDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
SimpleFeatureType SHAPE_TYPE = featureSource.getSchema();
/*
* The Shapefile format has a couple limitations:
* - "the_geom" is always first, and used for the geometry attribute name
* - "the_geom" must be of type Point, MultiPoint, MuiltiLineString, MultiPolygon
* - Attribute names are limited in length
* - Not all data types are supported (example Timestamp represented as Date)
*
* Each data store has different limitations so check the resulting SimpleFeatureType.
*/
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
/*
* SimpleFeatureStore has a method to add features from a
* SimpleFeatureCollection object, so we use the ListFeatureCollection
* class to wrap our list of features.
*/
// 直接Features转为要素集合
SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
// 提交事务创建要素集
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
}
System.exit(0); // success!
} else {
System.out.println(typeName + " does not support read/write access");
System.exit(1);
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
其他
写要素其他方案
在这里插入代码片String typeNames = dataStore.getTypeNames()[0];
SimpleFeatureSource source = store.getfeatureSource( typeName );
if( source instanceof SimpleFeatureStore){
SimpleFeatureStore store = (SimpleFeatureStore) source; // write access!
store.addFeatures( featureCollection );
store.removeFeatures( filter ); // filter is like SQL WHERE
store.modifyFeature( attribute, value, filter );
}
创建点
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory( null );
WKTReader reader = new WKTReader( geometryFactory );
Point point = (Point) reader.read("POINT (1 1)");
创建线
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
WKTReader reader = new WKTReader(geometryFactory);
LineString line = (LineString) reader.read("LINESTRING(0 2, 2 0, 8 6)");
创建面
WKBReader wkbReader = new WKBReader(geometryFactory);
MultiPolygon polygon = (MultiPolygon) wkbReader.read(WKBReader.hexToBytes(tokens[1]));
类图
Feature:要素
dataStore:相当于一个文件