Sunday, March 13, 2011

jython + the JTS geometry library

My favorite library for dealing with two dimensional points, lines, and polygons is Polygon by Jörg Rädler.  In a Java/jython environment, though, that's not available.  This led me to try my hand at JTS.  


Constructs a GeometryFactory that generates Geometries having a floating PrecisionModel and a spatial-reference ID of 0."  For what I'm doing this is fine.

2) The preferred constructor for the Point object takes a CoordinateArraySequence of length one instead of a single Coordinate object.  This is analogous to a character in Python being a string of length one.

We don't know yet what our values are for our Point's coordinates.  Let's have a look.

>>> ptx
POINT (0 0)

OK, zero-zero.  Let's assign something to those coordinates away from the origin.

>>> ptx.getCoordinates()[0].x = 44
>>> ptx.getCoordinates()[0].y = 22
>>> ptx
POINT (44 22)
Even though the Point has only one coordinate, we still need to specify that with the index 0.

Well, that was a lot of work for just one point.  Let's try something more efficient and fun.

>>> cas2 = CoordinateArraySequence(6)
>>> somecoordinates = [(1, 5), (7, 14), (22, 44), (36, 12), (19, 1), (12, 4)]
>>> for numx in range(len(somecoordinates)):
...     cas2.getCoordinate(numx).x = somecoordinates[numx][0]
...     cas2.getCoordinate(numx).y = somecoordinates[numx][1]
...
>>> cas2
((1.0, 5.0, NaN), (7.0, 14.0, NaN), (22.0, 44.0, NaN), (36.0, 12.0, NaN), (19.0, 1.0, NaN), (12.0, 4.0, NaN))
>>> from com.vividsolutions.jts.geom import LineString
>>> ls = LineString(cas2, factoryx)
>>> ch = ls.convexHull()
>>> ch
POLYGON ((19 1, 1 5, 22 44, 36 12, 19 1))
>>> 


LineString is one of the classes that can be instantiated from a CoordinateArraySequence.  I went with that mainly for ease of use.

There is a great deal more to JTS.  This post was mainly for getting started with the library.


No comments:

Post a Comment

Post a Comment