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" +
" }";