[GIS] How to extract bbox of polygon geometries in a shapefile using geotools

bboxgeotoolsshapefile

I have a shapefile which has building footprints as polygon features. I want to read shapefile and extract these bbox of these polygon features using geotools. So far I read shapefile but I don't know how can I access geometry and attributes of a shapefile records using geotools. Here is my code; but I don't know how can I do the rest of work for my purpose.

package org.geotools;

import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class Tiler {
File file = new File ("C:/Users/Ziya/Desktop/Kasustu/footprints.shp");
Map<String, URL> map = new HashMap<String, URL>();
public Tiler() throws IOException {
    map.put("url", file.toURI().toURL());
}

    DataStore dataStore= DataStoreFinder.getDataStore(map);
    SimpleFeatureSource featureSource = 
    dataStore.getFeatureSource(dataStore.getTypeNames()[0]);
    SimpleFeatureCollection collection = featureSource.getFeatures();

Best Answer

Once you have a SimpleFeatureCollection it is just a case of iterating through the collection and looking at whichever attributes you need. The SimpleFeature interface is well documented.

try (SimpleFeatureIterator itr = (SimpleFeatureIterator) inputFeatureCollection.features()) {
  while (itr.hasNext()) {
    SimpleFeature f = itr.next();
    //Default geometery 
    Geometry g = (Geometry)f.getDefaultGeomerty();
    //bounding box
    Geometry envPoly = g.getEnvelope(); // a polygon
    Envelope env = geom.getEnvelopeInternal(); // a simple envelope
    double minx = env.getMinX();
    double miny = env.getMinY();
    double maxx = env.getMaxX();
    double maxy = env.getMaxY();

    //access properties or attributes
    Property p = f.getProperty("name");
    PropertyType type = p.getType();
    Name name = p.getName();
    Object v = p.getValue();
    List<Object> l = f.getAttributes();
    Object a1 = f.getAttribute("name");
    Object a2 = f.getAttribute(0);
  }
}

Also please use URLs.fileToUrl(inFile) instead of file.toURI().toURL() your windows users will thank you for it.

Related Question