GeoTools is an open source (LGPL) Java code library which provides standards compliant methods for the manipulation of geospatial data. Unfortunately the GeoTools page and its documentation is not really clearly arranged.
Here is the way I implemented a quite common intersection analysis with the
GeoTools library version 2.4.
First create a new data store:
public void setDataStore(Map connect) {
try {
this.dataStore = DataStoreFinder.getDataStore(connect);
} catch (IOException ex) {
System.err.println("DataStore not found");
}
}
Variable connect contains the connection parameters, if a shape file is on hand, it looks like this:
File file = new File("/path/to/shape/file");
HashMap connect = new HashMap();
connect.put("url", file.toURI().toURL());
If a PostGIS database is connected, variable connect looks like this:
Map connect = new HashMap();
connect.put( PostgisDataStoreFactory.DBTYPE.key, "postgis" );
connect.put( PostgisDataStoreFactory.HOST.key, "www.yourserver.net" );
connect.put( PostgisDataStoreFactory.PORT.key, "5432" );
connect.put( PostgisDataStoreFactory.DATABASE.key, "database" );
connect.put( PostgisDataStoreFactory.USER.key, "username" );
connect.put( PostgisDataStoreFactory.PASSWD.key, "password" );
Once the data store is created, a new bounding box filter is initiated. Basically there are several ways to create such a filter, this is only one possibility.
String cqlExpression = "BBOX("
+ geometryColumnName
+ ","
+ minX
+ ","
+ minY
+ ","
+ maxX
+ ","
+ maxY
+ ",'EPSG:4326')";
Filter filter = CQL.toFilter(cqlExpression);
With this filter the geometries which intersect the defined bounding box are selected.
(Note that the selected geometries are not clipped.)
FeatureCollection featureCollection = featureSource.getFeatures(filter);
FeatureIterator featureIterator = featureCollection.features();
Before the geometries are clipped a new polygon which represents the bounding box has to be created.
//Instantiate the geometry factory
GeometryFactory geometryFactory =
new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING), 4326);
//Create the bounding box polygon
Coordinate[] bbox = new Coordinate[5];
bbox[0] = new Coordinate(minX,minY);
bbox[1] = new Coordinate(minX,maxY);
bbox[2] = new Coordinate(maxX,maxY);
bbox[3] = new Coordinate(maxX,minY);
bbox[4] = new Coordinate(minX,minY);
LinearRing bboxRing = geometryFactory.createLinearRing(bbox);
Polygon bboxPolygon = geometryFactory.createPolygon(bboxRing, null);
Now we iterate through the selected geometries and clip them
//Iterate over all features
while( featureIterator.hasNext() ) {
Feature feature = featureIterator.next();
Geometry geometry = feature.getDefaultGeometry();
//Clip the geometry and write the intersected geometry
writeGeometry(writer, geometry.intersection(bboxPolygon));
}
Last but not least all needed packages have to be added to the classpath and imported.