Tuesday, May 24, 2011

Geotools MapRender 900913 Mercator

Back again to the Geotools, i decided to build my own tile builder using
specific cartography.
To achieve this I googled a lot, and few answers were useful. So to make this easier for anybody who intends to make it work, here's a little description of my problem.
"Need to render a map using the Spherical Mercator EPSG:900913 (EPSG:3857) using Geotools2.7.1"

1. first than all, let's use some existing data from Udig-data: http://udig.refractions.net/docs/data-v1_2.zip
2. I assume that already hav the Geotools2.7.1 API
3. Here's a code snippet to render a map: http://docs.geotools.org/latest/userguide/library/render/gtrenderer.html
4. Need to add some new parameters to support the correct reprojection of the map:

  1. Map rendererParams = new HashMap();

  2. rendererParams.put(StreamingRenderer.OPTIMIZED_DATA_LOADING_KEY, true);

  3. rendererParams.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, isLineWidthOptimizationEnabled());

  4. //to support the mercator projection

  5. //turn on advanced projection handling

  6. rendererParams.put(StreamingRenderer.ADVANCED_PROJECTION_HANDLING_KEY, true);

  7. rendererParams.put(StreamingRenderer.CONTINUOUS_MAP_WRAPPING, true);

  8. //Add more parameters if needed

  9. renderer.setRendererHints(rendererParams);


5. It's very important to do what Andr
ea Aime says here: http://www.mail-archive.com/geotools-gt2-users@lists.sourceforge.net/msg04934.html.
"Check you feature source, if the default geometry in the feature type has no srs information set, no reprojection will occurr."
6. Finally the following code snippet will works perfectly to reproject from WGS84 to Spherical Mercator EPSG:900913:

  1. CoordinateReferenceSystem crs = CRS.decode("EPSG:900913");

  2. MapRenderer render = new StreamingMapRenderer(crs);

  3. render.setMapWidth(800);

  4. render.setMapHeight(800);

  5. render.setAreaOfInterest(new Envelope(-20037508,20037508,-20037508,20037508));

  6. DataStore ds = new ShapefileDataStore(new File("data/4326/countries.shp").toURI().toURL());

  7. render.addLayer(MapLayers.createStyledLayer(ds.getFeatureSource("countries")));

  8. RenderableWriter w = WriterFactory.findWriter("png");
  1. w.writeTo(new FileOutputStream("countries900913.png"), render);


RenderableWriter, WriterFactory, MapRenderer and StreamingRenderer are some interfaces and classes that does everything described above. StreamingRenderer is the most important and part of the code necessary to pr
oduce the reprojected image is listed at point 4.


Enjoy the result!!

No comments: