Saturday, May 3, 2008

How to create a feature for an empty Udig layer

Assume you have a new created layer in your Udig workspace. Now you want to programmatically add a feature to it by just knowing its coordinates.

You will need to create a feature that adapts to the schema you layer will have.
I was used to take a feature from the layer, duplicate it and change attributes and geometry in the past. Oviously this isn't very nice and I finally found the limitation. So here is what to do if you have no feature to copy from.



FeatureSource source = layer
.getResource(FeatureSource.class, new NullProgressMonitor());
if (source == null) {
throw new LayerNotSupportedException(
"This layer is not supported, only feature layers are supported.");
}
// get the featurecollection from the layer, even if empty
FeatureCollection selectedFeatureCollection = source.getFeatures();
/*
* in this case the feature has to be created on the blueprint of the layer's
* features, asking the user for the new attributes to use. Note that getFeatureType
* here doesn't supply hwat you want.
*/
FeatureType featureType = selectedFeatureCollection.getSchema();
/*
* try to create default features where possible
*/
Object attributes[] = DataUtilities.defaultValues(featureType);
/*
* geometry is not created as default, so add yours
*/
attributes[0] = gFac.createPoint(new Coordinate(0.0, 0.0));
featureToUse = featureType.create(attributes);

Feature is created.

No comments: