Geotoolsの例2、csvファイルを解析し、shpとして保存します



Geotools Example 2 Parse Csv File



序文

このチュートリアルには、次のものが含まれています。

  • create FeatureTypeFeatureCollection with Features
  • 使用GeometryFactoryビルドポイント
  • シェープファイルを書く
  • 強制投影

csvファイル

  1. テキストファイルを作成しますlocation.csv次に、次の場所をコピーして貼り付けます。



    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. またはダウンロード locations.csv

  3. 故郷など、他の場所をファイルに自由に追加してください。



依存関係ファイル

チュートリアルで使用されているバージョンは、最新バージョン23-SNAPSHOTです。テスト中にいくつかの問題が見つかりました。バージョン22.2を使用しました。必要に応じて、さまざまなバージョンを使用できます。

<dependencies> <--shapefile related dependencies--> <dependency> <groupId>org.geotoolsgroupId> <artifactId>gt-shapefileartifactId> <version>${geotools.version}version> dependency> <--Projection dependency--> <dependency> <groupId>org.geotoolsgroupId> <artifactId>gt-epsg-hsqlartifactId> <version>${geotools.version}version> dependency> dependencies> <--The following three warehouses do not need to be used over the wall. If the maven warehouse cannot be used, domestic mirrors can be used--> <repositories> <repository> <id>maven2-repository.dev.java.netid> <name>Java.net repositoryname> <url>http://download.java.net/maven/2url> repository> <repository> <id>osgeoid> <name>Open Source Geospatial Foundation Repositoryname> <url>http://download.osgeo.org/webdav/geotools/url> repository> <repository> <snapshots> <enabled>trueenabled> snapshots> <id>boundlessid> <name>Boundless Maven Repositoryname> <url>http://repo.boundlessgeo.com/mainurl> repository> repositories>

ステップ

1.csvファイルを選択します

import org.geotools.swing.data.JFileDataStoreChooser File file = JFileDataStoreChooser.showOpenFile('csv', null) if(file == null) { return }

2.FeatureTypeを作成します



import org.opengis.feature.simple.SimpleFeatureType import org.geotools.data.DataUtilities 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 )

3. csvファイルを解析し、S​​impleFeatureの配列に保存します

分析のアイデアは次のとおりです。javaリーダーBufferedReaderを介してcsvファイルを1行ずつ読み取り(csvの各行は1つの要素に対応します)、幾何学的要素ファクトリGeometryFactoryを介して幾何学的特徴点を作成し、shp要素構築ツールSimpleFeatureBuilderを介してshp要素を構築します、および幾何学的要素ポイントの追加情報と属性情報が最終的に配列に追加されます。

import org.opengis.feature.simple.SimpleFeature import org.geotools.geometry.jts.JTSFactoryFinder import org.locationtech.jts.geom.GeometryFactory import org.geotools.feature.simple.SimpleFeatureBuilder // SimpleFeature array List<SimpleFeature> features = new ArrayList<SimpleFeature>() // Geometry Factor Factory GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory() // feature builder SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE) try( BufferedReader reader = new BufferedReader(new FileReader(file)) ){ String line = reader.readLine() // parse the csv file into the SimpleFeature list for(line = reader.readLine() line != null line = reader.readLine()){ 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()) 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) } }

4.ダイアログボックスを呼び出して、shpファイルを保存します。この時点で、shpファイルは空であり、後で使用するために保存します。

import org.geotools.swing.data.JFileDataStoreChooser 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) } // This file is empty and needs to be filled with elements File newFile = chooser.getSelectedFile() if (newFile.equals(csvFile)) { System.out.println('Error: cannot replace ' + csvFile) System.exit(0) } return newFile }

5.shpデータソースSimpleFeatureSourceを取得します

File newFile = getNewShapeFile(file) // Data warehouse factory, generate data warehouse ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory() // Data warehouse generation parameters Map<String, Serializable> params = new HashMap<>() params.put('url', newFile.toURI().toURL()) params.put('create spatial index', Boolean.TRUE) // Data warehouse factory generates data warehouse ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params) // Define the data warehouse data element type newDataStore.createSchema(TYPE) // FeatureStore transaction control, here is to create create Transaction transaction = new DefaultTransaction('create') String typeName = newDataStore.getTypeNames()[0] // points // Feature source SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName)

6.shpデータソースを空のshpファイルに保存します

if (featureSource instanceof SimpleFeatureStore) { SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource 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) }

その他

1.属性情報を含めることができるSimpleFeatureTypeを構築するためのより柔軟な方法。

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 }