Search in sources :

Example 1 with FeatureCollection

use of org.geotools.feature.FeatureCollection in project spatial-portal by AtlasOfLivingAustralia.

the class ShapefileUtils method loadShapefile.

public static Map loadShapefile(File shpfile) {
    try {
        FileDataStore store = FileDataStoreFinder.getDataStore(shpfile);
        LOGGER.debug("Loading shapefile. Reading content:");
        LOGGER.debug(store.getTypeNames()[0]);
        FeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
        FeatureCollection featureCollection = featureSource.getFeatures();
        FeatureIterator it = featureCollection.features();
        Map shape = new HashMap();
        StringBuilder sb = new StringBuilder();
        StringBuilder sbGeometryCollection = new StringBuilder();
        boolean isGeometryCollection = false;
        while (it.hasNext()) {
            SimpleFeature feature = (SimpleFeature) it.next();
            Geometry geom = (Geometry) feature.getDefaultGeometry();
            WKTWriter wkt = new WKTWriter();
            String wktString = wkt.write(geom);
            wktString = wktString.replaceAll(", ", ",");
            boolean valid = true;
            boolean multipolygon = false;
            boolean polygon = false;
            boolean geometrycollection = false;
            if (wktString.startsWith(StringConstants.MULTIPOLYGON + " ")) {
                wktString = wktString.substring((StringConstants.MULTIPOLYGON + " (").length(), wktString.length() - 1);
                multipolygon = true;
            } else if (wktString.startsWith(StringConstants.POLYGON + " ")) {
                wktString = wktString.substring((StringConstants.POLYGON + " ").length());
                polygon = true;
            } else if (wktString.startsWith(StringConstants.GEOMETRYCOLLECTION + " (")) {
                wktString = wktString.substring((StringConstants.GEOMETRYCOLLECTION + " (").length(), wktString.length() - 1);
                geometrycollection = true;
                isGeometryCollection = true;
            } else {
                valid = false;
            }
            if (valid) {
                if (sb.length() > 0) {
                    sb.append(",");
                    sbGeometryCollection.append(",");
                }
                sb.append(wktString);
                if (multipolygon) {
                    sbGeometryCollection.append(StringConstants.MULTIPOLYGON).append("(").append(wktString.replace("(((", "(("));
                    if (!wktString.endsWith(")))")) {
                        sbGeometryCollection.append(")");
                    }
                } else if (polygon) {
                    sbGeometryCollection.append(StringConstants.POLYGON).append(wktString);
                } else if (geometrycollection) {
                    sbGeometryCollection.append(wktString);
                }
            }
        }
        if (!isGeometryCollection) {
            if (!sb.toString().contains(")))")) {
                sb.append(")");
            }
            shape.put(StringConstants.WKT, StringConstants.MULTIPOLYGON + "(" + sb.toString().replace("(((", "(("));
        } else {
            sbGeometryCollection.append(")");
            shape.put(StringConstants.WKT, StringConstants.GEOMETRYCOLLECTION + "(" + sbGeometryCollection);
        }
        try {
            it.close();
        } catch (Exception e) {
        }
        return shape;
    } catch (Exception e) {
        LOGGER.error("Unable to load shapefile: ", e);
    }
    return null;
}
Also used : SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) WKTWriter(com.vividsolutions.jts.io.WKTWriter) HashMap(java.util.HashMap) SimpleFeature(org.opengis.feature.simple.SimpleFeature) FeatureIterator(org.geotools.feature.FeatureIterator) Geometry(com.vividsolutions.jts.geom.Geometry) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) FeatureCollection(org.geotools.feature.FeatureCollection) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with FeatureCollection

use of org.geotools.feature.FeatureCollection in project v-leaflet by mstahv.

the class ChoroplethExample method getTestComponent.

