Extending a FeatureCollection by Adding new Attributes
Jump to navigation
Jump to search
The Problem
I imported a shapefile and put its contents in a jump FeatureCollection. With these Features I’m doing some calculations and now I want to add the result as a new attribute to the features, so I can export it as a new shapefile.
So basically I want to add a new field to attribute table and fill it with values.
But I just can’t figure it out! I played with with the addAttribute Method of the FeatureSchema, but that didn’t really work.
The Solution
you need to do the following:
- create a new FeatureSchema based on the old one
- create a new FeatureDataset with that FeatureSchema
- copy every feature from old to new FeatureSchema (use the function FeatureCollectionTools.copyFeatureAndSetFeatureSchema for this)
- add the features to the new FeatureSchema
- display
a code example can be found below
Another option, with respect to updating, may be to look on how the "View / Edit Schema"-Function from the mouse menu works (class: com.vividsolutions.jump.workbench.ui.plugin.ViewSchemaPlugIn)
Example
- the input is pFeatures
- I assume that this code is in the "run" or "execute" method of a plugin.
FeatureSchema fsNew=(FeatureSchema)pFeatures.getFeatureSchema().clone(); fsNew.addAttribute("huhuattribut",AttributeType.STRING); resultFC = new FeatureDataset(fsNew); //-- set the attribute for every feature in the collection for (Iterator iterator = pFeatures.iterator(); iterator.hasNext();) { Feature ftemp = (Feature) iterator.next(); //-- copies the original feature to the new feature schema Feature fcore = FeatureCollectionTools.copyFeatureAndSetFeatureSchema(ftemp, fsNew); //-- in case the geometry changed: fcore.setGeometry(core); //-- set the new attribute fcore.setAttribute("huhuattribut", "helloworld"); resultFC.add(fcore); } //-- display context.addLayer(StandardCategoryNames.RESULT, "newLayer", resultFC);