stevenhz
stevenhz

Reputation: 57

display legend with Geotools JMapFrame

Shall anybody give some tips on how to display a legend for a shapefile in JMapFrame of Geotools? I have already created the style for the shapefile and I need a way to tell the users how the style is defined, that comes out the need of legend.

There is a package org.geotools.legend. But I do not know how to use it.

Thanks!

Upvotes: 2

Views: 446

Answers (1)

Ian Turton
Ian Turton

Reputation: 10976

You need to iterate through the Styles FeatureTypeStyless Rules Symbolizers and draw a representative feature for each one. Something like:

private void drawLegend(BufferedImage img, Rule r) {
    for (Symbolizer sym : r.symbolizers()) {
      SimpleFeature feature = null;
      if (sym instanceof LineSymbolizer) {
        LineString line = drawer.line(new int[] { 1, 1, 10, 20, 20, 20 });
        feature = drawer.feature(line);
      } else if(sym instanceof PolygonSymbolizer) {
        Polygon  p = drawer.polygon(new int[] { 1, 1, 1, 18, 18, 18, 18, 1, 1,1 });
        feature = drawer.feature(p);
      } else if(sym instanceof PointSymbolizer || sym instanceof TextSymbolizer) {
        Point p = drawer.point(10, 10);
        feature = drawer.feature(p);
      } 
      if(feature == null)
        continue;
      drawer.drawDirect(img, feature, r);
      Graphics2D gr = img.createGraphics();
      gr.setColor(Color.BLACK);
      if (r.getDescription() != null && r.getDescription().getTitle() != null) {
        gr.drawString(r.getDescription().getTitle().toString(), 20, 18);
      }
    }
  }

And then you can draw those images to a JPanel or the map.

For a fully worked example see how GeoServer creates the response to a getLegendGraphic request.

Upvotes: 2

Related Questions