Giter Site home page Giter Site logo

jts2geojson's Introduction

Introduction

This Java library can convert JTS geometries to GeoJSON and back. Its API is similar to other io.* classes in JTS.

Build Status

Maven

<dependency>
    <groupId>org.wololo</groupId>
    <artifactId>jts2geojson</artifactId>
    <version>0.18.1</version>
</dependency>

Usage

  GeoJSONWriter writer = new GeoJSONWriter();
  GeoJSON json = writer.write(geometry);
  String jsonstring = json.toString();

  GeoJSONReader reader = new GeoJSONReader();
  Geometry geometry = reader.read(json);

Features and FeatureCollections

JTS does not have anything like GeoJSON Feature or FeatureCollection but they can be parsed by this library. Example:

  // parse Feature or FeatureCollection
  Feature feature = (Feature) GeoJSONFactory.create(json);
  FeatureCollection featureCollection = (FeatureCollection) GeoJSONFactory.create(json);

  // parse Geometry from Feature
  GeoJSONReader reader = new GeoJSONReader();
  Geometry geometry = reader.read(feature.getGeometry());
  geometry = reader.read(featureCollection.getFeatures()[0].getGeometry());

  // create and serialize a FeatureCollection
  List<Features> features = new ArrayList<Features>();
  Map<String, Object> properties = new HashMap<String, Object>();
  features.add(new Feature(geometry, properties));
  GeoJSONWriter writer = new GeoJSONWriter();
  GeoJSON json = writer.write(features);

jts2geojson's People

Contributors

agdula avatar amanbhurji avatar andypetrella avatar bjornharrtell avatar gerbsen avatar jeffreyeriksondg avatar lockwobr avatar noahtaylor avatar patzi avatar sebkur avatar snodnipper avatar ttomasz avatar wafisher avatar willcohen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jts2geojson's Issues

Error: cannot access Feature/Bad class file error

For our Android app, on upgrade to version 0.16.0, our lint check encountered this error:

error: cannot access Feature
    org.wololo.geojson.Feature[] $this$get, @org.jetbrains.annotations.NotNull()

  bad class file: /Users/../transforms-2/files-2.1/10e0c2a8959b26604a54ebc45767ffff/jetified-jts2geojson-0.16.0.jar(org/wololo/geojson/Feature.class)
    class file has wrong version 55.0, should be 52.0
    Please remove or make sure it appears in the correct subdirectory of the classpath.

This is a snippet of the generated java file that was pointed to by the logs (edited to hide details):

import java.lang.System;

@kotlin.Metadata(mv = {1, 4, 2}, bv = {1, 0, 3}, k = 2, d1 = ....)
public final class GeoJsonExtensionsKt {
    ...
    
    @org.jetbrains.annotations.NotNull()
    public static final org.wololo.geojson.Feature[] get(@org.jetbrains.annotations.NotNull()
    org.wololo.geojson.Feature[] $this$get, @org.jetbrains.annotations.NotNull()
    java.lang.String propName, @org.jetbrains.annotations.NotNull()
    java.lang.String propValue) {
        return null;
    }

....

Not sure how to approach this, your input on what's happening would be much appreciated. Thanks

Documentation request: Maven pull

Hi, my problems in #9 and #10 are now solved. However, it took me a little while to figure out that I need an extra repository, and that I have to pull version 0.7.0, which is the latest release, instead of version 0.8.0, which is the version in the Master branch POM.

While this is probably due to the fact that I'm not very proficient with Maven, there may be other unexperienced users stumbling upon this problem. That's why I think corner cases like these should be documented.

JsonMappingException when deserializing a GeometryCollection

When I attempt to deserialize a GeometryCollection, I run into this exception:

Cause: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of org.wololo.geojson.Geometry, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
 at [Source: N/A; line: -1, column: -1] (through reference chain: org.wololo.geojson.GeometryCollection["geometries"]->Object[][0])

The following GeoJSON will cause the exception:

{ "type": "GeometryCollection",
    "geometries": [
        {
            "type": "Point",
            "coordinates": [ 1.1, 2.2 ]
        }
    ]
}

I've taken the liberty of creating a pull request with the fix. Please let me know if you'd like any more information. Thanks!

Downgrade jdk version to 1.7

Hello, a lot of customers use jdk 1.7. So we also have to choose libraries that compiled for jdk 7 or publish downgraded fork. I think there isn't reason to use jdk 1.7 in this project, because it was built successfully with options 1.7 in maven-compiler-plugin.
Could you downgrade version of java source/target in maven compiler plugin or release a special version for us? It will be better rather then using with changed coordinates.

GeoJSONWriter compiled for Java 11 (class file version 55.0)

Latest closed version 0.14.1 is supposed to be compatible with Java 8. In pom.xml:

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin>

However when I try to instantiate from tests GeoJSONWriter I get this error:

java.lang.UnsupportedClassVersionError: org/wololo/jts2geojson/GeoJSONWriter has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2583)
at java.lang.Class.getDeclaredFields(Class.java:1916)
at org.junit.runners.model.TestClass.getSortedDeclaredFields(TestClass.java:77)
at org.junit.runners.model.TestClass.scanAnnotatedMembers(TestClass.java:70)
at org.junit.runners.model.TestClass.(TestClass.java:57)
at org.junit.runners.ParentRunner.createTestClass(ParentRunner.java:88)
at org.junit.runners.ParentRunner.(ParentRunner.java:83)
at org.junit.runners.BlockJUnit4ClassRunner.(BlockJUnit4ClassRunner.java:65)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:90)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:76)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:49)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:525)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

