前言
相关描述可参考Geotools例子2,解析csv文件保存为shp,这里直接贴出代码
实现
import org.geotools.data.DataUtilities;
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.SchemaException;
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.CoordinateSequence;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Polygon;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import javax.json.*;
import javax.json.stream.JsonParser;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GeoJSON {
public static void main(String[] args){
File file = new File("src/main/resources/anhui.json");
try(BufferedReader reader = new BufferedReader(new FileReader(file))){
StringBuilder str = new StringBuilder("");
String line = "";
for(line = reader.readLine(); line != null; line=reader.readLine()){
str.append(line);
}
// 创建要素类型FeatureType
final SimpleFeatureType TYPE =
DataUtilities.createType(
"Province",
"the_geom:Polygon:srid=4326,"
+ // <- the geometry attribute: Point type
"name:String,"
+ // <- a String attribute
"number:Integer" // a number attribute
);
List<SimpleFeature> features = new ArrayList<SimpleFeature>();
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
/**
* 解析JSON格式数据
*/
JsonReader jsonReader = Json.createReader(new StringReader(str.toString()));
JsonObject jsonObj = jsonReader.readObject();
JsonObject geometry = jsonObj.getJsonArray("features").getJsonObject(0).getJsonObject("geometry");
// 获取geometry类型和坐标
String type = geometry.getString("type");
JsonArray coordinates = geometry.getJsonArray("coordinates").getJsonArray(0);
ArrayList<Coordinate> list = new ArrayList<Coordinate>();
// Coordinate[] list = new Coordinate[200];
for(JsonValue obj : coordinates){
String[] objArray = obj.toString().split(",");
// 经纬度
String latitude = objArray[0].substring(1);
String longitude = objArray[1].substring(0, objArray[1].length() - 1);
list.add(new Coordinate(Double.parseDouble(longitude), Double.parseDouble(latitude)));
}
// 转换ArrayList为Coordinate[]
Coordinate coordinateList[] = new Coordinate[list.toArray().length];
for(int i = 0; i < coordinateList.length; i++){
coordinateList[i] = (Coordinate) list.toArray()[i];
}
Polygon polygon = geometryFactory.createPolygon(coordinateList);
// 生成要素
featureBuilder.add(polygon);
SimpleFeature feature = featureBuilder.buildFeature(null);
features.add(feature);
// 选择shp文件保存路径
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
// the user cancelled the dialog
System.exit(0);
}
File newFile = chooser.getSelectedFile();
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<>();
params.put("url", newFile.toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore newDataStore =
(ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
// 定义数据存储要素类型
newDataStore.createSchema(TYPE);
// FeatureStore事务控制,这里是创建
Transaction transaction = new DefaultTransaction("create");
String typeName = newDataStore.getTypeNames()[0]; // points
// 要素源
SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
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.
*/
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 (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SchemaException e) {
e.printStackTrace();
}
}
}