Creating map and saving it to image with GeoTools

Ian's answer is correct, and I have marked it as such. For the sake of completeness for anyone else that might be interested...


Question 1

No, you do not have to manually reproject layers. Specifying the projection on the viewport should suffice. Example:

    MapViewport vp = map.getViewport();
    CoordinateReferenceSystem crs = CRS.decode("EPSG:5070");
    vp.setCoordinateReferenceSystem(crs);

Question 2

In order to clip the map, you need to set the viewport bounds AND update the saveImage function. Here's an example of how to set the bounds to the projection extents:

    Extent crsExtent = crs.getDomainOfValidity();
    for (GeographicExtent element : crsExtent.getGeographicElements()) {
        if (element instanceof GeographicBoundingBox) {
            GeographicBoundingBox bounds = (GeographicBoundingBox) element;
            ReferencedEnvelope bbox = new ReferencedEnvelope(
                bounds.getSouthBoundLatitude(),
                bounds.getNorthBoundLatitude(),
                bounds.getWestBoundLongitude(),
                bounds.getEastBoundLongitude(),

                CRS.decode("EPSG:4326")
            );
            ReferencedEnvelope envelope = bbox.transform(crs, true);
            vp.setBounds(envelope);
        }
    }

In addition to setting the viewport bounds, the saveImage function should be modified to use the viewport bounds instead of map.getMaxBounds().

Change:

mapBounds = map.getMaxBounds();

To this:

mapBounds = map.getViewport().getBounds();

Here's the output:

US


Question 3

Thanks to Ian's suggestion, I was able to get the latitude lines to curve by densifying the line string. Here's the key snippit from the getGraticules() method referenced in the original post:

  //Add lines of latitude
    for (int y=-90; y<=90; y+=15){
        java.util.ArrayList<Coordinate> coords = new java.util.ArrayList<Coordinate>();
        for (double x=-135; x<=-45; x+=0.5){
            coords.add(new Coordinate(y,x,0));
        }
        LineString line = new LineString(coords.toArray(new Coordinate[coords.size()]), precisionModel, 4326);
        collection.add( SimpleFeatureBuilder.build( TYPE, new Object[]{ line }, null) );
    }

The output is as follows:

Output from reprojection 2

Although this approach works, I was hoping for a transform setting or something that would arc the lines for me.

Tags:

Geotools