2

I'm new to GeoTools and GIS generally. I have a shapefile containing feature polygons representing NY City taxi zones. I also have the coordinates in latitude and longitude for the pickup and drop-off locations for a (large) number of taxi trips.

I have read the Shapefile into a DataStore and can iterate over the features, but have no idea how to actually query it. I assume that this is a function that Geotools provides, but perhaps I'm wrong.

My code so far is below:

File file = new File("taxi_zones.shp");
FileDataStore myData = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource source = myData.getFeatureSource();
SimpleFeatureType schema = source.getSchema();

Query query = new Query(schema.getTypeName());

FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures(query);
try (FeatureIterator<SimpleFeature> features = collection.features()) {
    while (features.hasNext()) {
        SimpleFeature feature = features.next();
        System.out.println(feature.getID() + ": ");
        for (Property attribute : feature.getProperties()) {
            if (attribute.getName().toString().equals("the_geom")) {
                System.out.println("\t" + attribute.getName() + ":" + attribute.getValue());
            }
        }
    }
}

EDIT: I have since found the CQL subproject and realize i need something like: Filter filter = ECQL.toFilter(""), but I don't know how to formulate the query text

2

1 Answer 1

1

In this answer to a similar question I tested the 2 main ways of doing this - either looping over the points and testing them against the polygons, or looping over the polygons and finding the matching points. The "best" solution is dependent on the relative sizes of the datasets. In your case I would go with the indexed polygons containing points option.

  public static HashMap<String, Integer> polygonLoopIndex(SimpleFeatureCollection points, SimpleFeatureCollection polys,
      Expression propertyName) throws IOException {
    long start = System.currentTimeMillis();
    HashMap<String, Integer> results = new HashMap<>();
    SpatialIndexFeatureCollection index = new SpatialIndexFeatureCollection(points);
    try (SimpleFeatureIterator itr = polys.features()) {
      while (itr.hasNext()) {
        SimpleFeature poly = itr.next();
        Filter filter = filterFactory.within(propertyName, filterFactory.literal(poly.getDefaultGeometry()));
        SimpleFeatureCollection sub = index.subCollection(filter);
        results.put((String) poly.getAttribute("NAME"), sub.size());

      }
    }
    long end = System.currentTimeMillis();
    System.out.println("Indexed Polygon Loop Time = " + (end - start) + "ms");
    return results;
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.