Java Code Examples for org.geotools.feature.simple.SimpleFeatureBuilder#add()
The following examples show how to use
org.geotools.feature.simple.SimpleFeatureBuilder#add() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MapUtils.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Creates a feature layer based on a map object. */ public static Layer createFeatureLayerFromMapObject( InternalMapObject mapObject ) { Style style = mapObject.getStyle(); SimpleFeatureType featureType = mapObject.getFeatureType(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder( featureType ); DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(); featureBuilder.add( mapObject.getGeometry() ); SimpleFeature feature = featureBuilder.buildFeature( null ); featureCollection.add( feature ); return new FeatureLayer( featureCollection, style ); }
Example 2
Source File: FeatureWritable.java From geowave with Apache License 2.0 | 6 votes |
@Override public void readFields(final DataInput input) throws IOException { try { final String ns = input.readUTF(); featureType = FeatureDataUtils.decodeType( "-".equals(ns) ? "" : ns, input.readUTF(), input.readUTF(), input.readUTF()); } catch (final SchemaException e) { throw new IOException("Failed to parse the encoded feature type", e); } final SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); // read the fid final String fid = input.readUTF(); // read the other attributes, build the feature for (final AttributeDescriptor ad : featureType.getAttributeDescriptors()) { final Object att = readAttribute(ad, input); builder.add(att); } // build the feature feature = builder.buildFeature(fid); }
Example 3
Source File: SpatialTemporalQueryIT.java From geowave with Apache License 2.0 | 6 votes |
private static void ingestTimeRangeDataForDuplicateDeletion( final Calendar cal, final Writer writer, final SimpleFeatureBuilder featureTimeRangeBuilder, final int min, final int max, final int field, final String name) throws IOException { final GeometryFactory geomFactory = new GeometryFactory(); cal.set(field, min); featureTimeRangeBuilder.add(geomFactory.createPoint(new Coordinate(0, 0))); featureTimeRangeBuilder.add(cal.getTime()); cal.set(field, max); featureTimeRangeBuilder.add(cal.getTime()); final SimpleFeature feature = featureTimeRangeBuilder.buildFeature(name + ":fullrange"); writer.write(feature); }
Example 4
Source File: SimpleFeaturePointFigureTest.java From snap-desktop with GNU General Public License v3.0 | 5 votes |
private static SimpleFeature createFeature(SimpleFeatureType type, int index, float lat, float lon, double data) { SimpleFeatureBuilder fb = new SimpleFeatureBuilder(type); GeometryFactory gf = new GeometryFactory(); fb.add(index); fb.add(gf.createPoint(new Coordinate(lon, lat))); fb.add(data); return fb.buildFeature(Long.toHexString(System.nanoTime())); }
Example 5
Source File: ImportTrackAction.java From snap-desktop with GNU General Public License v3.0 | 5 votes |
private static SimpleFeature createFeature(SimpleFeatureType type, GeoCoding geoCoding, int pointIndex, float lat, float lon, double data) { PixelPos pixelPos = geoCoding.getPixelPos(new GeoPos(lat, lon), null); if (!pixelPos.isValid()) { return null; } SimpleFeatureBuilder fb = new SimpleFeatureBuilder(type); GeometryFactory gf = new GeometryFactory(); /*0*/ fb.add(gf.createPoint(new Coordinate(pixelPos.x, pixelPos.y))); /*1*/ fb.add(gf.createPoint(new Coordinate(lon, lat))); /*2*/ fb.add(data); return fb.buildFeature(String.format("ID%08d", pointIndex)); }
Example 6
Source File: AbstractFieldRetypingSource.java From geowave with Apache License 2.0 | 5 votes |
@Override public SimpleFeature getRetypedSimpleFeature( final SimpleFeatureBuilder builder, final SimpleFeature original) { final SimpleFeatureType target = builder.getFeatureType(); for (int i = 0; i < target.getAttributeCount(); i++) { final AttributeDescriptor attributeType = target.getDescriptor(i); Object value = null; if (original.getFeatureType().getDescriptor(attributeType.getName()) != null) { final Name name = attributeType.getName(); value = retypeAttributeValue(original.getAttribute(name), name); } builder.add(value); } String featureId = getFeatureId(original); if (featureId == null) { final FeatureId id = getDefaultFeatureId(original.getIdentifier(), original.getFeatureType(), target); featureId = id.getID(); } final SimpleFeature retyped = builder.buildFeature(featureId); retyped.getUserData().putAll(original.getUserData()); return retyped; }
Example 7
Source File: SpatialTemporalQueryIT.java From geowave with Apache License 2.0 | 5 votes |
private static void ingestTimeRangeData( final Calendar cal, final Writer writer, final SimpleFeatureBuilder featureTimeRangeBuilder, final int min, final int max, final int field, final String name) throws IOException { final GeometryFactory geomFactory = new GeometryFactory(); final int midPoint = (int) Math.floor((min + max) / 2.0); cal.set(field, min); featureTimeRangeBuilder.add(geomFactory.createPoint(new Coordinate(0, 0))); featureTimeRangeBuilder.add(cal.getTime()); cal.set(field, max); featureTimeRangeBuilder.add(cal.getTime()); SimpleFeature feature = featureTimeRangeBuilder.buildFeature(name + ":fullrange"); writer.write(feature); cal.set(field, min); featureTimeRangeBuilder.add(geomFactory.createPoint(new Coordinate(-0.1, -0.1))); featureTimeRangeBuilder.add(cal.getTime()); cal.set(field, midPoint); featureTimeRangeBuilder.add(cal.getTime()); feature = featureTimeRangeBuilder.buildFeature(name + ":firsthalfrange"); writer.write(feature); featureTimeRangeBuilder.add(geomFactory.createPoint(new Coordinate(0.1, 0.1))); featureTimeRangeBuilder.add(cal.getTime()); cal.set(field, max); featureTimeRangeBuilder.add(cal.getTime()); feature = featureTimeRangeBuilder.buildFeature(name + ":secondhalfrange"); writer.write(feature); }
Example 8
Source File: ShapeFile.java From tutorials with MIT License | 5 votes |
private static Function<Map.Entry<String, List<Double>>, SimpleFeature> toFeature(SimpleFeatureType CITY, GeometryFactory geometryFactory) { return location -> { Point point = geometryFactory.createPoint( new Coordinate(location.getValue() .get(0), location.getValue().get(1))); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); featureBuilder.add(point); featureBuilder.add(location.getKey()); return featureBuilder.buildFeature(null); }; }
Example 9
Source File: Shape.java From constellation with Apache License 2.0 | 4 votes |
/** * Construct geojson to represent a single shape given a list of * coordinates, a desired shape type and a unique identifier. * * @param uuid a unique identifier for the shape * @param type a type of shape * @param coordinates a list of coordinate tuples of the form (longitude, * latitude) from which to build the shape * @return a geojson string representing a single shape * @throws IOException there was a problem writing the generated shape */ public static String generateShape(final String uuid, final GeometryType type, final List<Tuple<Double, Double>> coordinates) throws IOException { // build precision formatter final StringBuilder precisionPattern = new StringBuilder("#."); for (int decimalPlace = 0; decimalPlace < GEOMETRY_PRECISION; decimalPlace++) { precisionPattern.append("#"); } final DecimalFormat precisionFormat = new DecimalFormat(precisionPattern.toString()); precisionFormat.setRoundingMode(RoundingMode.CEILING); // calculate geometry final double centroidLongitude = coordinates.stream().mapToDouble(coordinate -> coordinate.getFirst()).reduce((lon1, lon2) -> lon1 + lon2).getAsDouble() / coordinates.size(); final double centroidLatitude = coordinates.stream().mapToDouble(coordinate -> coordinate.getSecond()).reduce((lat1, lat2) -> lat1 + lat2).getAsDouble() / coordinates.size(); final double errorLongitude = coordinates.stream().mapToDouble(coordinate -> Math.abs(centroidLongitude - coordinate.getFirst())).max().getAsDouble(); final double errorLatitude = coordinates.stream().mapToDouble(coordinate -> Math.abs(centroidLatitude - coordinate.getSecond())).max().getAsDouble(); final double minLongitude = centroidLongitude - errorLongitude; final double minLatitude = centroidLatitude - errorLatitude; final double maxLongitude = centroidLongitude + errorLongitude; final double maxLatitude = centroidLatitude + errorLatitude; final double radius = Math.max(errorLatitude, errorLongitude); // build geometry final GeometryBuilder geometryBuilder = new GeometryBuilder(); final Geometry geometry; switch (type) { case POINT: geometry = geometryBuilder.point(centroidLongitude, centroidLatitude); break; case LINE: geometry = geometryBuilder.lineString(coordinates.stream() .flatMap(Tuple::stream) .mapToDouble(coordinate -> (Double) coordinate) .toArray()); break; case POLYGON: geometry = geometryBuilder.polygon(coordinates.stream() .flatMap(Tuple::stream) .mapToDouble(coordinate -> (Double) coordinate) .toArray()); break; case BOX: final List<Tuple<Double, Double>> boxCoordinates = new ArrayList<>(); boxCoordinates.add(Tuple.create(minLongitude, minLatitude)); boxCoordinates.add(Tuple.create(minLongitude, maxLatitude)); boxCoordinates.add(Tuple.create(maxLongitude, maxLatitude)); boxCoordinates.add(Tuple.create(maxLongitude, minLatitude)); geometry = geometryBuilder.polygon(boxCoordinates.stream() .flatMap(Tuple::stream) .mapToDouble(coordinate -> (Double) coordinate) .toArray()); break; default: throw new IllegalArgumentException(String.format("The specified shape type, %s, is not currently supported.", type)); } // initialise json final String wgs84; try { wgs84 = SpatialReference.WGS84.getSrs(); } catch (final FactoryException ex) { throw new IOException(ex); } final SimpleFeatureType featureType = generateFeatureType(uuid, wgs84, DEFAULT_GEOMETRY_ATTRIBUTE, type.getGeomertyClass(), null); final FeatureJSON featureJson = generateFeatureJson(featureType, false); // build feature final SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); featureBuilder.add(geometry); featureBuilder.set(NAME_ATTRIBUTE, uuid); featureBuilder.set(CENTROID_LATITUDE_ATTRIBUTE, precisionFormat.format(centroidLatitude)); featureBuilder.set(CENTROID_LONGITUDE_ATTRIBUTE, precisionFormat.format(centroidLongitude)); featureBuilder.set(RADIUS_ATTRIBUTE, precisionFormat.format(radius)); final SimpleFeature feature = featureBuilder.buildFeature(uuid); final DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(uuid, featureType); featureCollection.add(feature); // build json final ByteArrayOutputStream output = new ByteArrayOutputStream(); featureJson.writeFeatureCollection(featureCollection, output); return output.toString(StandardCharsets.UTF_8.name()); }
Example 10
Source File: CreateSampleData.java From sldeditor with GNU General Public License v3.0 | 4 votes |
/** * Creates the attributes. * * @param fieldList the field list * @param fieldMap the field map * @param featureType the feature type * @param builder the builder * @param feature the feature */ private void createAttributes( List<DataSourceAttributeData> fieldList, Map<String, DataSourceAttributeData> fieldMap, SimpleFeatureType featureType, SimpleFeatureBuilder builder, SimpleFeature feature) { builder.init((SimpleFeature) feature); int index = 0; for (AttributeDescriptor descriptor : featureType.getAttributeDescriptors()) { AttributeType attributeType = descriptor.getType(); Object value = null; Class<?> fieldType = attributeType.getBinding(); if (attributeType instanceof GeometryTypeImpl) { geometryType = GeometryTypeMapping.getGeometryType(fieldType); switch (geometryType) { case POLYGON: ExamplePolygonInterface examplePolygon = DataSourceFactory.createExamplePolygon(null); value = examplePolygon.getPolygon(); break; case LINE: ExampleLineInterface exampleLine = DataSourceFactory.createExampleLine(null); value = exampleLine.getLine(); break; case POINT: default: ExamplePointInterface examplePoint = DataSourceFactory.createExamplePoint(null); value = examplePoint.getPoint(); break; } } else { if ((fieldList != null) && (index < fieldList.size())) { DataSourceAttributeData attrData = fieldMap.get(descriptor.getLocalName()); if (attrData != null) { value = attrData.getValue(); } } value = getFieldTypeValue( index, attributeType.getName().getLocalPart(), fieldType, value); } builder.add(value); index++; } }
Example 11
Source File: InLineFeatureModel.java From sldeditor with GNU General Public License v3.0 | 4 votes |
/** Adds the new column. */ public void addNewColumn() { if (featureCollection != null) { String attributeName = getUniqueAttributeName(); columnList.add(attributeName); // Populate field names SimpleFeatureTypeBuilder featureTypeBuilder = new SimpleFeatureTypeBuilder(); featureTypeBuilder.init(featureCollection.getSchema()); featureTypeBuilder.add(attributeName, String.class); SimpleFeatureType newFeatureType = featureTypeBuilder.buildFeatureType(); String typeName = userLayer.getInlineFeatureType().getTypeName(); try { SimpleFeatureSource featureSource = userLayer.getInlineFeatureDatastore().getFeatureSource(typeName); SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(newFeatureType); ArrayList<SimpleFeature> featureList = new ArrayList<>(); SimpleFeatureIterator it = featureSource.getFeatures().features(); try { while (it.hasNext()) { SimpleFeature sf = it.next(); sfb.addAll(sf.getAttributes()); sfb.add(new String("")); featureList.add(sfb.buildFeature(null)); } } finally { it.close(); } SimpleFeatureCollection collection = new ListFeatureCollection(newFeatureType, featureList); featureCollection = collection; cachedFeature = null; lastRow = -1; DataStore dataStore = DataUtilities.dataStore(collection); userLayer.setInlineFeatureDatastore(dataStore); userLayer.setInlineFeatureType(newFeatureType); } catch (IOException e) { ConsoleManager.getInstance().exception(this, e); } this.fireTableStructureChanged(); this.fireTableDataChanged(); if (parentObj != null) { parentObj.inlineFeatureUpdated(); } } }
Example 12
Source File: InLineFeatureModel.java From sldeditor with GNU General Public License v3.0 | 4 votes |
/** Adds the new feature. */ public void addNewFeature() { SimpleFeatureType featureType = userLayer.getInlineFeatureType(); String typeName = userLayer.getInlineFeatureType().getTypeName(); try { SimpleFeatureSource featureSource = userLayer.getInlineFeatureDatastore().getFeatureSource(typeName); SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(featureType); ArrayList<SimpleFeature> featureList = new ArrayList<>(); SimpleFeatureIterator it = featureSource.getFeatures().features(); try { while (it.hasNext()) { SimpleFeature sf = it.next(); List<Object> attributeValueList = sf.getAttributes(); sfb.addAll(attributeValueList); featureList.add(sfb.buildFeature(null)); } // Add new feature String wktString = "wkt://POINT(0 0)"; Geometry geometry = WKTConversion.convertToGeometry(wktString, getSelectedCRSCode()); sfb.add(geometry); featureList.add(sfb.buildFeature(null)); } finally { it.close(); } SimpleFeatureCollection collection = new ListFeatureCollection(featureType, featureList); featureCollection = collection; cachedFeature = null; lastRow = -1; DataStore dataStore = DataUtilities.dataStore(collection); userLayer.setInlineFeatureDatastore(dataStore); } catch (IOException e) { ConsoleManager.getInstance().exception(this, e); } this.fireTableStructureChanged(); this.fireTableDataChanged(); if (parentObj != null) { parentObj.inlineFeatureUpdated(); } }
Example 13
Source File: OSMUtils.java From traffic-engine with GNU General Public License v3.0 | 4 votes |
static public void toShapefile( List<SpatialDataItem> segs, String filename ) throws SchemaException, IOException { final SimpleFeatureType TYPE = DataUtilities.createType("Location", "the_geom:LineString:srid=4326," + "name:String" ); System.out.println("TYPE:"+TYPE); List<SimpleFeature> features = new ArrayList<SimpleFeature>(); /* * GeometryFactory will be used to create the geometry attribute of each feature, * using a Point object for the location. */ GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); for( SpatialDataItem seg : segs ){ featureBuilder.add( seg.getGeometry() ); featureBuilder.add( seg.id ); SimpleFeature feature = featureBuilder.buildFeature(null); features.add( feature ); } File newFile = new File( filename ); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", newFile.toURI().toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); /* * TYPE is used as a template to describe the file contents */ newDataStore.createSchema(TYPE); ContentFeatureSource cfs = newDataStore.getFeatureSource(); if (cfs instanceof SimpleFeatureStore) { SimpleFeatureStore featureStore = (SimpleFeatureStore) cfs; SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features); try { featureStore.addFeatures(collection); } catch (Exception problem) { problem.printStackTrace(); } finally { } } }
Example 14
Source File: OmsTrentoPProjectFilesGenerator.java From hortonmachine with GNU General Public License v3.0 | 4 votes |
private SimpleFeatureCollection createNewCollection( SimpleFeatureType simpleFeatureType ) { DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(); SimpleFeatureIterator stationsIter = pOldVector.features(); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(simpleFeatureType); // create the features. try { while( stationsIter.hasNext() ) { SimpleFeature networkFeature = stationsIter.next(); try { // add the geometry. builder.add(networkFeature.getDefaultGeometry()); // add the ID. Integer field = ((Integer) networkFeature.getAttribute(TrentoPFeatureType.ID_STR)); if (field == null) { throw new IllegalArgumentException(); } builder.add(field); // add the area. Double value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.DRAIN_AREA_STR)); if (value == null) { throw new IllegalArgumentException(); } builder.add(value); // add the percentage of the area which is dry. value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.PERCENTAGE_OF_DRY_AREA)); builder.add(value); // the pipes elevation is the elevation of the // terrain minus the depth. value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.DEPTH_INITIAL_PIPE_STR)); builder.add(value); // the pipes elevation is the elevation of the // terrain minus the depth. value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.DEPTH_FINAL_PIPE_STR)); builder.add(value); // add the runoff coefficent. value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.RUNOFF_COEFFICIENT_STR)); builder.add(value); // add the average residence time. value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.AVERAGE_RESIDENCE_TIME_STR)); builder.add(value); // add the ks. value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.KS_STR)); builder.add(value); // add the average slope. value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.AVERAGE_SLOPE_STR)); builder.add(value); // add the diameters. value = ((Double) networkFeature.getAttribute(TrentoPFeatureType.DIAMETER_STR)); builder.add(value); // build the feature SimpleFeature feature = builder.buildFeature(null); featureCollection.add(feature); } catch (NullPointerException e) { throw new IllegalArgumentException(); } } } finally { stationsIter.close(); } return featureCollection; }
Example 15
Source File: ShapefileTool.java From geowave with Apache License 2.0 | 4 votes |
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "Directories may alreadybe there") public static void writeShape(final String typeName, final File dir, final Geometry[] shapes) throws IOException { FileUtils.deleteDirectory(dir); dir.mkdirs(); final SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(createFeatureType(typeName, shapes[0] instanceof Point)); final ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); final Map<String, Serializable> params = new HashMap<>(); params.put("url", new File(dir.getAbsolutePath() + "/" + typeName + ".shp").toURI().toURL()); params.put("create spatial index", Boolean.TRUE); final ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); newDataStore.createSchema(createFeatureType(typeName, shapes[0] instanceof Point)); final Transaction transaction = new DefaultTransaction("create"); try (final FeatureWriter<SimpleFeatureType, SimpleFeature> writer = newDataStore.getFeatureWriterAppend(typeName, transaction)) { final int i = 1; for (final Geometry shape : shapes) { featureBuilder.add(shape); featureBuilder.add(Integer.valueOf(i)); final SimpleFeature feature = featureBuilder.buildFeature(null); final SimpleFeature copy = writer.next(); for (final AttributeDescriptor attrD : feature.getFeatureType().getAttributeDescriptors()) { // the null case should only happen for geometry if (copy.getFeatureType().getDescriptor(attrD.getName()) != null) { copy.setAttribute(attrD.getName(), feature.getAttribute(attrD.getName())); } } // shape files force geometry name to be 'the_geom'. So isolate // this change copy.setDefaultGeometry(feature.getDefaultGeometry()); writer.write(); } } catch (final IOException e) { LOGGER.warn("Problem with the FeatureWritter", e); transaction.rollback(); } finally { transaction.commit(); transaction.close(); } }