@Override
public Component getTestComponent() {
    leafletMap = new LMap();
    leafletMap.addLayer(new LOpenStreetMapLayer());
    leafletMap.setView(37.8, -96.0, 4.0);
    /*
         * Reading from geojson here, but typically you'd just query
         * your DB directly for the data.
         */
    FeatureJSON io = new FeatureJSON();
    try {
        // 
        // 
        FeatureCollection fc = io.readFeatureCollection(getClass().getResourceAsStream("/us-states.json"));
        FeatureIterator iterator = fc.features();
        try {
            while (iterator.hasNext()) {
                Feature feature = iterator.next();
                final String name = feature.getProperty("name").getValue().toString();
                final Double density = (Double) feature.getProperty("density").getValue();
                System.out.println("State " + name + " read!");
                Geometry geometry = (Geometry) feature.getDefaultGeometryProperty().getValue();
                // Using a helper create v-leaflet components from geojson
                Collection<LeafletLayer> toLayers = JTSUtil.toLayers(geometry);
                for (LeafletLayer l : toLayers) {
                    leafletMap.addComponent(l);
                    if (l instanceof AbstractLeafletVector) {
                        configureFeature(l, density, name);
                    } else if (l instanceof LLayerGroup) {
                        LLayerGroup g = (LLayerGroup) l;
                        for (Component component : g) {
                            configureFeature((LeafletLayer) component, density, name);
                        }
                    }
                }
            }
        } finally {
            iterator.close();
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(ChoroplethExample.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ChoroplethExample.class.getName()).log(Level.SEVERE, null, ex);
    }
    /*
         * AbsoluteLayout is a handy layout you can use to place any Vaadin
         * components on top of map. Here we just use raw html label to create
         * a legend, but we could use dynamically generated html or e.g. Table
         * component on top of the map as well.
         */
    AbsoluteLayout absoluteLayout = new AbsoluteLayout();
    absoluteLayout.setWidth("800px");
    absoluteLayout.setHeight("500px");
    absoluteLayout.addComponent(leafletMap);
    Label label = new Label("<style>.legend { background:white; padding:10px; border-radius: 4px; text-align: left; line-height: 18px; color: #555; } .legend i { width: 18px; height: 18px; float: left; margin-right: 8px; opacity: 0.7; }</style><div class=\"info legend leaflet-control\"><i style=\"background:#FFEDA0\"></i> 0–10<br><i style=\"background:#FED976\"></i> 10–20<br><i style=\"background:#FEB24C\"></i> 20–50<br><i style=\"background:#FD8D3C\"></i> 50–100<br><i style=\"background:#FC4E2A\"></i> 100–200<br><i style=\"background:#E31A1C\"></i> 200–500<br><i style=\"background:#BD0026\"></i> 500–1000<br><i style=\"background:#800026\"></i> 1000+</div>", ContentMode.HTML);
    label.setWidth("100px");
    absoluteLayout.addComponent(label, "bottom: 30px; right: 20px;");
    return absoluteLayout;
}
Also used : MalformedURLException(java.net.MalformedURLException) LOpenStreetMapLayer(org.vaadin.addon.leaflet.LOpenStreetMapLayer) LeafletLayer(org.vaadin.addon.leaflet.LeafletLayer) Label(com.vaadin.ui.Label) IOException(java.io.IOException) Feature(org.opengis.feature.Feature) AbsoluteLayout(com.vaadin.ui.AbsoluteLayout) FeatureIterator(org.geotools.feature.FeatureIterator) Geometry(com.vividsolutions.jts.geom.Geometry) LLayerGroup(org.vaadin.addon.leaflet.LLayerGroup) FeatureJSON(org.geotools.geojson.feature.FeatureJSON) LMap(org.vaadin.addon.leaflet.LMap) FeatureCollection(org.geotools.feature.FeatureCollection) Component(com.vaadin.ui.Component) AbstractLeafletVector(org.vaadin.addon.leaflet.AbstractLeafletVector)

Example 3 with FeatureCollection

use of org.geotools.feature.FeatureCollection in project v-leaflet by mstahv.

the class GeoJSONExample method getTestComponent.

@Override
public Component getTestComponent() {
    leafletMap = new LMap();
    leafletMap.setWidth("600px");
    leafletMap.setHeight("400px");
    /*
         * Note, this is just one option to read GeoJSON in java. Here, using 
         * helper from geotools library. In some simple cases approach to use
         * plain Json library like Jackson or GSON might be better.
         */
    FeatureJSON io = new FeatureJSON();
    try {
        long currentTimeMillis = System.currentTimeMillis();
        // Look ma, no proxy needed, how cool is that!
        FeatureCollection fc = io.readFeatureCollection(new URL("http://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_500k.json").openStream());
        Logger.getLogger(GeoJSONExample.class.getName()).severe("Download in " + (System.currentTimeMillis() - currentTimeMillis));
        currentTimeMillis = System.currentTimeMillis();
        FeatureIterator iterator = fc.features();
        try {
            while (iterator.hasNext()) {
                Feature feature = iterator.next();
                final String name = feature.getProperty("NAME").getValue().toString();
                System.out.println("State " + name + " read!");
                Geometry geometry = (Geometry) feature.getDefaultGeometryProperty().getValue();
                // The geojson provided in example is rather complex (several megabytes)
                // Use JTS to simplyfy. Note that it is rather easy to use
                // different settings on different zoom levels, as well as decide
                // to drop the feature form client altogether
                geometry = DouglasPeuckerSimplifier.simplify(geometry, 0.2);
                // In this example can be Polygon/Multipolygon
                Collection<LeafletLayer> toLayers = JTSUtil.toLayers(geometry);
                for (LeafletLayer l : toLayers) {
                    leafletMap.addComponent(l);
                    if (l instanceof LPolygon) {
                        LPolygon lPolygon = (LPolygon) l;
                        lPolygon.addClickListener(new LeafletClickListener() {

                            @Override
                            public void onClick(LeafletClickEvent event) {
                                Notification.show("That is " + name);
                            }
                        });
                    }
                }
            }
            Logger.getLogger(GeoJSONExample.class.getName()).severe("Reducing and creating layers " + (System.currentTimeMillis() - currentTimeMillis));
        } finally {
            iterator.close();
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(GeoJSONExample.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GeoJSONExample.class.getName()).log(Level.SEVERE, null, ex);
    }
    leafletMap.zoomToContent();
    return leafletMap;
}
Also used : LeafletClickEvent(org.vaadin.addon.leaflet.LeafletClickEvent) MalformedURLException(java.net.MalformedURLException) LeafletLayer(org.vaadin.addon.leaflet.LeafletLayer) LeafletClickListener(org.vaadin.addon.leaflet.LeafletClickListener) IOException(java.io.IOException) Feature(org.opengis.feature.Feature) URL(java.net.URL) LPolygon(org.vaadin.addon.leaflet.LPolygon) FeatureIterator(org.geotools.feature.FeatureIterator) Geometry(com.vividsolutions.jts.geom.Geometry) FeatureJSON(org.geotools.geojson.feature.FeatureJSON) LMap(org.vaadin.addon.leaflet.LMap) FeatureCollection(org.geotools.feature.FeatureCollection)

Example 4 with FeatureCollection

use of org.geotools.feature.FeatureCollection in project GeoGig by boundlessgeo.

the class AbstractGeoJsonCommand method getDataStore.

protected DataStore getDataStore(String geoJSON) throws FileNotFoundException, IOException {
    try {
        File geoJsonfile = new File(geoJSON);
        checkParameter(geoJsonfile.exists(), "File does not exist '%s'", geoJsonfile);
        InputStream in = new FileInputStream(geoJsonfile);
        FeatureJSON fjson = new FeatureJSON();
        @SuppressWarnings("rawtypes") FeatureCollection fc = fjson.readFeatureCollection(in);
        @SuppressWarnings("unchecked") DataStore dataStore = new MemoryDataStore(fc);
        return dataStore;
    } catch (IOException ioe) {
        throw new CommandFailedException("Error opening GeoJSON: " + ioe.getMessage(), ioe);
    }
}
Also used : FeatureJSON(org.geotools.geojson.feature.FeatureJSON) FeatureCollection(org.geotools.feature.FeatureCollection) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) DataStore(org.geotools.data.DataStore) MemoryDataStore(org.geotools.data.memory.MemoryDataStore) MemoryDataStore(org.geotools.data.memory.MemoryDataStore) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException)

