Saturday, March 19, 2011

WKT (Well Known Text) + JTS Topology + jython

The last few posts have dealt with the JTS Topology library.  This one will wrap up that topic with a method for converting JTS's Geometry objects to and from text, WKT.

WKT is a standard of the Open Geospatial Consortium (OGC).  Objects expressed in WKT are not much different than their string representations in JTS.  Below is a code example of working back and forth between JTS and WKT.


Jython 2.5.2 (Release_2_5_2:7206, Mar 2 2011, 23:12:06)
[OpenJDK Client VM (Sun Microsystems Inc.)] on java1.7.0-internal
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append('/home/carl/Downloads/jts/lib/jts-1.11.jar')
>>> from com.vividsolutions.jts.geom import GeometryFactory
>>> from com.vividsolutions.jts.geom import Coordinate
>>> from com.vividsolutions.jts.geom import LinearRing
>>> from com.vividsolutions.jts.io import WKTWriter
>>> from com.vividsolutions.jts.io import WKTReader
>>> coord1 = Coordinate(0, 0)
>>> coord2 = Coordinate(0, 1)
>>> coord3 = Coordinate(1, 1)
>>> coord4 = Coordinate(1, 0)
>>> coord5 = Coordinate(0, 0)
>>> coords = [coord1, coord2, coord3, coord4, coord5]
>>> from com.vividsolutions.jts.geom.impl import CoordinateArraySequence
>>> cas = CoordinateArraySequence(coords)
>>> gf = GeometryFactory()
>>> lr = LinearRing(cas, gf)
>>> asquare = gf.createPolygon(lr, None)
>>> f = open('wkttest.xml', 'w')
>>> wktwriter = WKTWriter()

>>> # this is just my own personal preference
>>> # it is inefficient for storage, but
>>> # sometimes easier on the eyes
>>> wktwriter.setMaxCoordinatesPerLine(1)
>>> text = wktwriter.writeFormatted(asquare)
>>> f.write(text)
>>> f.close()
>>> print text
POLYGON ((0 0,
  0 1,
  1 1,
  1 0,
  0 0))
>>> wktreader = WKTReader()
>>> f = open('wkttest.xml', 'r')
>>> text = f.read()
>>> asquare2 = wktreader.read(text)
>>> asquare2
POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))



It's fairly easy to store JTS Geometry objects in human readable (WKT) format and reuse them.  


There is a good bit more to WKT than what's shown here.  This was just a simple example for getting started.


WKB (Well Known Binary) is also available in JTS - this is used for efficient storage of Geometry objects, mainly in databases.


JTS also has a WKTFileReader class which can read in multiple geometries from a file.

No comments:

Post a Comment