[GIS] Create a color scale/legend for choropleth map using geotools (or other open source Java library)

geotoolsjavalegendopen-source-gis

I'm experimenting with choropleth maps using geotools.

Is there an easy way to add a color scale to the map (using geotools itself or some other os library)? By a color scale I mean a bar that shows how the feature attribute values map to color, with labeled ticks either automatically generated, or at break points of my choosing.

Ideally, I'd like to generate a separate color scale that could be rendered independently of the choropleth map, so that I can use a single color with layouts containing multiple maps.

I'm not absolutely wedded to geotools, and would consider other open source libraries, though I'd much prefer to stick with JVM languages (Clojure, Groovy, Java, …).

Best Answer

Assuming that you know what colours you want and how many classes there are, (i.e. you can parse the SLD file) this is a simple case of looping through the list of colours and rule titles and drawing a small square of the right colour and printing the title next to it on a BufferedImage or suchlike. So something like the following could work:

BufferImage img = new ....;
Graphics2D g = img.getGraphics2D();
for(int i=0;i<nClasses;i++){
   g.setColor(colors[i];
   g.drawRect(0,i*25,20,20);
   g.drawString(title[i],30,i*25);
}

If you want to do anything more complex then have a look at how GeoServer does it in BufferedImageLegendGraphicBuilder