Add feature to existing layer in Geotools

2.1k views Asked by At

I add a layer to a Geotools MapPane, consisting of various WKT String features. The layer is displayed correctly. Now, at the click of a button on the UI, I want to add another feature to this layer.

Initially, I create the layer and display it using the following:

List<SimpleFeature> list  = featuresFromWkt(wktString, name); //method name explains what it does..
ListFeatureCollection col = new ListFeatureCollection(getFeatureType(), list); 
Color color = Color.BLUE;
Style style = SLD.createPolygonStyle(color, color.brighter(), 0.5f);
FeatureLayer layer = new FeatureLayer(col, style);
layer.setVisible(true);
layer.setTitle(name);
mapContent.layers().add(layer)

Now, to add something to the layer, I get the layer from the content, using:

FeatureLayer layer = (FeatureLayer) mapContent.layers().get(0);

I can now use layer.getSimpleFeatureSource() to retrieve the source, but there seems to be no way to cast this source back to something I can call a .addFeature(someNewFeature) on to add something to the map.

I can keep a reference to the ListFeatureCollection and use that to add new features, but I would prefer to only use the mapConent.layers.get(layerNumber) approach and then use the layer to add stuff.

All the samples I have seen thus far just add another layer with the new features. I do not want to add another layer, rather just add something to the existing layer, of which the content sits in memory. Am I missing something here? Is there a GeoTools class I am not aware of?

1

There are 1 answers

2
cello On BEST ANSWER

Have a look at http://osgeo-org.1560.x6.nabble.com/Adding-geometry-to-layer-td4324729.html. This sounds very similar to your problem and was asked a while ago on the GeoTools mailing list.

Basic idea, in case the mailing list archive linked above becomes unavailable at some point in time:

  • Create a feature collection containing your features (might be empty initially)
  • add this feature collection to a map layer
  • add features later to the feature collection.

According to the statement on the mailing list: "The map pane should repaint automagically when you add features to the collection (there is a chain of events sent from the feature collection to the map layer to the layer list to the map pane)"