Example 5 with FeatureCollection

use of org.geotools.feature.FeatureCollection in project GeoGig by boundlessgeo.

the class ImportOp method getFeatureSource.

@SuppressWarnings({ "rawtypes", "unchecked" })
private FeatureSource getFeatureSource(String typeName) {
    FeatureSource featureSource;
    try {
        featureSource = dataStore.getFeatureSource(typeName);
    } catch (Exception e) {
        throw new GeoToolsOpException(StatusCode.UNABLE_TO_GET_FEATURES);
    }
    return new ForwardingFeatureSource(featureSource) {

        @Override
        public FeatureCollection getFeatures(Query query) throws IOException {
            final FeatureCollection features = super.getFeatures(query);
            return new ForwardingFeatureCollection(features) {

                @Override
                public FeatureIterator features() {
                    final FeatureType featureType = getSchema();
                    final String fidPrefix = featureType.getName().getLocalPart() + ".";
                    FeatureIterator iterator = delegate.features();
                    return new FidAndFtReplacerIterator(iterator, fidAttribute, fidPrefix, (SimpleFeatureType) featureType);
                }
            };
        }
    };
}
Also used : FeatureIterator(org.geotools.feature.FeatureIterator) ForwardingFeatureIterator(org.locationtech.geogig.api.data.ForwardingFeatureIterator) ForwardingFeatureSource(org.locationtech.geogig.api.data.ForwardingFeatureSource) JDBCFeatureSource(org.geotools.jdbc.JDBCFeatureSource) FeatureSource(org.geotools.data.FeatureSource) ResolveFeatureType(org.locationtech.geogig.api.plumbing.ResolveFeatureType) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) FeatureType(org.opengis.feature.type.FeatureType) Query(org.geotools.data.Query) ForwardingFeatureCollection(org.locationtech.geogig.api.data.ForwardingFeatureCollection) ForwardingFeatureCollection(org.locationtech.geogig.api.data.ForwardingFeatureCollection) FeatureCollection(org.geotools.feature.FeatureCollection) ForwardingFeatureSource(org.locationtech.geogig.api.data.ForwardingFeatureSource) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Aggregations

FeatureCollection (org.geotools.feature.FeatureCollection)13 FeatureIterator (org.geotools.feature.FeatureIterator)7 FeatureJSON (org.geotools.geojson.feature.FeatureJSON)6 Feature (org.opengis.feature.Feature)5 Geometry (com.vividsolutions.jts.geom.Geometry)4 IOException (java.io.IOException)4 File (java.io.File)3 AdaptorFeatureCollection (org.geotools.feature.collection.AdaptorFeatureCollection)3 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 MalformedURLException (java.net.MalformedURLException)2 ArrayList (java.util.ArrayList)2 DataStore (org.geotools.data.DataStore)2 FeatureSource (org.geotools.data.FeatureSource)2 Query (org.geotools.data.Query)2 MemoryDataStore (org.geotools.data.memory.MemoryDataStore)2 SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)2 CommandFailedException (org.locationtech.geogig.cli.CommandFailedException)2 SimpleFeature (org.opengis.feature.simple.SimpleFeature)2 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)2