Hello!

      I'am stuck trying to render map in mercator projection.
Whatever i try geotools is not rendering in any other projection than
which you can see on image http://ds.azcltd.com/quickStart/geotools_QuickStart.jpg (I don't know what projection it is). As you can see this image does'not
look even a bit like mercator. (For demonstration another image
http://ds.azcltd.com/quickStart/google_mercator.jpg - google maps screenshot - that is example of projection I want to have)

I spent really lots of time! I read lots of documentations, mailing
lists... I do not know what I am doing wrong! StreamingRenderer alwayl
produce same result! I tryed many variants of WKT - result is the same.
Please, help me to solve this problem

I use geotools 2.4.1.
I have attached my source's main file QuickStart.java.
whole test project is available at http://ds.azcltd.com/quickStart/QuickStart.zip - approximately 36 kbytes (it consists of 5 java files and 3 resource files. )

Please, help me!

ps: I know that my english is not so good... So, excuse me for that.







package com.azoft;

import com.vividsolutions.jts.geom.Envelope;
import org.geotools.filter.IllegalFilterException;
import org.geotools.gui.swing.*;
import org.geotools.map.DefaultMapContext;
import org.geotools.map.MapContext;
import org.geotools.referencing.CRS;
import org.geotools.referencing.FactoryFinder;
import org.geotools.renderer.GTRenderer;
import org.geotools.renderer.lite.StreamingRenderer;
import org.geotools.styling.*;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CRSFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class QuickStart {
    //GUI frame, pane and extras
    static JFrame frame;
    static JMapPane jmp;
    static JToolBar jtb;
    static JLabel text;

    //Display elements
    static MapContext context;
    static GTRenderer renderer;
    static com.vividsolutions.jts.geom.Envelope worldbounds;



    /**
     * Create a GUI map displayer.
     * <p/>
     * This is all Swing stuff for the JMapPane.
     */
    public static void initGUI() {
        frame = new JFrame("My Map Viewer");
//        frame.setBounds(20,20,500,310);
        frame.setBounds(20, 20, 1080, 600);
        frame.setBackground(Color.cyan);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container content = frame.getContentPane();
        content.setBackground(Color.magenta);
        content.setLayout(new BorderLayout());
//        content.setLayout(new GridLayout(1,2 ));

//        jmpp = new JMapPane();
        jmp = new JMapPane();
        jmp.setBackground(Color.white);
//        jmp.setSize(20,100);
        //jmp.addZoomChangeListener(this);

/* TODO: Fix this TOOLBAR STUFF BELOW: */
        content.setLayout(new BorderLayout());
        jtb = new JToolBar();
        Action zoomIn = new ZoomInAction(jmp);
        Action zoomOut = new ZoomOutAction(jmp);
        Action pan = new PanAction(jmp);
        Action select = new SelectAction(jmp);
        Action reset = new ResetAction(jmp);
        jtb.add(zoomIn);
        jtb.add(zoomOut);
        jtb.add(pan);
        jtb.addSeparator();
        jtb.add(reset);
        jtb.addSeparator();
        jtb.add(select);
        final JButton button = new JButton();
        button.setText("CRS");
        button.setToolTipText("Change map prjection");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String code = JOptionPane.showInputDialog(button, "Coordinate 
Reference System:", "EPSG:4326");
                try {
//                 CoordinateReferenceSystem crs = CRS.decode( code );
                    CoordinateReferenceSystem crs = CRS.parseWKT(code);
                    System.out.println("crs = '" + crs + "'");
                    
jmp.getContext().setAreaOfInterest(jmp.getContext().getAreaOfInterest(), crs);
                    jmp.setReset(true);
                    jmp.repaint();

                }
                catch (FactoryException fe) {
                    JOptionPane.showMessageDialog(button, fe.getMessage(), 
fe.getClass().toString(), JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
        });
        jtb.add(button);

        content.add(jtb, BorderLayout.NORTH);
/* TOOLBAR STUFF ABOVE */

        content.add(jmp, BorderLayout.CENTER);
//        content.add(jmp);

        content.doLayout();
        frame.setVisible(true);

    }


    private static double FACTOR = (double) 580 / (double) 420;
    private static double oneKilometer = ((90. / 10000.) / FACTOR);
    private static double MIN_SCALE_FACTOR = 0.11622 / oneKilometer;
    private static double MAX_SCALE_FACTOR = 0.11624 / oneKilometer;
    private static final double googleMaxZoom = 65000;
    private static final double[] zoomLevels = {
            googleMaxZoom / 1048576, googleMaxZoom / 524288,
            googleMaxZoom / 262144, googleMaxZoom / 131072, googleMaxZoom / 
65536, googleMaxZoom / 32768,
            googleMaxZoom / 16384, googleMaxZoom / 8192, googleMaxZoom / 4096, 
googleMaxZoom / 2048,
            googleMaxZoom / 1024, googleMaxZoom / 512, googleMaxZoom / 256, 
googleMaxZoom / 128,
            googleMaxZoom / 64, googleMaxZoom / 32, googleMaxZoom / 16, 
googleMaxZoom / 8,
            googleMaxZoom / 4, googleMaxZoom / 2, googleMaxZoom};

    private static final List<MapLayer> mapLayers = new ArrayList<MapLayer>();

    private static void loadMapLayers(String mapLayersXmlPath) throws 
IOException, IllegalFilterException {
        final String destinationCharset = "cp1251";

        DocumentBuilderFactory domFactory = 
DocumentBuilderFactory.newInstance();
        domFactory.setValidating(false);

        try {
            double eps = 1e-10;
            DocumentBuilder builder = domFactory.newDocumentBuilder();

            Document doc = builder.parse("resources/MapLayers.xml");

//            String rootDir = QuickStart.class.getResource("/").toString();

            NodeList mapLayerTags = doc.getElementsByTagName("MapLayer");
            for (int i = 0; i < mapLayerTags.getLength(); i++) {
                Node mapLayerTag = mapLayerTags.item(i);
                String path = 
mapLayerTag.getAttributes().getNamedItem("path").getTextContent();
                int maxScaleNum = (int) 
Double.parseDouble(mapLayerTag.getAttributes().getNamedItem("maxScaleNum").getTextContent());
                double priority = 
Double.parseDouble(mapLayerTag.getAttributes().getNamedItem("priority").getTextContent());
                String type = 
mapLayerTag.getAttributes().getNamedItem("type").getTextContent();
                String sorceCharset = 
mapLayerTag.getAttributes().getNamedItem("sorceCharset").getTextContent();

                SourceData source;
//                if ("SourceShapefilesFromArcSde".equals(type)) {
//                    source = new SourceShapefilesFromArcSde(rootDir + path, 
sorceCharset, destinationCharset);
//                } else if ("SourceMPfiles".equals(type)) {
                source = new SourceMPfiles(path, sorceCharset, 
destinationCharset);
//                } else if ("SourceShapefiles".equals(type)) {
//                    source = new SourceShapefiles(rootDir + path, 
sorceCharset, destinationCharset);
//                } else {
//                    throw new IllegalArgumentException("Unknown MapLayer 
type");
//                }

                System.out.println("======Creating MapLayer from: '" + 
source.getPath() + "'");

                List<Layer> layers = new ArrayList<Layer>();
                NodeList layerTags = mapLayerTag.getChildNodes();
                for (int j = 0; j < layerTags.getLength(); j++) {
                    Node layerTag = layerTags.item(j);
                    if (!"Layer".equals(layerTag.getNodeName())) {
                        continue;
                    }

                    String file = 
layerTag.getAttributes().getNamedItem("file").getTextContent();
                    String filter = 
layerTag.getAttributes().getNamedItem("filter").getTextContent();
                    String pathToStyle = 
layerTag.getAttributes().getNamedItem("pathToStyle").getTextContent();
                    try {
                        layers.add(new Layer(source, file, filter,
//                                createStyle(servletContext, 
servletContext.getRealPath(pathToStyle)),
                                createStyle(pathToStyle),
                                pathToStyle));
                    } catch (Throwable e) {
                        System.out.println("Can not create Layer[" + 
source.getPath() + ", " + file + ", " + filter + ", " + pathToStyle + "]");
                    }
                }

//                mapLayersManager.addLayer(new MapLayer(source.getPath(), 
layers, zoomLevels[maxScaleNum] + eps, priority));
                mapLayers.add(new MapLayer(source.getPath(), layers, 
zoomLevels[maxScaleNum] + eps, priority));

                System.out.println("======/MapLayer from: '" + source.getPath() 
+ "' successfully created.");
            }
        } catch (ParserConfigurationException e) {
            throw new IllegalArgumentException("'" + mapLayersXmlPath + "' is 
invalid!", e);
        } catch (SAXException e) {
            throw new IllegalArgumentException("'" + mapLayersXmlPath + "' is 
invalid!", e);
        }
    }

    private static Style createStyle(String path) throws IOException {
        SLDParser sldParser = new SLDParser(new 
StyleBuilder().getStyleFactory());

        File f = new File(path);
//        log.info("Loading style from: '" + f.getPath() + "'");
        FileReader is = new FileReader(f);
        BufferedReader br = new BufferedReader(is);

        String styleXml = "", line, link = "xlink:href=\"";
        //setup links on images
        while ((line = br.readLine()) != null) {
            int ind = line.indexOf(link);
            if (ind >= 0) {
                String tmp = line.substring(ind + link.length());
                int ind2 = tmp.indexOf("\"");
                if (ind2 >= 0) {
                    tmp = tmp.substring(0, ind2);
//                    String realPath = servletContext.getResource("/" + 
tmp).toString();
                    String realPath = "resources/" + tmp;
                    line = line.replace(tmp, realPath);
                }
            }
            styleXml += line;
        }
        br.close();
        is.close();

        sldParser.setInput(new StringReader(styleXml));
        Style style = sldParser.readXML()[0];

        //setup MinScaleDenominator and MaxScaleDenominator
        for (FeatureTypeStyle featureTypeStyle : style.getFeatureTypeStyles()) {
            if (featureTypeStyle == null || featureTypeStyle.getRules() == 
null) {
                continue;
            }
            for (Rule rule : featureTypeStyle.getRules()) {
                if (rule == null) {
                    continue;
                }
                double min = rule.getMinScaleDenominator();
                double max = rule.getMaxScaleDenominator();
                int minI = (int) min, maxI = (int) max;
                minI = zoomLevels.length <= minI ? zoomLevels.length - 1 : minI 
< 0 ? 0 : minI;
                maxI = zoomLevels.length <= maxI ? zoomLevels.length - 1 : maxI 
< 0 ? 0 : maxI;
                rule.setMinScaleDenominator(zoomLevels[minI] * 
MIN_SCALE_FACTOR);
                rule.setMaxScaleDenominator(zoomLevels[maxI] * 
MAX_SCALE_FACTOR);
//                rule.setMaxScaleDenominator(zoomLevels[zoomLevels.length-1] * 
RenderConst.MAX_SCALE_FACTOR);
//                rule.setMinScaleDenominator(0);
//                rule.setMaxScaleDenominator(1e25);
            }
        }
        return style;
    }

    /**
     * Display features onto the screen.
     * <p/>
     * This is a very crude example, showing only how do display a map. The
     * core class, JMapPane, also has a toolbar which is not shown here. See
     * the demo/gui for more details.
     */
    public static void loadGUI() throws Exception {

        //Setup the context and renderer within the jmappane
        context = new DefaultMapContext(); //WGS84 by default //TODO: make 
mercator
        //Trying to make Mercator
        CRSFactory crsFactory = FactoryFinder.getCRSFactory(null);
        String wkt = "PROJCS[\"Mercator_1SP\", "
                + "GEOGCS[\"WGS84\", "
                + "DATUM[\"WGS84\", "
                + "SPHEROID[\"WGS84\", 6378137.0, 298.257223563]], "
                + "PRIMEM[\"Greenwich\", 0.0], "
                + "UNIT[\"degree\",0.017453292519943295], "
                + "AXIS[\"Longitude\",EAST], "
                + "AXIS[\"Latitude\",NORTH]], "
                + "PROJECTION[\"Mercator_1SP\"], "
                + "PARAMETER[\"semi_major\", 6378137.0], "
                + "PARAMETER[\"semi_minor\", 6356752.314245179], "
                + "PARAMETER[\"central_meridian\", 0.0], "
                + "PARAMETER[\"scale_factor\", 1.0], "
                + "PARAMETER[\"false_easting\", 0.0], "
                + "PARAMETER[\"false_northing\", 0.0], "
                + "UNIT[\"metre\",1.0], "
                + "AXIS[\"x\",EAST], "
                + "AXIS[\"y\",NORTH]]";
        CoordinateReferenceSystem prjCRS = null;
        try {
            prjCRS = crsFactory.createFromWKT(wkt);
            System.out.println("prjCRS = '" + prjCRS + "'");
        } catch (FactoryException fe) {
            System.err.println("On prjCRS creation a FactoryException :" + 
fe.getMessage());
        }
        Envelope e = new Envelope(-170.0, 170.0, -80.0, 80.0);
        context.setAreaOfInterest(e, prjCRS);


        renderer = new StreamingRenderer();
        jmp.setRenderer(renderer);
        jmp.setContext(context);

        //Add the data directly to the context (which makes the MapLayers)
        for (MapLayer mapLayer : mapLayers) {
            mapLayer.applyLayer(context);
        }

        //Set boundary to all that's visible
        jmp.setMapArea(context.getLayerBounds());
//        jmp.setMapArea(e);

        jmp.setHighlightLayer(context.getLayer(0));

//        jmp.setSize(200,600);
        frame.repaint();
        frame.doLayout();
//        Thread.sleep(5000);
//        jmp.setSize(200,600);
//        frame.repaint();
//        frame.doLayout();

    }

    /**
     * This is main() the only real function in this QuickStart tutorial.
     * The class works sequentially through every step
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        System.out.println("QuickStart: Tutorial Start...");

        System.out.println("\tStart: Create FeatureSource from scratch.");
        loadMapLayers("");
        System.out.println("\t  End: Created FeatureSource from scratch.");

        System.out.println("\tStart: Initialize the GUI.");
        initGUI();
        System.out.println("\t  End: Initialized the GUI.");

        System.out.println("\tStart: Load the map.");
        loadGUI();
        System.out.println("\t  End: Loaded the map.");

        System.out.println("QuickStart: Tutorial End.");
    }

}
-------------------------------------------------------------------------
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://ad.doubleclick.net/clk;164216239;13503038;w?http://sf.net/marketplace
_______________________________________________
Geotools-gt2-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/geotools-gt2-users

Reply via email to