Parse GeoJSON file with Java Topology Suite or GeoTools
Asked Answered
A

3

5

For example, if you have a GeoJSON file like this with a polygon(simple file for the test)

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -4.658203125,
              41.343824581185686
            ],
            [
              -5.6689453125,
              39.13006024213511
            ],
            [
              -1.9335937499999998,
              39.16414104768742
            ],
            [
              -1.3623046875,
              41.21172151054787
            ],
            [
              -4.658203125,
              41.343824581185686
            ]
          ]
        ]
      }
    }
  ]
}

The point:

Geometry point2 = new WKTReader().read("POINT (-3.2958984375 40.44694705960048)");

And you want to load the geoJSON file in your program to test in this polygon contains the point, how could you do it in Java using JTS?


Other option could be use GeoTools with GeoJson plugin but i'm not able to parse a GeoJson file


What I have tried

Using GEOTOOLS like this

String content = new String(Files.readAllBytes(Paths.get("file.geojson")), "UTF-8");
GeometryJSON gjson = new GeometryJSON();
Reader reader = new StringReader(content);
Polygon p = gjson.readPolygon(reader);
System.out.println("polygon: " + p);

The problem here is that polygon p only contains the last polygon of the geojson file. If this file have many polygons, how should I parse it?

Using JTS2GEOJSON like this

String content = new String(Files.readAllBytes(Paths.get("file.geojson")), "UTF-8");
System.out.println("content: " + content);
GeoJSONReader reader1 = new GeoJSONReader();
Geometry geometry = reader1.read(content);

This code fail is this line:

Geometry geometry = reader1.read(content);

With this error:

Exception in thread "main" java.lang.UnsupportedOperationException
    at org.wololo.jts2geojson.GeoJSONReader.read(GeoJSONReader.java:51)
    at org.wololo.jts2geojson.GeoJSONReader.read(GeoJSONReader.java:21)
    at org.wololo.jts2geojson.GeoJSONReader.read(GeoJSONReader.java:16)

This error is due i'm trying to read a FeatureCollections from GeoJson file. It works if I tried with this simple string:

   String content = "{\n" +
                "        \"type\": \"Polygon\",\n" +
                "        \"coordinates\": [\n" +
                "          [\n" +
                "            [\n" +
                "              -4.141845703125,\n" +
                "              40.9218144123785\n" +
                "            ],\n" +
                "            [\n" +
                "              -4.603271484375,\n" +
                "              40.002371935876475\n" +
                "            ],\n" +
                "            [\n" +
                "              -3.5595703125,\n" +
                "              39.757879992021756\n" +
                "            ],\n" +
                "            [\n" +
                "              -2.548828125,\n" +
                "              40.43858586704331\n" +
                "            ],\n" +
                "            [\n" +
                "              -3.2080078125,\n" +
                "              41.12074559016745\n" +
                "            ],\n" +
                "            [\n" +
                "              -4.141845703125,\n" +
                "              40.9218144123785\n" +
                "            ]\n" +
                "          ]\n" +
                "        ]\n" +
                "      }";
Ancelin answered 28/12, 2018 at 10:57 Comment(2)
What have you tried so far?Jut
I added more details in the main post @IanTurtonAncelin
J
7

If you are using GeoTools then you need to start thinking in terms of DataStores and FeatureCollections. There is lots of built in smarts (much of it using JTS) to handle filtering etc which saves you a lot if potential issues.

File inFile = new File("/home/ian/Data/states/states.geojson");
Map<String, Object> params = new HashMap<>();
params.put(GeoJSONDataStoreFactory.URLP.key, URLs.fileToUrl(inFile));
DataStore newDataStore = DataStoreFinder.getDataStore(params);
String pt = "POINT (-107 42)";

FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
SimpleFeatureSource featureSource = newDataStore.getFeatureSource(newDataStore.getTypeNames()[0]);
Filter f = ff.contains(ff.property(featureSource.getSchema().getGeometryDescriptor().getLocalName()),
    ff.literal(pt));
SimpleFeatureCollection collection = featureSource.getFeatures(f);
if (collection.size() > 0) {
  try (SimpleFeatureIterator itr = collection.features()) {
    while (itr.hasNext()) {
      System.out.println(itr.next());
    }
  }
}

This will need the following in your pom.xml:

<dependency>
   <groupId>org.geotools</groupId>
   <artifactId>gt-geojsondatastore</artifactId>
   <version>${geotools.version}</version>
</dependency>
<dependency>
   <groupId>org.geotools</groupId>
   <artifactId>gt-shapefile</artifactId>
   <version>${geotools.version}</version>
 </dependency>
Jut answered 8/1, 2019 at 9:36 Comment(7)
it would be possible to do it using an InputStream inFile instead of File inFile? I have tried but it doesn't work here: URLs.fileToUrl(inFile) The way I've done is read from InputStream, create a temporary file and copy to to him but if I run this code in AWS it fails and I think is due to create a file (because in local run without problem)Ancelin
No, you need either a real URL or a file converted to a URL. May be using java.tempfile might help?Jut
That is what we are using: File tempFile = File.createTempFile("prefix-", ".geojson"); tempFile.deleteOnExit(); and if I run it locally with apache Flink all works well. The problem is when I run it in Kinesis Data Analytics no error have been shown but the method doesn't work because I don't have any resultAncelin
I think this is probably going to be a new question for AWS experts - all I can suggest is checking the file exists in the code?Jut
Hi @IanTurton, would you help me with this question? gis.stackexchange.com/q/330030/146554Vintager
GeoJSONDataStoreFactory <- what is this ?Progeny
A factory for creating GeoJSONDataStores?Jut
G
2

With the GeoJsonReader class you can read a GeoJson Geometry from a JSON fragment into a Geometry:

http://locationtech.github.io/jts/javadoc/org/locationtech/jts/io/geojson/GeoJsonReader.html

Then, test whether that geometry (geojson polygon) contains the argument geometry (wkt point):

http://locationtech.github.io/jts/javadoc/org/locationtech/jts/geom/Geometry.html#contains(org.locationtech.jts.geom.Geometry)

Geraldo answered 31/12, 2018 at 4:20 Comment(1)
how should I use the GeoJSONReader according to my code added at the main post?Ancelin
C
0

I got tired of complicated interfaces of GeoTools reader, and created a simple library for reading and writing GeoJSON FeatureCollections:

https://github.com/Urban-Research-Lab/jts-geojson

It uses Google Gson for reading json files, Geogson library for converting GeoJSON geometry structures into JTS Geometry objects. As well as some simple helper methods.

It ignores annyoying GeoJSON strictness (which actually only allows fixed set of properties for all features, or using same type of geometries).

Uses MIT License, so use it wherever you want.

Reading GeoJSON is as simple as:

val featureCollection = GeoJSONImportExport.readFeatureCollection(FileInputStream("test.geojson"))
val geom = featureCollection.features[0].geometry // JTS Geometry object
val propValue = featureCollection.features[0].properties["propName"]

Using the library is a bit complicated since it is only published in Github repo, and you need to add it first. Instructions can be found on Github.

Cambyses answered 24/10 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.