Was version incorrectly generated?

Cannot access via Maven

When I put the artifact from the pom.xml in my project pom.xml, it says "Missing artifact". Either the library is not on Maven Central (while the setup implies it were), or the upload is broken.

It shouldn't be my Maven because it loads other libraries (which, besides from Apache Commons from Glassfish, are Neo4j and Neo4j Spatial with all their nested dependencies) without any problems.

Conflicting property-based creators

I'm getting the following problem when trying to deserialise:

com.fasterxml.jackson.databind.JsonMappingException: Conflicting property-based creators: already had explicitly marked [constructor for org.wololo.geojson.LineString,

I suspect the introduction of multiple JsonCreator constructors.

GeoJSONFactory cannot parse features with null geometries

RFC7946 3.2 reads

A Feature object has a member with the name "geometry".  The value
of the geometry member SHALL be either a Geometry object as
defined above or, in the case that the Feature is unlocated, a
JSON null value.

Parsing a Geojson with null geometry throws a NullPointerException which should be processed per the RFC.
"""{"type":"Feature","geometry":null,"properties":{"test":1}}"""

Steps to reproduce current behaviour:

val json = """{"type":"Feature","geometry":null,"properties":{"test":1}}"""
GeoJSONFactory.create(json)

Release with 1.8 compatibility

0.14.1 appears to have been compiled with JDK11: see here for a downstream error when trying to use the library under JDK8. The pom has 1.8 set as target and source, so I'm not sure what needs to be changed in the deploy process for this.

Typo in readme

// create and serialize a FeatureCollection
  List<Features> features = new ArrayList<Features>();
  Map<String, Object> properties = new HashMap<String, Object>();
  features.add(new Feature(geometry, properties);
  GeoJSONWriter writer = new GeoJSONWriter();
  GeoJSON json = writer.write(features);

Feature should be singular

// create and serialize a FeatureCollection
  List<Feature> features = new ArrayList<Feature>();
  Map<String, Object> properties = new HashMap<String, Object>();
  features.add(new Feature(geometry, properties));             <-- extra parenthesis
  GeoJSONWriter writer = new GeoJSONWriter();
  GeoJSON json = writer.write(features);

Hibernate Spatial Compatibility

Hello guys,

This library is compatible with hibernate spatial? Currently, hibernate spatial uses the Geometry class org.locationtech.jts.geom.Geometry which will conflit with the Geometry class in this project.

Allow empty geometry to be parsed by jts2geojson

Many thanks for this great library @bjornharrtell !

Currently jts2geojson is not be able to parse empty geometries in either direction.
This is a correct behavior as GeoJSON processors are not required to parse empty geometries but may do so.

Would you are interested and accept a PR which brings empty geometry parsing into jts2geojson?

JTS already implements this with the additional dependency org.locationtech.jts.io:jts-io-common and the corresponding org.locationtech.jts.io.geojson.GeoJsonWriter.

var geomFactory = new GeometryFactory();
var geoJsonWriter = new org.locationtech.jts.io.geojson.GeoJsonWriter();
geoJsonWriter.setEncodeCRS(false);

var emptyPoint = geomFactory.createPoint();

var geoJson = geoJsonWriter.write(emptyPoint);
// {"type":"Point","coordinates":[]}

RFT 7946 Geometry Object

A GeoJSON Geometry object of any type other than
"GeometryCollection" has a member with the name "coordinates".
The value of the "coordinates" member is an array. The structure
of the elements in this array is determined by the type of
geometry. GeoJSON processors MAY interpret Geometry objects with
empty "coordinates" arrays as null objects.

Problems when trying to Maven-pull (Eclipse)

This is a followup issue to #9, mainly a question but correlated with a documentation request. Upon trying to establish the Maven pull, I noticed that I forgot to add the repository. I added it, but it's still failing to pull. Could you please review my POM for what else I'm missing out, and write an explanation for how to pull with Maven Eclipse so other users won't run in the same problems?

Here's my POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ptvgroup.haeg.neo4j</groupId>
  <artifactId>Spatial</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <repositories>
    <repository>
      <id>neo4j-contrib-releases</id>
      <url>https://raw.github.com/neo4j-contrib/m2/master/releases</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
    <repository>
      <id>neo4j-contrib-snapshots</id>
      <url>https://raw.github.con/neo4j-contrib/m2/master/snapshots</url>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
    <repository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>
  <dependencies>
   <dependency>
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j</artifactId>
    <version>2.3.0</version>
   </dependency>
   <dependency>
     <groupId>org.glassfish.external</groupId>
     <artifactId>apache-commons</artifactId>
     <version>3.0-b68</version>
   </dependency> 
   <dependency>
     <groupId>org.neo4j</groupId>
     <artifactId>neo4j-spatial</artifactId>
     <version>0.15-neo4j-2.3.0</version>
   </dependency>
   <dependency>
      <groupId>org.wololo</groupId>
      <artifactId>jts2geojson</artifactId>
      <version>0.8.0</version>
    </dependency>
  </dependencies>
</project>

Put properties to JSON

Hey, I'm using your libaray to convert my geometry objects into geoJson.

But I need to add additional info to the geojson objects. Such as a name, an ID and a number value.
Is this possible?

Or is it possible to convert an object of mine which is containing a Geometry value to geojson ?

Reading/writing 3D coordinates

The current versions of GeoJSONReader and GEOJSONWriter don't handle 3D coordinates. I propose the following changes:

GeoJSONWriter:

double[] convert(Coordinate coordinate) {
        if(Double.isNaN( coordinate.z )) {
            return new double[] { coordinate.x, coordinate.y };
        }
        else {
            return new double[] { coordinate.x, coordinate.y, coordinate.z };
        }
    }

GeoJSONReader:

Coordinate convert(double[] c) {
        if(c.length == 2){
            return new Coordinate(c[0], c[1]);
        }
        else{
            return new Coordinate(c[0], c[1], c[2]);
        }
    }

Thanks for a useful library, btw!

Polygon with Holes does not support the right-hand rule

Hi,

Thank you for writing this tool. I've been trying to use your tool for a polygon with a hole in it. Testing the result at (http://geojsonlint.com/).

In JTS polygons are declared such that the exterior contour will be clockwise and the holes will be anti-clockwise. GeoJson however operates on the opposite assumption that holes are anti-clockwise.

I don't think your code currently corrects for this deviation. Would an update be possible?

Thank you for any response.

Support JTS 1.17

If use jts2geojson together with JTS 1.17+, the following exception will occur:

java.lang.NoSuchMethodError: org.locationtech.jts.geom.Polygon.getExteriorRing()Lorg/locationtech/jts/geom/LineString;
at org.wololo.jts2geojson.GeoJSONWriter.convert(GeoJSONWriter.java:79)
at org.wololo.jts2geojson.GeoJSONWriter.write(GeoJSONWriter.java:28)

Can you please support JTS 1.17+?

Null properties Jackson serializer - change null collection to empty one

Running into an issue when using Geotools, GeoDataFactory. When parsing the GeoJSON, if no properties are present, getting a null instead of an empty pair of brackets. Is there a way the properties map could be configured so that properties : {} could be output instead of properties:null ?

Jackson 2.9 adds new properties to existing (but rarely used) @JsonSetter annotation to allow specifying one of common alternatives.

propose that org.wololo.geojson.Feature use the @JsonSetter annotation :

@JsonSetter(nulls = Nulls.AS_EMPTY)
public Map<String, Object> getProperties() {
	return properties;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.